babylon.viewer.max.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477
  1. (function universalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define("babylonjs-viewer", [], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-viewer"] = factory();
  8. else {
  9. root["BabylonViewer"] = factory(root["BABYLON"]);
  10. }
  11. })(this, function() {
  12. var BabylonViewer =
  13. /******/ (function(modules) { // webpackBootstrap
  14. /******/ // The module cache
  15. /******/ var installedModules = {};
  16. /******/
  17. /******/ // The require function
  18. /******/ function __webpack_require__(moduleId) {
  19. /******/
  20. /******/ // Check if module is in cache
  21. /******/ if(installedModules[moduleId]) {
  22. /******/ return installedModules[moduleId].exports;
  23. /******/ }
  24. /******/ // Create a new module (and put it into the cache)
  25. /******/ var module = installedModules[moduleId] = {
  26. /******/ i: moduleId,
  27. /******/ l: false,
  28. /******/ exports: {}
  29. /******/ };
  30. /******/
  31. /******/ // Execute the module function
  32. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  33. /******/
  34. /******/ // Flag the module as loaded
  35. /******/ module.l = true;
  36. /******/
  37. /******/ // Return the exports of the module
  38. /******/ return module.exports;
  39. /******/ }
  40. /******/
  41. /******/
  42. /******/ // expose the modules object (__webpack_modules__)
  43. /******/ __webpack_require__.m = modules;
  44. /******/
  45. /******/ // expose the module cache
  46. /******/ __webpack_require__.c = installedModules;
  47. /******/
  48. /******/ // define getter function for harmony exports
  49. /******/ __webpack_require__.d = function(exports, name, getter) {
  50. /******/ if(!__webpack_require__.o(exports, name)) {
  51. /******/ Object.defineProperty(exports, name, {
  52. /******/ configurable: false,
  53. /******/ enumerable: true,
  54. /******/ get: getter
  55. /******/ });
  56. /******/ }
  57. /******/ };
  58. /******/
  59. /******/ // getDefaultExport function for compatibility with non-harmony modules
  60. /******/ __webpack_require__.n = function(module) {
  61. /******/ var getter = module && module.__esModule ?
  62. /******/ function getDefault() { return module['default']; } :
  63. /******/ function getModuleExports() { return module; };
  64. /******/ __webpack_require__.d(getter, 'a', getter);
  65. /******/ return getter;
  66. /******/ };
  67. /******/
  68. /******/ // Object.prototype.hasOwnProperty.call
  69. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  70. /******/
  71. /******/ // __webpack_public_path__
  72. /******/ __webpack_require__.p = "";
  73. /******/
  74. /******/ // Load entry module and return exports
  75. /******/ return __webpack_require__(__webpack_require__.s = 14);
  76. /******/ })
  77. /************************************************************************/
  78. /******/ ([
  79. /* 0 */
  80. /***/ (function(module, exports, __webpack_require__) {
  81. /* WEBPACK VAR INJECTION */(function(global) {var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  82. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  83. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  84. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  85. return c > 3 && r && Object.defineProperty(target, key, r), r;
  86. };
  87. var __extends = (this && this.__extends) || (function () {
  88. var extendStatics = Object.setPrototypeOf ||
  89. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  90. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91. return function (d, b) {
  92. extendStatics(d, b);
  93. function __() { this.constructor = d; }
  94. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  95. };
  96. })();
  97. (function universalModuleDefinition(root, factory) {
  98. if(true)
  99. module.exports = factory();
  100. else if(typeof define === 'function' && define.amd)
  101. define("babylonjs", [], factory);
  102. else if(typeof exports === 'object')
  103. exports["babylonjs"] = factory();
  104. else {
  105. root["BABYLON"] = factory(root["BABYLON"]);
  106. }
  107. })(this, function() {
  108. var BABYLON;
  109. (function (BABYLON) {
  110. /**
  111. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  112. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  113. */
  114. var EffectFallbacks = /** @class */ (function () {
  115. function EffectFallbacks() {
  116. this._defines = {};
  117. this._currentRank = 32;
  118. this._maxRank = -1;
  119. }
  120. /**
  121. * Removes the fallback from the bound mesh.
  122. */
  123. EffectFallbacks.prototype.unBindMesh = function () {
  124. this._mesh = null;
  125. };
  126. /**
  127. * Adds a fallback on the specified property.
  128. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  129. * @param define The name of the define in the shader
  130. */
  131. EffectFallbacks.prototype.addFallback = function (rank, define) {
  132. if (!this._defines[rank]) {
  133. if (rank < this._currentRank) {
  134. this._currentRank = rank;
  135. }
  136. if (rank > this._maxRank) {
  137. this._maxRank = rank;
  138. }
  139. this._defines[rank] = new Array();
  140. }
  141. this._defines[rank].push(define);
  142. };
  143. /**
  144. * Sets the mesh to use CPU skinning when needing to fallback.
  145. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  146. * @param mesh The mesh to use the fallbacks.
  147. */
  148. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  149. this._mesh = mesh;
  150. if (rank < this._currentRank) {
  151. this._currentRank = rank;
  152. }
  153. if (rank > this._maxRank) {
  154. this._maxRank = rank;
  155. }
  156. };
  157. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  158. /**
  159. * Checks to see if more fallbacks are still availible.
  160. */
  161. get: function () {
  162. return this._currentRank <= this._maxRank;
  163. },
  164. enumerable: true,
  165. configurable: true
  166. });
  167. /**
  168. * Removes the defines that shoould be removed when falling back.
  169. * @param currentDefines defines the current define statements for the shader.
  170. * @param effect defines the current effect we try to compile
  171. * @returns The resulting defines with defines of the current rank removed.
  172. */
  173. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  174. // First we try to switch to CPU skinning
  175. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  176. this._mesh.computeBonesUsingShaders = false;
  177. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  178. var scene = this._mesh.getScene();
  179. for (var index = 0; index < scene.meshes.length; index++) {
  180. var otherMesh = scene.meshes[index];
  181. if (!otherMesh.material) {
  182. continue;
  183. }
  184. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  185. continue;
  186. }
  187. if (otherMesh.material.getEffect() === effect) {
  188. otherMesh.computeBonesUsingShaders = false;
  189. }
  190. else {
  191. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  192. var subMesh = _a[_i];
  193. var subMeshEffect = subMesh.effect;
  194. if (subMeshEffect === effect) {
  195. otherMesh.computeBonesUsingShaders = false;
  196. break;
  197. }
  198. }
  199. }
  200. }
  201. }
  202. else {
  203. var currentFallbacks = this._defines[this._currentRank];
  204. if (currentFallbacks) {
  205. for (var index = 0; index < currentFallbacks.length; index++) {
  206. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  207. }
  208. }
  209. this._currentRank++;
  210. }
  211. return currentDefines;
  212. };
  213. return EffectFallbacks;
  214. }());
  215. BABYLON.EffectFallbacks = EffectFallbacks;
  216. /**
  217. * Options to be used when creating an effect.
  218. */
  219. var EffectCreationOptions = /** @class */ (function () {
  220. function EffectCreationOptions() {
  221. }
  222. return EffectCreationOptions;
  223. }());
  224. BABYLON.EffectCreationOptions = EffectCreationOptions;
  225. /**
  226. * Effect containing vertex and fragment shader that can be executed on an object.
  227. */
  228. var Effect = /** @class */ (function () {
  229. /**
  230. * Instantiates an effect.
  231. * An effect can be used to create/manage/execute vertex and fragment shaders.
  232. * @param baseName Name of the effect.
  233. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  234. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  235. * @param samplers List of sampler variables that will be passed to the shader.
  236. * @param engine Engine to be used to render the effect
  237. * @param defines Define statements to be added to the shader.
  238. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  239. * @param onCompiled Callback that will be called when the shader is compiled.
  240. * @param onError Callback that will be called if an error occurs during shader compilation.
  241. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  242. */
  243. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  244. if (samplers === void 0) { samplers = null; }
  245. if (defines === void 0) { defines = null; }
  246. if (fallbacks === void 0) { fallbacks = null; }
  247. if (onCompiled === void 0) { onCompiled = null; }
  248. if (onError === void 0) { onError = null; }
  249. var _this = this;
  250. /**
  251. * Unique ID of the effect.
  252. */
  253. this.uniqueId = 0;
  254. /**
  255. * Observable that will be called when the shader is compiled.
  256. */
  257. this.onCompileObservable = new BABYLON.Observable();
  258. /**
  259. * Observable that will be called if an error occurs during shader compilation.
  260. */
  261. this.onErrorObservable = new BABYLON.Observable();
  262. /**
  263. * Observable that will be called when effect is bound.
  264. */
  265. this.onBindObservable = new BABYLON.Observable();
  266. this._uniformBuffersNames = {};
  267. this._isReady = false;
  268. this._compilationError = "";
  269. this.name = baseName;
  270. if (attributesNamesOrOptions.attributes) {
  271. var options = attributesNamesOrOptions;
  272. this._engine = uniformsNamesOrEngine;
  273. this._attributesNames = options.attributes;
  274. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  275. this._samplers = options.samplers;
  276. this.defines = options.defines;
  277. this.onError = options.onError;
  278. this.onCompiled = options.onCompiled;
  279. this._fallbacks = options.fallbacks;
  280. this._indexParameters = options.indexParameters;
  281. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  282. if (options.uniformBuffersNames) {
  283. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  284. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  285. }
  286. }
  287. }
  288. else {
  289. this._engine = engine;
  290. this.defines = defines;
  291. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  292. this._samplers = samplers;
  293. this._attributesNames = attributesNamesOrOptions;
  294. this.onError = onError;
  295. this.onCompiled = onCompiled;
  296. this._indexParameters = indexParameters;
  297. this._fallbacks = fallbacks;
  298. }
  299. this.uniqueId = Effect._uniqueIdSeed++;
  300. if (this._getFromCache(baseName)) {
  301. this._prepareEffect();
  302. return;
  303. }
  304. var vertexSource;
  305. var fragmentSource;
  306. if (baseName.vertexElement) {
  307. vertexSource = document.getElementById(baseName.vertexElement);
  308. if (!vertexSource) {
  309. vertexSource = baseName.vertexElement;
  310. }
  311. }
  312. else {
  313. vertexSource = baseName.vertex || baseName;
  314. }
  315. if (baseName.fragmentElement) {
  316. fragmentSource = document.getElementById(baseName.fragmentElement);
  317. if (!fragmentSource) {
  318. fragmentSource = baseName.fragmentElement;
  319. }
  320. }
  321. else {
  322. fragmentSource = baseName.fragment || baseName;
  323. }
  324. var finalVertexCode;
  325. this._loadVertexShaderAsync(vertexSource)
  326. .then(function (vertexCode) {
  327. return _this._processIncludesAsync(vertexCode);
  328. })
  329. .then(function (vertexCodeWithIncludes) {
  330. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  331. return _this._loadFragmentShaderAsync(fragmentSource);
  332. })
  333. .then(function (fragmentCode) {
  334. return _this._processIncludesAsync(fragmentCode);
  335. })
  336. .then(function (fragmentCodeWithIncludes) {
  337. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  338. if (baseName) {
  339. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  340. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  341. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  342. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  343. }
  344. else {
  345. _this._vertexSourceCode = finalVertexCode;
  346. _this._fragmentSourceCode = migratedFragmentCode;
  347. }
  348. _this._setInCache(baseName);
  349. _this._prepareEffect();
  350. });
  351. }
  352. Effect.prototype._getSourceCacheKey = function (baseName) {
  353. var cacheKey = baseName;
  354. if (this._indexParameters) {
  355. for (var key in this._indexParameters) {
  356. if (this._indexParameters.hasOwnProperty(key)) {
  357. cacheKey += "|";
  358. cacheKey += key;
  359. cacheKey += "_";
  360. cacheKey += this._indexParameters[key];
  361. }
  362. }
  363. }
  364. return cacheKey;
  365. };
  366. Effect.prototype._getFromCache = function (baseName) {
  367. if (typeof baseName !== "string") {
  368. return false;
  369. }
  370. var cacheKey = this._getSourceCacheKey(baseName);
  371. var sources = Effect._sourceCache[cacheKey];
  372. if (!sources) {
  373. return false;
  374. }
  375. this._vertexSourceCode = sources.vertex;
  376. this._fragmentSourceCode = sources.fragment;
  377. return true;
  378. };
  379. Effect.prototype._setInCache = function (baseName) {
  380. if (typeof baseName !== "string") {
  381. return;
  382. }
  383. var cacheKey = this._getSourceCacheKey(baseName);
  384. Effect._sourceCache[cacheKey] = {
  385. vertex: this._vertexSourceCode,
  386. fragment: this._fragmentSourceCode
  387. };
  388. };
  389. Object.defineProperty(Effect.prototype, "key", {
  390. /**
  391. * Unique key for this effect
  392. */
  393. get: function () {
  394. return this._key;
  395. },
  396. enumerable: true,
  397. configurable: true
  398. });
  399. /**
  400. * If the effect has been compiled and prepared.
  401. * @returns if the effect is compiled and prepared.
  402. */
  403. Effect.prototype.isReady = function () {
  404. return this._isReady;
  405. };
  406. /**
  407. * The engine the effect was initialized with.
  408. * @returns the engine.
  409. */
  410. Effect.prototype.getEngine = function () {
  411. return this._engine;
  412. };
  413. /**
  414. * The compiled webGL program for the effect
  415. * @returns the webGL program.
  416. */
  417. Effect.prototype.getProgram = function () {
  418. return this._program;
  419. };
  420. /**
  421. * The set of names of attribute variables for the shader.
  422. * @returns An array of attribute names.
  423. */
  424. Effect.prototype.getAttributesNames = function () {
  425. return this._attributesNames;
  426. };
  427. /**
  428. * Returns the attribute at the given index.
  429. * @param index The index of the attribute.
  430. * @returns The location of the attribute.
  431. */
  432. Effect.prototype.getAttributeLocation = function (index) {
  433. return this._attributes[index];
  434. };
  435. /**
  436. * Returns the attribute based on the name of the variable.
  437. * @param name of the attribute to look up.
  438. * @returns the attribute location.
  439. */
  440. Effect.prototype.getAttributeLocationByName = function (name) {
  441. var index = this._attributesNames.indexOf(name);
  442. return this._attributes[index];
  443. };
  444. /**
  445. * The number of attributes.
  446. * @returns the numnber of attributes.
  447. */
  448. Effect.prototype.getAttributesCount = function () {
  449. return this._attributes.length;
  450. };
  451. /**
  452. * Gets the index of a uniform variable.
  453. * @param uniformName of the uniform to look up.
  454. * @returns the index.
  455. */
  456. Effect.prototype.getUniformIndex = function (uniformName) {
  457. return this._uniformsNames.indexOf(uniformName);
  458. };
  459. /**
  460. * Returns the attribute based on the name of the variable.
  461. * @param uniformName of the uniform to look up.
  462. * @returns the location of the uniform.
  463. */
  464. Effect.prototype.getUniform = function (uniformName) {
  465. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  466. };
  467. /**
  468. * Returns an array of sampler variable names
  469. * @returns The array of sampler variable neames.
  470. */
  471. Effect.prototype.getSamplers = function () {
  472. return this._samplers;
  473. };
  474. /**
  475. * The error from the last compilation.
  476. * @returns the error string.
  477. */
  478. Effect.prototype.getCompilationError = function () {
  479. return this._compilationError;
  480. };
  481. /**
  482. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  483. * @param func The callback to be used.
  484. */
  485. Effect.prototype.executeWhenCompiled = function (func) {
  486. if (this.isReady()) {
  487. func(this);
  488. return;
  489. }
  490. this.onCompileObservable.add(function (effect) {
  491. func(effect);
  492. });
  493. };
  494. /** @ignore */
  495. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  496. if (BABYLON.Tools.IsWindowObjectExist()) {
  497. // DOM element ?
  498. if (vertex instanceof HTMLElement) {
  499. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  500. return Promise.resolve(vertexCode);
  501. }
  502. }
  503. // Base64 encoded ?
  504. if (vertex.substr(0, 7) === "base64:") {
  505. var vertexBinary = window.atob(vertex.substr(7));
  506. return Promise.resolve(vertexBinary);
  507. }
  508. // Is in local store ?
  509. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  510. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  511. }
  512. var vertexShaderUrl;
  513. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  514. vertexShaderUrl = vertex;
  515. }
  516. else {
  517. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  518. }
  519. // Vertex shader
  520. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  521. };
  522. /** @ignore */
  523. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  524. if (BABYLON.Tools.IsWindowObjectExist()) {
  525. // DOM element ?
  526. if (fragment instanceof HTMLElement) {
  527. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  528. return Promise.resolve(fragmentCode);
  529. }
  530. }
  531. // Base64 encoded ?
  532. if (fragment.substr(0, 7) === "base64:") {
  533. var fragmentBinary = window.atob(fragment.substr(7));
  534. return Promise.resolve(fragmentBinary);
  535. }
  536. // Is in local store ?
  537. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  538. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  539. }
  540. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  541. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  542. }
  543. var fragmentShaderUrl;
  544. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  545. fragmentShaderUrl = fragment;
  546. }
  547. else {
  548. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  549. }
  550. // Fragment shader
  551. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  552. };
  553. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  554. // Rebuild shaders source code
  555. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  556. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  557. vertexCode = prefix + vertexCode;
  558. fragmentCode = prefix + fragmentCode;
  559. // Number lines of shaders source code
  560. var i = 2;
  561. var regex = /\n/gm;
  562. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  563. i = 2;
  564. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  565. // Dump shaders name and formatted source code
  566. if (this.name.vertexElement) {
  567. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  568. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  569. }
  570. else if (this.name.vertex) {
  571. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  572. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  573. }
  574. else {
  575. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  576. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  577. }
  578. };
  579. ;
  580. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  581. var preparedSourceCode = this._processPrecision(sourceCode);
  582. if (this._engine.webGLVersion == 1) {
  583. return preparedSourceCode;
  584. }
  585. // Already converted
  586. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  587. return preparedSourceCode.replace("#version 300 es", "");
  588. }
  589. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  590. // Remove extensions
  591. // #extension GL_OES_standard_derivatives : enable
  592. // #extension GL_EXT_shader_texture_lod : enable
  593. // #extension GL_EXT_frag_depth : enable
  594. // #extension GL_EXT_draw_buffers : require
  595. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  596. var result = preparedSourceCode.replace(regex, "");
  597. // Migrate to GLSL v300
  598. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  599. result = result.replace(/attribute[ \t]/g, "in ");
  600. result = result.replace(/[ \t]attribute/g, " in");
  601. if (isFragment) {
  602. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  603. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  604. result = result.replace(/texture2D\s*\(/g, "texture(");
  605. result = result.replace(/textureCube\s*\(/g, "texture(");
  606. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  607. result = result.replace(/gl_FragColor/g, "glFragColor");
  608. result = result.replace(/gl_FragData/g, "glFragData");
  609. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  610. }
  611. return result;
  612. };
  613. Effect.prototype._processIncludesAsync = function (sourceCode) {
  614. var _this = this;
  615. return new Promise(function (resolve, reject) {
  616. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  617. var match = regex.exec(sourceCode);
  618. var returnValue = sourceCode;
  619. while (match != null) {
  620. var includeFile = match[1];
  621. // Uniform declaration
  622. if (includeFile.indexOf("__decl__") !== -1) {
  623. includeFile = includeFile.replace(/__decl__/, "");
  624. if (_this._engine.supportsUniformBuffers) {
  625. includeFile = includeFile.replace(/Vertex/, "Ubo");
  626. includeFile = includeFile.replace(/Fragment/, "Ubo");
  627. }
  628. includeFile = includeFile + "Declaration";
  629. }
  630. if (Effect.IncludesShadersStore[includeFile]) {
  631. // Substitution
  632. var includeContent = Effect.IncludesShadersStore[includeFile];
  633. if (match[2]) {
  634. var splits = match[3].split(",");
  635. for (var index = 0; index < splits.length; index += 2) {
  636. var source = new RegExp(splits[index], "g");
  637. var dest = splits[index + 1];
  638. includeContent = includeContent.replace(source, dest);
  639. }
  640. }
  641. if (match[4]) {
  642. var indexString = match[5];
  643. if (indexString.indexOf("..") !== -1) {
  644. var indexSplits = indexString.split("..");
  645. var minIndex = parseInt(indexSplits[0]);
  646. var maxIndex = parseInt(indexSplits[1]);
  647. var sourceIncludeContent = includeContent.slice(0);
  648. includeContent = "";
  649. if (isNaN(maxIndex)) {
  650. maxIndex = _this._indexParameters[indexSplits[1]];
  651. }
  652. for (var i = minIndex; i < maxIndex; i++) {
  653. if (!_this._engine.supportsUniformBuffers) {
  654. // Ubo replacement
  655. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  656. return p1 + "{X}";
  657. });
  658. }
  659. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  660. }
  661. }
  662. else {
  663. if (!_this._engine.supportsUniformBuffers) {
  664. // Ubo replacement
  665. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  666. return p1 + "{X}";
  667. });
  668. }
  669. includeContent = includeContent.replace(/\{X\}/g, indexString);
  670. }
  671. }
  672. // Replace
  673. returnValue = returnValue.replace(match[0], includeContent);
  674. }
  675. else {
  676. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  677. _this._engine._loadFileAsync(includeShaderUrl)
  678. .then(function (fileContent) {
  679. Effect.IncludesShadersStore[includeFile] = fileContent;
  680. return _this._processIncludesAsync(returnValue);
  681. })
  682. .then(function (returnValue) {
  683. resolve(returnValue);
  684. });
  685. return;
  686. }
  687. match = regex.exec(sourceCode);
  688. }
  689. resolve(returnValue);
  690. });
  691. };
  692. Effect.prototype._processPrecision = function (source) {
  693. if (source.indexOf("precision highp float") === -1) {
  694. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  695. source = "precision mediump float;\n" + source;
  696. }
  697. else {
  698. source = "precision highp float;\n" + source;
  699. }
  700. }
  701. else {
  702. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  703. source = source.replace("precision highp float", "precision mediump float");
  704. }
  705. }
  706. return source;
  707. };
  708. /**
  709. * Recompiles the webGL program
  710. * @param vertexSourceCode The source code for the vertex shader.
  711. * @param fragmentSourceCode The source code for the fragment shader.
  712. * @param onCompiled Callback called when completed.
  713. * @param onError Callback called on error.
  714. */
  715. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  716. var _this = this;
  717. this._isReady = false;
  718. this._vertexSourceCodeOverride = vertexSourceCode;
  719. this._fragmentSourceCodeOverride = fragmentSourceCode;
  720. this.onError = function (effect, error) {
  721. if (onError) {
  722. onError(error);
  723. }
  724. };
  725. this.onCompiled = function () {
  726. var scenes = _this.getEngine().scenes;
  727. for (var i = 0; i < scenes.length; i++) {
  728. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  729. }
  730. if (onCompiled) {
  731. onCompiled(_this._program);
  732. }
  733. };
  734. this._fallbacks = null;
  735. this._prepareEffect();
  736. };
  737. /**
  738. * Gets the uniform locations of the the specified variable names
  739. * @param names THe names of the variables to lookup.
  740. * @returns Array of locations in the same order as variable names.
  741. */
  742. Effect.prototype.getSpecificUniformLocations = function (names) {
  743. var engine = this._engine;
  744. return engine.getUniforms(this._program, names);
  745. };
  746. /**
  747. * Prepares the effect
  748. */
  749. Effect.prototype._prepareEffect = function () {
  750. var attributesNames = this._attributesNames;
  751. var defines = this.defines;
  752. var fallbacks = this._fallbacks;
  753. this._valueCache = {};
  754. var previousProgram = this._program;
  755. try {
  756. var engine = this._engine;
  757. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  758. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  759. }
  760. else {
  761. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  762. }
  763. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  764. if (engine.supportsUniformBuffers) {
  765. for (var name in this._uniformBuffersNames) {
  766. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  767. }
  768. }
  769. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  770. this._attributes = engine.getAttributes(this._program, attributesNames);
  771. var index;
  772. for (index = 0; index < this._samplers.length; index++) {
  773. var sampler = this.getUniform(this._samplers[index]);
  774. if (sampler == null) {
  775. this._samplers.splice(index, 1);
  776. index--;
  777. }
  778. }
  779. engine.bindSamplers(this);
  780. this._compilationError = "";
  781. this._isReady = true;
  782. if (this.onCompiled) {
  783. this.onCompiled(this);
  784. }
  785. this.onCompileObservable.notifyObservers(this);
  786. this.onCompileObservable.clear();
  787. // Unbind mesh reference in fallbacks
  788. if (this._fallbacks) {
  789. this._fallbacks.unBindMesh();
  790. }
  791. if (previousProgram) {
  792. this.getEngine()._deleteProgram(previousProgram);
  793. }
  794. }
  795. catch (e) {
  796. this._compilationError = e.message;
  797. // Let's go through fallbacks then
  798. BABYLON.Tools.Error("Unable to compile effect:");
  799. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  800. return " " + uniform;
  801. }));
  802. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  803. return " " + attribute;
  804. }));
  805. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  806. BABYLON.Tools.Error("Error: " + this._compilationError);
  807. if (previousProgram) {
  808. this._program = previousProgram;
  809. this._isReady = true;
  810. if (this.onError) {
  811. this.onError(this, this._compilationError);
  812. }
  813. this.onErrorObservable.notifyObservers(this);
  814. }
  815. if (fallbacks && fallbacks.isMoreFallbacks) {
  816. BABYLON.Tools.Error("Trying next fallback.");
  817. this.defines = fallbacks.reduce(this.defines, this);
  818. this._prepareEffect();
  819. }
  820. else {
  821. if (this.onError) {
  822. this.onError(this, this._compilationError);
  823. }
  824. this.onErrorObservable.notifyObservers(this);
  825. this.onErrorObservable.clear();
  826. // Unbind mesh reference in fallbacks
  827. if (this._fallbacks) {
  828. this._fallbacks.unBindMesh();
  829. }
  830. }
  831. }
  832. };
  833. Object.defineProperty(Effect.prototype, "isSupported", {
  834. /**
  835. * Checks if the effect is supported. (Must be called after compilation)
  836. */
  837. get: function () {
  838. return this._compilationError === "";
  839. },
  840. enumerable: true,
  841. configurable: true
  842. });
  843. /**
  844. * Binds a texture to the engine to be used as output of the shader.
  845. * @param channel Name of the output variable.
  846. * @param texture Texture to bind.
  847. */
  848. Effect.prototype._bindTexture = function (channel, texture) {
  849. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  850. };
  851. /**
  852. * Sets a texture on the engine to be used in the shader.
  853. * @param channel Name of the sampler variable.
  854. * @param texture Texture to set.
  855. */
  856. Effect.prototype.setTexture = function (channel, texture) {
  857. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  858. };
  859. /**
  860. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  861. * @param channel Name of the sampler variable.
  862. * @param texture Texture to set.
  863. */
  864. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  865. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  866. };
  867. /**
  868. * Sets an array of textures on the engine to be used in the shader.
  869. * @param channel Name of the variable.
  870. * @param textures Textures to set.
  871. */
  872. Effect.prototype.setTextureArray = function (channel, textures) {
  873. if (this._samplers.indexOf(channel + "Ex") === -1) {
  874. var initialPos = this._samplers.indexOf(channel);
  875. for (var index = 1; index < textures.length; index++) {
  876. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  877. }
  878. }
  879. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  880. };
  881. /**
  882. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  883. * @param channel Name of the sampler variable.
  884. * @param postProcess Post process to get the input texture from.
  885. */
  886. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  887. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  888. };
  889. /** @ignore */
  890. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  891. var cache = this._valueCache[uniformName];
  892. var flag = matrix.updateFlag;
  893. if (cache !== undefined && cache === flag) {
  894. return false;
  895. }
  896. this._valueCache[uniformName] = flag;
  897. return true;
  898. };
  899. /** @ignore */
  900. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  901. var cache = this._valueCache[uniformName];
  902. if (!cache) {
  903. cache = [x, y];
  904. this._valueCache[uniformName] = cache;
  905. return true;
  906. }
  907. var changed = false;
  908. if (cache[0] !== x) {
  909. cache[0] = x;
  910. changed = true;
  911. }
  912. if (cache[1] !== y) {
  913. cache[1] = y;
  914. changed = true;
  915. }
  916. return changed;
  917. };
  918. /** @ignore */
  919. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  920. var cache = this._valueCache[uniformName];
  921. if (!cache) {
  922. cache = [x, y, z];
  923. this._valueCache[uniformName] = cache;
  924. return true;
  925. }
  926. var changed = false;
  927. if (cache[0] !== x) {
  928. cache[0] = x;
  929. changed = true;
  930. }
  931. if (cache[1] !== y) {
  932. cache[1] = y;
  933. changed = true;
  934. }
  935. if (cache[2] !== z) {
  936. cache[2] = z;
  937. changed = true;
  938. }
  939. return changed;
  940. };
  941. /** @ignore */
  942. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  943. var cache = this._valueCache[uniformName];
  944. if (!cache) {
  945. cache = [x, y, z, w];
  946. this._valueCache[uniformName] = cache;
  947. return true;
  948. }
  949. var changed = false;
  950. if (cache[0] !== x) {
  951. cache[0] = x;
  952. changed = true;
  953. }
  954. if (cache[1] !== y) {
  955. cache[1] = y;
  956. changed = true;
  957. }
  958. if (cache[2] !== z) {
  959. cache[2] = z;
  960. changed = true;
  961. }
  962. if (cache[3] !== w) {
  963. cache[3] = w;
  964. changed = true;
  965. }
  966. return changed;
  967. };
  968. /**
  969. * Binds a buffer to a uniform.
  970. * @param buffer Buffer to bind.
  971. * @param name Name of the uniform variable to bind to.
  972. */
  973. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  974. var bufferName = this._uniformBuffersNames[name];
  975. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  976. return;
  977. }
  978. Effect._baseCache[bufferName] = buffer;
  979. this._engine.bindUniformBufferBase(buffer, bufferName);
  980. };
  981. /**
  982. * Binds block to a uniform.
  983. * @param blockName Name of the block to bind.
  984. * @param index Index to bind.
  985. */
  986. Effect.prototype.bindUniformBlock = function (blockName, index) {
  987. this._engine.bindUniformBlock(this._program, blockName, index);
  988. };
  989. /**
  990. * Sets an interger value on a uniform variable.
  991. * @param uniformName Name of the variable.
  992. * @param value Value to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setInt = function (uniformName, value) {
  996. var cache = this._valueCache[uniformName];
  997. if (cache !== undefined && cache === value)
  998. return this;
  999. this._valueCache[uniformName] = value;
  1000. this._engine.setInt(this.getUniform(uniformName), value);
  1001. return this;
  1002. };
  1003. /**
  1004. * Sets an int array on a uniform variable.
  1005. * @param uniformName Name of the variable.
  1006. * @param array array to be set.
  1007. * @returns this effect.
  1008. */
  1009. Effect.prototype.setIntArray = function (uniformName, array) {
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setIntArray(this.getUniform(uniformName), array);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1016. * @param uniformName Name of the variable.
  1017. * @param array array to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setIntArray2 = function (uniformName, array) {
  1021. this._valueCache[uniformName] = null;
  1022. this._engine.setIntArray2(this.getUniform(uniformName), array);
  1023. return this;
  1024. };
  1025. /**
  1026. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1027. * @param uniformName Name of the variable.
  1028. * @param array array to be set.
  1029. * @returns this effect.
  1030. */
  1031. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1032. this._valueCache[uniformName] = null;
  1033. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1034. return this;
  1035. };
  1036. /**
  1037. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1038. * @param uniformName Name of the variable.
  1039. * @param array array to be set.
  1040. * @returns this effect.
  1041. */
  1042. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1043. this._valueCache[uniformName] = null;
  1044. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1045. return this;
  1046. };
  1047. /**
  1048. * Sets an float array on a uniform variable.
  1049. * @param uniformName Name of the variable.
  1050. * @param array array to be set.
  1051. * @returns this effect.
  1052. */
  1053. Effect.prototype.setFloatArray = function (uniformName, array) {
  1054. this._valueCache[uniformName] = null;
  1055. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1056. return this;
  1057. };
  1058. /**
  1059. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1060. * @param uniformName Name of the variable.
  1061. * @param array array to be set.
  1062. * @returns this effect.
  1063. */
  1064. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1065. this._valueCache[uniformName] = null;
  1066. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1067. return this;
  1068. };
  1069. /**
  1070. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1071. * @param uniformName Name of the variable.
  1072. * @param array array to be set.
  1073. * @returns this effect.
  1074. */
  1075. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1076. this._valueCache[uniformName] = null;
  1077. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1078. return this;
  1079. };
  1080. /**
  1081. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1082. * @param uniformName Name of the variable.
  1083. * @param array array to be set.
  1084. * @returns this effect.
  1085. */
  1086. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1087. this._valueCache[uniformName] = null;
  1088. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1089. return this;
  1090. };
  1091. /**
  1092. * Sets an array on a uniform variable.
  1093. * @param uniformName Name of the variable.
  1094. * @param array array to be set.
  1095. * @returns this effect.
  1096. */
  1097. Effect.prototype.setArray = function (uniformName, array) {
  1098. this._valueCache[uniformName] = null;
  1099. this._engine.setArray(this.getUniform(uniformName), array);
  1100. return this;
  1101. };
  1102. /**
  1103. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1104. * @param uniformName Name of the variable.
  1105. * @param array array to be set.
  1106. * @returns this effect.
  1107. */
  1108. Effect.prototype.setArray2 = function (uniformName, array) {
  1109. this._valueCache[uniformName] = null;
  1110. this._engine.setArray2(this.getUniform(uniformName), array);
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1115. * @param uniformName Name of the variable.
  1116. * @param array array to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setArray3 = function (uniformName, array) {
  1120. this._valueCache[uniformName] = null;
  1121. this._engine.setArray3(this.getUniform(uniformName), array);
  1122. return this;
  1123. };
  1124. /**
  1125. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1126. * @param uniformName Name of the variable.
  1127. * @param array array to be set.
  1128. * @returns this effect.
  1129. */
  1130. Effect.prototype.setArray4 = function (uniformName, array) {
  1131. this._valueCache[uniformName] = null;
  1132. this._engine.setArray4(this.getUniform(uniformName), array);
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets matrices on a uniform variable.
  1137. * @param uniformName Name of the variable.
  1138. * @param matrices matrices to be set.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1142. if (!matrices) {
  1143. return this;
  1144. }
  1145. this._valueCache[uniformName] = null;
  1146. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1147. return this;
  1148. };
  1149. /**
  1150. * Sets matrix on a uniform variable.
  1151. * @param uniformName Name of the variable.
  1152. * @param matrix matrix to be set.
  1153. * @returns this effect.
  1154. */
  1155. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1156. if (this._cacheMatrix(uniformName, matrix)) {
  1157. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1158. }
  1159. return this;
  1160. };
  1161. /**
  1162. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1163. * @param uniformName Name of the variable.
  1164. * @param matrix matrix to be set.
  1165. * @returns this effect.
  1166. */
  1167. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1168. this._valueCache[uniformName] = null;
  1169. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1170. return this;
  1171. };
  1172. /**
  1173. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1174. * @param uniformName Name of the variable.
  1175. * @param matrix matrix to be set.
  1176. * @returns this effect.
  1177. */
  1178. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1179. this._valueCache[uniformName] = null;
  1180. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1181. return this;
  1182. };
  1183. /**
  1184. * Sets a float on a uniform variable.
  1185. * @param uniformName Name of the variable.
  1186. * @param value value to be set.
  1187. * @returns this effect.
  1188. */
  1189. Effect.prototype.setFloat = function (uniformName, value) {
  1190. var cache = this._valueCache[uniformName];
  1191. if (cache !== undefined && cache === value)
  1192. return this;
  1193. this._valueCache[uniformName] = value;
  1194. this._engine.setFloat(this.getUniform(uniformName), value);
  1195. return this;
  1196. };
  1197. /**
  1198. * Sets a boolean on a uniform variable.
  1199. * @param uniformName Name of the variable.
  1200. * @param bool value to be set.
  1201. * @returns this effect.
  1202. */
  1203. Effect.prototype.setBool = function (uniformName, bool) {
  1204. var cache = this._valueCache[uniformName];
  1205. if (cache !== undefined && cache === bool)
  1206. return this;
  1207. this._valueCache[uniformName] = bool;
  1208. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1209. return this;
  1210. };
  1211. /**
  1212. * Sets a Vector2 on a uniform variable.
  1213. * @param uniformName Name of the variable.
  1214. * @param vector2 vector2 to be set.
  1215. * @returns this effect.
  1216. */
  1217. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1218. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1219. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1220. }
  1221. return this;
  1222. };
  1223. /**
  1224. * Sets a float2 on a uniform variable.
  1225. * @param uniformName Name of the variable.
  1226. * @param x First float in float2.
  1227. * @param y Second float in float2.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1231. if (this._cacheFloat2(uniformName, x, y)) {
  1232. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Vector3 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param vector3 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1243. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1244. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a float3 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param x First float in float3.
  1252. * @param y Second float in float3.
  1253. * @param z Third float in float3.
  1254. * @returns this effect.
  1255. */
  1256. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1257. if (this._cacheFloat3(uniformName, x, y, z)) {
  1258. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1259. }
  1260. return this;
  1261. };
  1262. /**
  1263. * Sets a Vector4 on a uniform variable.
  1264. * @param uniformName Name of the variable.
  1265. * @param vector4 Value to be set.
  1266. * @returns this effect.
  1267. */
  1268. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1269. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1270. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1271. }
  1272. return this;
  1273. };
  1274. /**
  1275. * Sets a float4 on a uniform variable.
  1276. * @param uniformName Name of the variable.
  1277. * @param x First float in float4.
  1278. * @param y Second float in float4.
  1279. * @param z Third float in float4.
  1280. * @param w Fourth float in float4.
  1281. * @returns this effect.
  1282. */
  1283. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1284. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1285. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1286. }
  1287. return this;
  1288. };
  1289. /**
  1290. * Sets a Color3 on a uniform variable.
  1291. * @param uniformName Name of the variable.
  1292. * @param color3 Value to be set.
  1293. * @returns this effect.
  1294. */
  1295. Effect.prototype.setColor3 = function (uniformName, color3) {
  1296. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1297. this._engine.setColor3(this.getUniform(uniformName), color3);
  1298. }
  1299. return this;
  1300. };
  1301. /**
  1302. * Sets a Color4 on a uniform variable.
  1303. * @param uniformName Name of the variable.
  1304. * @param color3 Value to be set.
  1305. * @param alpha Alpha value to be set.
  1306. * @returns this effect.
  1307. */
  1308. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1309. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1310. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1311. }
  1312. return this;
  1313. };
  1314. /**
  1315. * Sets a Color4 on a uniform variable
  1316. * @param uniformName defines the name of the variable
  1317. * @param color4 defines the value to be set
  1318. * @returns this effect.
  1319. */
  1320. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1321. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1322. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1323. }
  1324. return this;
  1325. };
  1326. /**
  1327. * Resets the cache of effects.
  1328. */
  1329. Effect.ResetCache = function () {
  1330. Effect._baseCache = {};
  1331. };
  1332. Effect._uniqueIdSeed = 0;
  1333. Effect._baseCache = {};
  1334. Effect._sourceCache = {};
  1335. // Statics
  1336. /**
  1337. * Store of each shader (The can be looked up using effect.key)
  1338. */
  1339. Effect.ShadersStore = {};
  1340. /**
  1341. * Store of each included file for a shader (The can be looked up using effect.key)
  1342. */
  1343. Effect.IncludesShadersStore = {};
  1344. return Effect;
  1345. }());
  1346. BABYLON.Effect = Effect;
  1347. })(BABYLON || (BABYLON = {}));
  1348. //# sourceMappingURL=babylon.effect.js.map
  1349. //# sourceMappingURL=babylon.types.js.map
  1350. var BABYLON;
  1351. (function (BABYLON) {
  1352. var KeyboardEventTypes = /** @class */ (function () {
  1353. function KeyboardEventTypes() {
  1354. }
  1355. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1356. get: function () {
  1357. return KeyboardEventTypes._KEYDOWN;
  1358. },
  1359. enumerable: true,
  1360. configurable: true
  1361. });
  1362. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1363. get: function () {
  1364. return KeyboardEventTypes._KEYUP;
  1365. },
  1366. enumerable: true,
  1367. configurable: true
  1368. });
  1369. KeyboardEventTypes._KEYDOWN = 0x01;
  1370. KeyboardEventTypes._KEYUP = 0x02;
  1371. return KeyboardEventTypes;
  1372. }());
  1373. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1374. var KeyboardInfo = /** @class */ (function () {
  1375. function KeyboardInfo(type, event) {
  1376. this.type = type;
  1377. this.event = event;
  1378. }
  1379. return KeyboardInfo;
  1380. }());
  1381. BABYLON.KeyboardInfo = KeyboardInfo;
  1382. /**
  1383. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1384. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1385. */
  1386. var KeyboardInfoPre = /** @class */ (function (_super) {
  1387. __extends(KeyboardInfoPre, _super);
  1388. function KeyboardInfoPre(type, event) {
  1389. var _this = _super.call(this, type, event) || this;
  1390. _this.skipOnPointerObservable = false;
  1391. return _this;
  1392. }
  1393. return KeyboardInfoPre;
  1394. }(KeyboardInfo));
  1395. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1396. })(BABYLON || (BABYLON = {}));
  1397. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1398. var BABYLON;
  1399. (function (BABYLON) {
  1400. var PointerEventTypes = /** @class */ (function () {
  1401. function PointerEventTypes() {
  1402. }
  1403. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1404. get: function () {
  1405. return PointerEventTypes._POINTERDOWN;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1411. get: function () {
  1412. return PointerEventTypes._POINTERUP;
  1413. },
  1414. enumerable: true,
  1415. configurable: true
  1416. });
  1417. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1418. get: function () {
  1419. return PointerEventTypes._POINTERMOVE;
  1420. },
  1421. enumerable: true,
  1422. configurable: true
  1423. });
  1424. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1425. get: function () {
  1426. return PointerEventTypes._POINTERWHEEL;
  1427. },
  1428. enumerable: true,
  1429. configurable: true
  1430. });
  1431. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1432. get: function () {
  1433. return PointerEventTypes._POINTERPICK;
  1434. },
  1435. enumerable: true,
  1436. configurable: true
  1437. });
  1438. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1439. get: function () {
  1440. return PointerEventTypes._POINTERTAP;
  1441. },
  1442. enumerable: true,
  1443. configurable: true
  1444. });
  1445. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1446. get: function () {
  1447. return PointerEventTypes._POINTERDOUBLETAP;
  1448. },
  1449. enumerable: true,
  1450. configurable: true
  1451. });
  1452. PointerEventTypes._POINTERDOWN = 0x01;
  1453. PointerEventTypes._POINTERUP = 0x02;
  1454. PointerEventTypes._POINTERMOVE = 0x04;
  1455. PointerEventTypes._POINTERWHEEL = 0x08;
  1456. PointerEventTypes._POINTERPICK = 0x10;
  1457. PointerEventTypes._POINTERTAP = 0x20;
  1458. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1459. return PointerEventTypes;
  1460. }());
  1461. BABYLON.PointerEventTypes = PointerEventTypes;
  1462. var PointerInfoBase = /** @class */ (function () {
  1463. function PointerInfoBase(type, event) {
  1464. this.type = type;
  1465. this.event = event;
  1466. }
  1467. return PointerInfoBase;
  1468. }());
  1469. BABYLON.PointerInfoBase = PointerInfoBase;
  1470. /**
  1471. * This class is used to store pointer related info for the onPrePointerObservable event.
  1472. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1473. */
  1474. var PointerInfoPre = /** @class */ (function (_super) {
  1475. __extends(PointerInfoPre, _super);
  1476. function PointerInfoPre(type, event, localX, localY) {
  1477. var _this = _super.call(this, type, event) || this;
  1478. _this.skipOnPointerObservable = false;
  1479. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1480. return _this;
  1481. }
  1482. return PointerInfoPre;
  1483. }(PointerInfoBase));
  1484. BABYLON.PointerInfoPre = PointerInfoPre;
  1485. /**
  1486. * This type contains all the data related to a pointer event in Babylon.js.
  1487. * 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.
  1488. */
  1489. var PointerInfo = /** @class */ (function (_super) {
  1490. __extends(PointerInfo, _super);
  1491. function PointerInfo(type, event, pickInfo) {
  1492. var _this = _super.call(this, type, event) || this;
  1493. _this.pickInfo = pickInfo;
  1494. return _this;
  1495. }
  1496. return PointerInfo;
  1497. }(PointerInfoBase));
  1498. BABYLON.PointerInfo = PointerInfo;
  1499. })(BABYLON || (BABYLON = {}));
  1500. //# sourceMappingURL=babylon.pointerEvents.js.map
  1501. var BABYLON;
  1502. (function (BABYLON) {
  1503. BABYLON.ToGammaSpace = 1 / 2.2;
  1504. BABYLON.ToLinearSpace = 2.2;
  1505. BABYLON.Epsilon = 0.001;
  1506. /**
  1507. * Class used to hold a RBG color
  1508. */
  1509. var Color3 = /** @class */ (function () {
  1510. /**
  1511. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1512. * @param r defines the red component (between 0 and 1, default is 0)
  1513. * @param g defines the green component (between 0 and 1, default is 0)
  1514. * @param b defines the blue component (between 0 and 1, default is 0)
  1515. */
  1516. function Color3(
  1517. /**
  1518. * Defines the red component (between 0 and 1, default is 0)
  1519. */
  1520. r,
  1521. /**
  1522. * Defines the green component (between 0 and 1, default is 0)
  1523. */
  1524. g,
  1525. /**
  1526. * Defines the blue component (between 0 and 1, default is 0)
  1527. */
  1528. b) {
  1529. if (r === void 0) { r = 0; }
  1530. if (g === void 0) { g = 0; }
  1531. if (b === void 0) { b = 0; }
  1532. this.r = r;
  1533. this.g = g;
  1534. this.b = b;
  1535. }
  1536. /**
  1537. * Creates a string with the Color3 current values
  1538. * @returns the string representation of the Color3 object
  1539. */
  1540. Color3.prototype.toString = function () {
  1541. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1542. };
  1543. /**
  1544. * Returns the string "Color3"
  1545. * @returns "Color3"
  1546. */
  1547. Color3.prototype.getClassName = function () {
  1548. return "Color3";
  1549. };
  1550. /**
  1551. * Compute the Color3 hash code
  1552. * @returns an unique number that can be used to hash Color3 objects
  1553. */
  1554. Color3.prototype.getHashCode = function () {
  1555. var hash = this.r || 0;
  1556. hash = (hash * 397) ^ (this.g || 0);
  1557. hash = (hash * 397) ^ (this.b || 0);
  1558. return hash;
  1559. };
  1560. // Operators
  1561. /**
  1562. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1563. * @param array defines the array where to store the r,g,b components
  1564. * @param index defines an optional index in the target array to define where to start storing values
  1565. * @returns the current Color3 object
  1566. */
  1567. Color3.prototype.toArray = function (array, index) {
  1568. if (index === undefined) {
  1569. index = 0;
  1570. }
  1571. array[index] = this.r;
  1572. array[index + 1] = this.g;
  1573. array[index + 2] = this.b;
  1574. return this;
  1575. };
  1576. /**
  1577. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1578. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1579. * @returns a new {BABYLON.Color4} object
  1580. */
  1581. Color3.prototype.toColor4 = function (alpha) {
  1582. if (alpha === void 0) { alpha = 1; }
  1583. return new Color4(this.r, this.g, this.b, alpha);
  1584. };
  1585. /**
  1586. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1587. * @returns the new array
  1588. */
  1589. Color3.prototype.asArray = function () {
  1590. var result = new Array();
  1591. this.toArray(result, 0);
  1592. return result;
  1593. };
  1594. /**
  1595. * Returns the luminance value
  1596. * @returns a float value
  1597. */
  1598. Color3.prototype.toLuminance = function () {
  1599. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1600. };
  1601. /**
  1602. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1603. * @param otherColor defines the second operand
  1604. * @returns the new Color3 object
  1605. */
  1606. Color3.prototype.multiply = function (otherColor) {
  1607. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1608. };
  1609. /**
  1610. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1611. * @param otherColor defines the second operand
  1612. * @param result defines the Color3 object where to store the result
  1613. * @returns the current Color3
  1614. */
  1615. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1616. result.r = this.r * otherColor.r;
  1617. result.g = this.g * otherColor.g;
  1618. result.b = this.b * otherColor.b;
  1619. return this;
  1620. };
  1621. /**
  1622. * Determines equality between Color3 objects
  1623. * @param otherColor defines the second operand
  1624. * @returns true if the rgb values are equal to the passed ones
  1625. */
  1626. Color3.prototype.equals = function (otherColor) {
  1627. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1628. };
  1629. /**
  1630. * Determines equality between the current Color3 object and a set of r,b,g values
  1631. * @param r defines the red component to check
  1632. * @param g defines the green component to check
  1633. * @param b defines the blue component to check
  1634. * @returns true if the rgb values are equal to the passed ones
  1635. */
  1636. Color3.prototype.equalsFloats = function (r, g, b) {
  1637. return this.r === r && this.g === g && this.b === b;
  1638. };
  1639. /**
  1640. * Multiplies in place each rgb value by scale
  1641. * @param scale defines the scaling factor
  1642. * @returns the updated Color3
  1643. */
  1644. Color3.prototype.scale = function (scale) {
  1645. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1646. };
  1647. /**
  1648. * Multiplies the rgb values by scale and stores the result into "result"
  1649. * @param scale defines the scaling factor
  1650. * @param result defines the Color3 object where to store the result
  1651. * @returns the unmodified current Color3
  1652. */
  1653. Color3.prototype.scaleToRef = function (scale, result) {
  1654. result.r = this.r * scale;
  1655. result.g = this.g * scale;
  1656. result.b = this.b * scale;
  1657. return this;
  1658. };
  1659. /**
  1660. * Scale the current Color3 values by a factor and add the result to a given Color3
  1661. * @param scale defines the scale factor
  1662. * @param result defines color to store the result into
  1663. * @returns the unmodified current Color3
  1664. */
  1665. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1666. result.r += this.r * scale;
  1667. result.g += this.g * scale;
  1668. result.b += this.b * scale;
  1669. return this;
  1670. };
  1671. /**
  1672. * Clamps the rgb values by the min and max values and stores the result into "result"
  1673. * @param min defines minimum clamping value (default is 0)
  1674. * @param max defines maximum clamping value (default is 1)
  1675. * @param result defines color to store the result into
  1676. * @returns the original Color3
  1677. */
  1678. Color3.prototype.clampToRef = function (min, max, result) {
  1679. if (min === void 0) { min = 0; }
  1680. if (max === void 0) { max = 1; }
  1681. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1682. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1683. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1684. return this;
  1685. };
  1686. /**
  1687. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1688. * @param otherColor defines the second operand
  1689. * @returns the new Color3
  1690. */
  1691. Color3.prototype.add = function (otherColor) {
  1692. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1693. };
  1694. /**
  1695. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1696. * @param otherColor defines the second operand
  1697. * @param result defines Color3 object to store the result into
  1698. * @returns the unmodified current Color3
  1699. */
  1700. Color3.prototype.addToRef = function (otherColor, result) {
  1701. result.r = this.r + otherColor.r;
  1702. result.g = this.g + otherColor.g;
  1703. result.b = this.b + otherColor.b;
  1704. return this;
  1705. };
  1706. /**
  1707. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1708. * @param otherColor defines the second operand
  1709. * @returns the new Color3
  1710. */
  1711. Color3.prototype.subtract = function (otherColor) {
  1712. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1713. };
  1714. /**
  1715. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1716. * @param otherColor defines the second operand
  1717. * @param result defines Color3 object to store the result into
  1718. * @returns the unmodified current Color3
  1719. */
  1720. Color3.prototype.subtractToRef = function (otherColor, result) {
  1721. result.r = this.r - otherColor.r;
  1722. result.g = this.g - otherColor.g;
  1723. result.b = this.b - otherColor.b;
  1724. return this;
  1725. };
  1726. /**
  1727. * Copy the current object
  1728. * @returns a new Color3 copied the current one
  1729. */
  1730. Color3.prototype.clone = function () {
  1731. return new Color3(this.r, this.g, this.b);
  1732. };
  1733. /**
  1734. * Copies the rgb values from the source in the current Color3
  1735. * @param source defines the source Color3 object
  1736. * @returns the updated Color3 object
  1737. */
  1738. Color3.prototype.copyFrom = function (source) {
  1739. this.r = source.r;
  1740. this.g = source.g;
  1741. this.b = source.b;
  1742. return this;
  1743. };
  1744. /**
  1745. * Updates the Color3 rgb values from the passed floats
  1746. * @param r defines the red component to read from
  1747. * @param g defines the green component to read from
  1748. * @param b defines the blue component to read from
  1749. * @returns the current Color3 object
  1750. */
  1751. Color3.prototype.copyFromFloats = function (r, g, b) {
  1752. this.r = r;
  1753. this.g = g;
  1754. this.b = b;
  1755. return this;
  1756. };
  1757. /**
  1758. * Updates the Color3 rgb values from the passed floats
  1759. * @param r defines the red component to read from
  1760. * @param g defines the green component to read from
  1761. * @param b defines the blue component to read from
  1762. * @returns the current Color3 object
  1763. */
  1764. Color3.prototype.set = function (r, g, b) {
  1765. return this.copyFromFloats(r, g, b);
  1766. };
  1767. /**
  1768. * Compute the Color3 hexadecimal code as a string
  1769. * @returns a string containing the hexadecimal representation of the Color3 object
  1770. */
  1771. Color3.prototype.toHexString = function () {
  1772. var intR = (this.r * 255) | 0;
  1773. var intG = (this.g * 255) | 0;
  1774. var intB = (this.b * 255) | 0;
  1775. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1776. };
  1777. /**
  1778. * Computes a new Color3 converted from the current one to linear space
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.prototype.toLinearSpace = function () {
  1782. var convertedColor = new Color3();
  1783. this.toLinearSpaceToRef(convertedColor);
  1784. return convertedColor;
  1785. };
  1786. /**
  1787. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1788. * @param convertedColor defines the Color3 object where to store the linear space version
  1789. * @returns the unmodified Color3
  1790. */
  1791. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1792. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1793. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1794. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1795. return this;
  1796. };
  1797. /**
  1798. * Computes a new Color3 converted from the current one to gamma space
  1799. * @returns a new Color3 object
  1800. */
  1801. Color3.prototype.toGammaSpace = function () {
  1802. var convertedColor = new Color3();
  1803. this.toGammaSpaceToRef(convertedColor);
  1804. return convertedColor;
  1805. };
  1806. /**
  1807. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1808. * @param convertedColor defines the Color3 object where to store the gamma space version
  1809. * @returns the unmodified Color3
  1810. */
  1811. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1812. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1813. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1814. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1815. return this;
  1816. };
  1817. // Statics
  1818. /**
  1819. * Creates a new Color3 from the string containing valid hexadecimal values
  1820. * @param hex defines a string containing valid hexadecimal values
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.FromHexString = function (hex) {
  1824. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1825. return new Color3(0, 0, 0);
  1826. }
  1827. var r = parseInt(hex.substring(1, 3), 16);
  1828. var g = parseInt(hex.substring(3, 5), 16);
  1829. var b = parseInt(hex.substring(5, 7), 16);
  1830. return Color3.FromInts(r, g, b);
  1831. };
  1832. /**
  1833. * Creates a new Vector3 from the starting index of the passed array
  1834. * @param array defines the source array
  1835. * @param offset defines an offset in the source array
  1836. * @returns a new Color3 object
  1837. */
  1838. Color3.FromArray = function (array, offset) {
  1839. if (offset === void 0) { offset = 0; }
  1840. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1841. };
  1842. /**
  1843. * Creates a new Color3 from integer values (< 256)
  1844. * @param r defines the red component to read from (value between 0 and 255)
  1845. * @param g defines the green component to read from (value between 0 and 255)
  1846. * @param b defines the blue component to read from (value between 0 and 255)
  1847. * @returns a new Color3 object
  1848. */
  1849. Color3.FromInts = function (r, g, b) {
  1850. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1851. };
  1852. /**
  1853. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1854. * @param start defines the start Color3 value
  1855. * @param end defines the end Color3 value
  1856. * @param amount defines the gradient value between start and end
  1857. * @returns a new Color3 object
  1858. */
  1859. Color3.Lerp = function (start, end, amount) {
  1860. var r = start.r + ((end.r - start.r) * amount);
  1861. var g = start.g + ((end.g - start.g) * amount);
  1862. var b = start.b + ((end.b - start.b) * amount);
  1863. return new Color3(r, g, b);
  1864. };
  1865. /**
  1866. * Returns a Color3 value containing a red color
  1867. * @returns a new Color3 object
  1868. */
  1869. Color3.Red = function () { return new Color3(1, 0, 0); };
  1870. /**
  1871. * Returns a Color3 value containing a green color
  1872. * @returns a new Color3 object
  1873. */
  1874. Color3.Green = function () { return new Color3(0, 1, 0); };
  1875. /**
  1876. * Returns a Color3 value containing a blue color
  1877. * @returns a new Color3 object
  1878. */
  1879. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1880. /**
  1881. * Returns a Color3 value containing a black color
  1882. * @returns a new Color3 object
  1883. */
  1884. Color3.Black = function () { return new Color3(0, 0, 0); };
  1885. /**
  1886. * Returns a Color3 value containing a white color
  1887. * @returns a new Color3 object
  1888. */
  1889. Color3.White = function () { return new Color3(1, 1, 1); };
  1890. /**
  1891. * Returns a Color3 value containing a purple color
  1892. * @returns a new Color3 object
  1893. */
  1894. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1895. /**
  1896. * Returns a Color3 value containing a magenta color
  1897. * @returns a new Color3 object
  1898. */
  1899. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1900. /**
  1901. * Returns a Color3 value containing a yellow color
  1902. * @returns a new Color3 object
  1903. */
  1904. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1905. /**
  1906. * Returns a Color3 value containing a gray color
  1907. * @returns a new Color3 object
  1908. */
  1909. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1910. /**
  1911. * Returns a Color3 value containing a teal color
  1912. * @returns a new Color3 object
  1913. */
  1914. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1915. /**
  1916. * Returns a Color3 value containing a random color
  1917. * @returns a new Color3 object
  1918. */
  1919. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1920. return Color3;
  1921. }());
  1922. BABYLON.Color3 = Color3;
  1923. /**
  1924. * Class used to hold a RBGA color
  1925. */
  1926. var Color4 = /** @class */ (function () {
  1927. /**
  1928. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1929. * @param r defines the red component (between 0 and 1, default is 0)
  1930. * @param g defines the green component (between 0 and 1, default is 0)
  1931. * @param b defines the blue component (between 0 and 1, default is 0)
  1932. * @param a defines the alpha component (between 0 and 1, default is 1)
  1933. */
  1934. function Color4(
  1935. /**
  1936. * Defines the red component (between 0 and 1, default is 0)
  1937. */
  1938. r,
  1939. /**
  1940. * Defines the green component (between 0 and 1, default is 0)
  1941. */
  1942. g,
  1943. /**
  1944. * Defines the blue component (between 0 and 1, default is 0)
  1945. */
  1946. b,
  1947. /**
  1948. * Defines the alpha component (between 0 and 1, default is 1)
  1949. */
  1950. a) {
  1951. if (r === void 0) { r = 0; }
  1952. if (g === void 0) { g = 0; }
  1953. if (b === void 0) { b = 0; }
  1954. if (a === void 0) { a = 1; }
  1955. this.r = r;
  1956. this.g = g;
  1957. this.b = b;
  1958. this.a = a;
  1959. }
  1960. // Operators
  1961. /**
  1962. * Adds in place the passed Color4 values to the current Color4 object
  1963. * @param right defines the second operand
  1964. * @returns the current updated Color4 object
  1965. */
  1966. Color4.prototype.addInPlace = function (right) {
  1967. this.r += right.r;
  1968. this.g += right.g;
  1969. this.b += right.b;
  1970. this.a += right.a;
  1971. return this;
  1972. };
  1973. /**
  1974. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1975. * @returns the new array
  1976. */
  1977. Color4.prototype.asArray = function () {
  1978. var result = new Array();
  1979. this.toArray(result, 0);
  1980. return result;
  1981. };
  1982. /**
  1983. * Stores from the starting index in the passed array the Color4 successive values
  1984. * @param array defines the array where to store the r,g,b components
  1985. * @param index defines an optional index in the target array to define where to start storing values
  1986. * @returns the current Color4 object
  1987. */
  1988. Color4.prototype.toArray = function (array, index) {
  1989. if (index === undefined) {
  1990. index = 0;
  1991. }
  1992. array[index] = this.r;
  1993. array[index + 1] = this.g;
  1994. array[index + 2] = this.b;
  1995. array[index + 3] = this.a;
  1996. return this;
  1997. };
  1998. /**
  1999. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  2000. * @param right defines the second operand
  2001. * @returns a new Color4 object
  2002. */
  2003. Color4.prototype.add = function (right) {
  2004. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  2005. };
  2006. /**
  2007. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  2008. * @param right defines the second operand
  2009. * @returns a new Color4 object
  2010. */
  2011. Color4.prototype.subtract = function (right) {
  2012. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  2013. };
  2014. /**
  2015. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  2016. * @param right defines the second operand
  2017. * @param result defines the Color4 object where to store the result
  2018. * @returns the current Color4 object
  2019. */
  2020. Color4.prototype.subtractToRef = function (right, result) {
  2021. result.r = this.r - right.r;
  2022. result.g = this.g - right.g;
  2023. result.b = this.b - right.b;
  2024. result.a = this.a - right.a;
  2025. return this;
  2026. };
  2027. /**
  2028. * Creates a new Color4 with the current Color4 values multiplied by scale
  2029. * @param scale defines the scaling factor to apply
  2030. * @returns a new Color4 object
  2031. */
  2032. Color4.prototype.scale = function (scale) {
  2033. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2034. };
  2035. /**
  2036. * Multiplies the current Color4 values by scale and stores the result in "result"
  2037. * @param scale defines the scaling factor to apply
  2038. * @param result defines the Color4 object where to store the result
  2039. * @returns the current unmodified Color4
  2040. */
  2041. Color4.prototype.scaleToRef = function (scale, result) {
  2042. result.r = this.r * scale;
  2043. result.g = this.g * scale;
  2044. result.b = this.b * scale;
  2045. result.a = this.a * scale;
  2046. return this;
  2047. };
  2048. /**
  2049. * Scale the current Color4 values by a factor and add the result to a given Color4
  2050. * @param scale defines the scale factor
  2051. * @param result defines the Color4 object where to store the result
  2052. * @returns the unmodified current Color4
  2053. */
  2054. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2055. result.r += this.r * scale;
  2056. result.g += this.g * scale;
  2057. result.b += this.b * scale;
  2058. result.a += this.a * scale;
  2059. return this;
  2060. };
  2061. /**
  2062. * Clamps the rgb values by the min and max values and stores the result into "result"
  2063. * @param min defines minimum clamping value (default is 0)
  2064. * @param max defines maximum clamping value (default is 1)
  2065. * @param result defines color to store the result into.
  2066. * @returns the cuurent Color4
  2067. */
  2068. Color4.prototype.clampToRef = function (min, max, result) {
  2069. if (min === void 0) { min = 0; }
  2070. if (max === void 0) { max = 1; }
  2071. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2072. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2073. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2074. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2075. return this;
  2076. };
  2077. /**
  2078. * Multipy an Color4 value by another and return a new Color4 object
  2079. * @param color defines the Color4 value to multiply by
  2080. * @returns a new Color4 object
  2081. */
  2082. Color4.prototype.multiply = function (color) {
  2083. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2084. };
  2085. /**
  2086. * Multipy a Color4 value by another and push the result in a reference value
  2087. * @param color defines the Color4 value to multiply by
  2088. * @param result defines the Color4 to fill the result in
  2089. * @returns the result Color4
  2090. */
  2091. Color4.prototype.multiplyToRef = function (color, result) {
  2092. result.r = this.r * color.r;
  2093. result.g = this.g * color.g;
  2094. result.b = this.b * color.b;
  2095. result.a = this.a * color.a;
  2096. return result;
  2097. };
  2098. /**
  2099. * Creates a string with the Color4 current values
  2100. * @returns the string representation of the Color4 object
  2101. */
  2102. Color4.prototype.toString = function () {
  2103. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2104. };
  2105. /**
  2106. * Returns the string "Color4"
  2107. * @returns "Color4"
  2108. */
  2109. Color4.prototype.getClassName = function () {
  2110. return "Color4";
  2111. };
  2112. /**
  2113. * Compute the Color4 hash code
  2114. * @returns an unique number that can be used to hash Color4 objects
  2115. */
  2116. Color4.prototype.getHashCode = function () {
  2117. var hash = this.r || 0;
  2118. hash = (hash * 397) ^ (this.g || 0);
  2119. hash = (hash * 397) ^ (this.b || 0);
  2120. hash = (hash * 397) ^ (this.a || 0);
  2121. return hash;
  2122. };
  2123. /**
  2124. * Creates a new Color4 copied from the current one
  2125. * @returns a new Color4 object
  2126. */
  2127. Color4.prototype.clone = function () {
  2128. return new Color4(this.r, this.g, this.b, this.a);
  2129. };
  2130. /**
  2131. * Copies the passed Color4 values into the current one
  2132. * @param source defines the source Color4 object
  2133. * @returns the current updated Color4 object
  2134. */
  2135. Color4.prototype.copyFrom = function (source) {
  2136. this.r = source.r;
  2137. this.g = source.g;
  2138. this.b = source.b;
  2139. this.a = source.a;
  2140. return this;
  2141. };
  2142. /**
  2143. * Copies the passed float values into the current one
  2144. * @param r defines the red component to read from
  2145. * @param g defines the green component to read from
  2146. * @param b defines the blue component to read from
  2147. * @param a defines the alpha component to read from
  2148. * @returns the current updated Color4 object
  2149. */
  2150. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2151. this.r = r;
  2152. this.g = g;
  2153. this.b = b;
  2154. this.a = a;
  2155. return this;
  2156. };
  2157. /**
  2158. * Copies the passed float values into the current one
  2159. * @param r defines the red component to read from
  2160. * @param g defines the green component to read from
  2161. * @param b defines the blue component to read from
  2162. * @param a defines the alpha component to read from
  2163. * @returns the current updated Color4 object
  2164. */
  2165. Color4.prototype.set = function (r, g, b, a) {
  2166. return this.copyFromFloats(r, g, b, a);
  2167. };
  2168. /**
  2169. * Compute the Color4 hexadecimal code as a string
  2170. * @returns a string containing the hexadecimal representation of the Color4 object
  2171. */
  2172. Color4.prototype.toHexString = function () {
  2173. var intR = (this.r * 255) | 0;
  2174. var intG = (this.g * 255) | 0;
  2175. var intB = (this.b * 255) | 0;
  2176. var intA = (this.a * 255) | 0;
  2177. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2178. };
  2179. /**
  2180. * Computes a new Color4 converted from the current one to linear space
  2181. * @returns a new Color4 object
  2182. */
  2183. Color4.prototype.toLinearSpace = function () {
  2184. var convertedColor = new Color4();
  2185. this.toLinearSpaceToRef(convertedColor);
  2186. return convertedColor;
  2187. };
  2188. /**
  2189. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2190. * @param convertedColor defines the Color4 object where to store the linear space version
  2191. * @returns the unmodified Color4
  2192. */
  2193. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2194. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2195. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2196. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2197. convertedColor.a = this.a;
  2198. return this;
  2199. };
  2200. /**
  2201. * Computes a new Color4 converted from the current one to gamma space
  2202. * @returns a new Color4 object
  2203. */
  2204. Color4.prototype.toGammaSpace = function () {
  2205. var convertedColor = new Color4();
  2206. this.toGammaSpaceToRef(convertedColor);
  2207. return convertedColor;
  2208. };
  2209. /**
  2210. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2211. * @param convertedColor defines the Color4 object where to store the gamma space version
  2212. * @returns the unmodified Color4
  2213. */
  2214. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2215. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2216. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2217. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2218. convertedColor.a = this.a;
  2219. return this;
  2220. };
  2221. // Statics
  2222. /**
  2223. * Creates a new Color4 from the string containing valid hexadecimal values
  2224. * @param hex defines a string containing valid hexadecimal values
  2225. * @returns a new Color4 object
  2226. */
  2227. Color4.FromHexString = function (hex) {
  2228. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2229. return new Color4(0.0, 0.0, 0.0, 0.0);
  2230. }
  2231. var r = parseInt(hex.substring(1, 3), 16);
  2232. var g = parseInt(hex.substring(3, 5), 16);
  2233. var b = parseInt(hex.substring(5, 7), 16);
  2234. var a = parseInt(hex.substring(7, 9), 16);
  2235. return Color4.FromInts(r, g, b, a);
  2236. };
  2237. /**
  2238. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2239. * @param left defines the start value
  2240. * @param right defines the end value
  2241. * @param amount defines the gradient factor
  2242. * @returns a new Color4 object
  2243. */
  2244. Color4.Lerp = function (left, right, amount) {
  2245. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2246. Color4.LerpToRef(left, right, amount, result);
  2247. return result;
  2248. };
  2249. /**
  2250. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2251. * @param left defines the start value
  2252. * @param right defines the end value
  2253. * @param amount defines the gradient factor
  2254. * @param result defines the Color4 object where to store data
  2255. */
  2256. Color4.LerpToRef = function (left, right, amount, result) {
  2257. result.r = left.r + (right.r - left.r) * amount;
  2258. result.g = left.g + (right.g - left.g) * amount;
  2259. result.b = left.b + (right.b - left.b) * amount;
  2260. result.a = left.a + (right.a - left.a) * amount;
  2261. };
  2262. /**
  2263. * Creates a new Color4 from the starting index element of the passed array
  2264. * @param array defines the source array to read from
  2265. * @param offset defines the offset in the source array
  2266. * @returns a new Color4 object
  2267. */
  2268. Color4.FromArray = function (array, offset) {
  2269. if (offset === void 0) { offset = 0; }
  2270. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2271. };
  2272. /**
  2273. * Creates a new Color3 from integer values (< 256)
  2274. * @param r defines the red component to read from (value between 0 and 255)
  2275. * @param g defines the green component to read from (value between 0 and 255)
  2276. * @param b defines the blue component to read from (value between 0 and 255)
  2277. * @param a defines the alpha component to read from (value between 0 and 255)
  2278. * @returns a new Color3 object
  2279. */
  2280. Color4.FromInts = function (r, g, b, a) {
  2281. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2282. };
  2283. /**
  2284. * Check the content of a given array and convert it to an array containing RGBA data
  2285. * If the original array was already containing count * 4 values then it is returned directly
  2286. * @param colors defines the array to check
  2287. * @param count defines the number of RGBA data to expect
  2288. * @returns an array containing count * 4 values (RGBA)
  2289. */
  2290. Color4.CheckColors4 = function (colors, count) {
  2291. // Check if color3 was used
  2292. if (colors.length === count * 3) {
  2293. var colors4 = [];
  2294. for (var index = 0; index < colors.length; index += 3) {
  2295. var newIndex = (index / 3) * 4;
  2296. colors4[newIndex] = colors[index];
  2297. colors4[newIndex + 1] = colors[index + 1];
  2298. colors4[newIndex + 2] = colors[index + 2];
  2299. colors4[newIndex + 3] = 1.0;
  2300. }
  2301. return colors4;
  2302. }
  2303. return colors;
  2304. };
  2305. return Color4;
  2306. }());
  2307. BABYLON.Color4 = Color4;
  2308. var Vector2 = /** @class */ (function () {
  2309. /**
  2310. * Creates a new Vector2 from the passed x and y coordinates.
  2311. */
  2312. function Vector2(x, y) {
  2313. this.x = x;
  2314. this.y = y;
  2315. }
  2316. /**
  2317. * Returns a string with the Vector2 coordinates.
  2318. */
  2319. Vector2.prototype.toString = function () {
  2320. return "{X: " + this.x + " Y:" + this.y + "}";
  2321. };
  2322. /**
  2323. * Returns the string "Vector2"
  2324. */
  2325. Vector2.prototype.getClassName = function () {
  2326. return "Vector2";
  2327. };
  2328. /**
  2329. * Returns the Vector2 hash code as a number.
  2330. */
  2331. Vector2.prototype.getHashCode = function () {
  2332. var hash = this.x || 0;
  2333. hash = (hash * 397) ^ (this.y || 0);
  2334. return hash;
  2335. };
  2336. // Operators
  2337. /**
  2338. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2339. * Returns the Vector2.
  2340. */
  2341. Vector2.prototype.toArray = function (array, index) {
  2342. if (index === void 0) { index = 0; }
  2343. array[index] = this.x;
  2344. array[index + 1] = this.y;
  2345. return this;
  2346. };
  2347. /**
  2348. * Returns a new array with 2 elements : the Vector2 coordinates.
  2349. */
  2350. Vector2.prototype.asArray = function () {
  2351. var result = new Array();
  2352. this.toArray(result, 0);
  2353. return result;
  2354. };
  2355. /**
  2356. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2357. * Returns the updated Vector2.
  2358. */
  2359. Vector2.prototype.copyFrom = function (source) {
  2360. this.x = source.x;
  2361. this.y = source.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Sets the Vector2 coordinates with the passed floats.
  2366. * Returns the updated Vector2.
  2367. */
  2368. Vector2.prototype.copyFromFloats = function (x, y) {
  2369. this.x = x;
  2370. this.y = y;
  2371. return this;
  2372. };
  2373. /**
  2374. * Sets the Vector2 coordinates with the passed floats.
  2375. * Returns the updated Vector2.
  2376. */
  2377. Vector2.prototype.set = function (x, y) {
  2378. return this.copyFromFloats(x, y);
  2379. };
  2380. /**
  2381. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2382. */
  2383. Vector2.prototype.add = function (otherVector) {
  2384. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2385. };
  2386. /**
  2387. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2388. * Returns the Vector2.
  2389. */
  2390. Vector2.prototype.addToRef = function (otherVector, result) {
  2391. result.x = this.x + otherVector.x;
  2392. result.y = this.y + otherVector.y;
  2393. return this;
  2394. };
  2395. /**
  2396. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2397. * Returns the updated Vector2.
  2398. */
  2399. Vector2.prototype.addInPlace = function (otherVector) {
  2400. this.x += otherVector.x;
  2401. this.y += otherVector.y;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2406. */
  2407. Vector2.prototype.addVector3 = function (otherVector) {
  2408. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2409. };
  2410. /**
  2411. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2412. */
  2413. Vector2.prototype.subtract = function (otherVector) {
  2414. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2415. };
  2416. /**
  2417. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2418. * Returns the Vector2.
  2419. */
  2420. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2421. result.x = this.x - otherVector.x;
  2422. result.y = this.y - otherVector.y;
  2423. return this;
  2424. };
  2425. /**
  2426. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2427. * Returns the updated Vector2.
  2428. */
  2429. Vector2.prototype.subtractInPlace = function (otherVector) {
  2430. this.x -= otherVector.x;
  2431. this.y -= otherVector.y;
  2432. return this;
  2433. };
  2434. /**
  2435. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2436. * Returns the updated Vector2.
  2437. */
  2438. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2439. this.x *= otherVector.x;
  2440. this.y *= otherVector.y;
  2441. return this;
  2442. };
  2443. /**
  2444. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2445. */
  2446. Vector2.prototype.multiply = function (otherVector) {
  2447. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2448. };
  2449. /**
  2450. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2451. * Returns the Vector2.
  2452. */
  2453. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2454. result.x = this.x * otherVector.x;
  2455. result.y = this.y * otherVector.y;
  2456. return this;
  2457. };
  2458. /**
  2459. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2460. */
  2461. Vector2.prototype.multiplyByFloats = function (x, y) {
  2462. return new Vector2(this.x * x, this.y * y);
  2463. };
  2464. /**
  2465. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2466. */
  2467. Vector2.prototype.divide = function (otherVector) {
  2468. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2469. };
  2470. /**
  2471. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2472. * Returns the Vector2.
  2473. */
  2474. Vector2.prototype.divideToRef = function (otherVector, result) {
  2475. result.x = this.x / otherVector.x;
  2476. result.y = this.y / otherVector.y;
  2477. return this;
  2478. };
  2479. /**
  2480. * Divides the current Vector3 coordinates by the passed ones.
  2481. * Returns the updated Vector3.
  2482. */
  2483. Vector2.prototype.divideInPlace = function (otherVector) {
  2484. return this.divideToRef(otherVector, this);
  2485. };
  2486. /**
  2487. * Returns a new Vector2 with current Vector2 negated coordinates.
  2488. */
  2489. Vector2.prototype.negate = function () {
  2490. return new Vector2(-this.x, -this.y);
  2491. };
  2492. /**
  2493. * Multiply the Vector2 coordinates by scale.
  2494. * Returns the updated Vector2.
  2495. */
  2496. Vector2.prototype.scaleInPlace = function (scale) {
  2497. this.x *= scale;
  2498. this.y *= scale;
  2499. return this;
  2500. };
  2501. /**
  2502. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2503. */
  2504. Vector2.prototype.scale = function (scale) {
  2505. var result = new Vector2(0, 0);
  2506. this.scaleToRef(scale, result);
  2507. return result;
  2508. };
  2509. /**
  2510. * Scale the current Vector2 values by a factor to a given Vector2
  2511. * @param scale defines the scale factor
  2512. * @param result defines the Vector2 object where to store the result
  2513. * @returns the unmodified current Vector2
  2514. */
  2515. Vector2.prototype.scaleToRef = function (scale, result) {
  2516. result.x = this.x * scale;
  2517. result.y = this.y * scale;
  2518. return this;
  2519. };
  2520. /**
  2521. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2522. * @param scale defines the scale factor
  2523. * @param result defines the Vector2 object where to store the result
  2524. * @returns the unmodified current Vector2
  2525. */
  2526. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2527. result.x += this.x * scale;
  2528. result.y += this.y * scale;
  2529. return this;
  2530. };
  2531. /**
  2532. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2533. */
  2534. Vector2.prototype.equals = function (otherVector) {
  2535. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2536. };
  2537. /**
  2538. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2539. */
  2540. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2541. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2542. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2543. };
  2544. // Properties
  2545. /**
  2546. * Returns the vector length (float).
  2547. */
  2548. Vector2.prototype.length = function () {
  2549. return Math.sqrt(this.x * this.x + this.y * this.y);
  2550. };
  2551. /**
  2552. * Returns the vector squared length (float);
  2553. */
  2554. Vector2.prototype.lengthSquared = function () {
  2555. return (this.x * this.x + this.y * this.y);
  2556. };
  2557. // Methods
  2558. /**
  2559. * Normalize the vector.
  2560. * Returns the updated Vector2.
  2561. */
  2562. Vector2.prototype.normalize = function () {
  2563. var len = this.length();
  2564. if (len === 0)
  2565. return this;
  2566. var num = 1.0 / len;
  2567. this.x *= num;
  2568. this.y *= num;
  2569. return this;
  2570. };
  2571. /**
  2572. * Returns a new Vector2 copied from the Vector2.
  2573. */
  2574. Vector2.prototype.clone = function () {
  2575. return new Vector2(this.x, this.y);
  2576. };
  2577. // Statics
  2578. /**
  2579. * Returns a new Vector2(0, 0)
  2580. */
  2581. Vector2.Zero = function () {
  2582. return new Vector2(0, 0);
  2583. };
  2584. /**
  2585. * Returns a new Vector2(1, 1)
  2586. */
  2587. Vector2.One = function () {
  2588. return new Vector2(1, 1);
  2589. };
  2590. /**
  2591. * Returns a new Vector2 set from the passed index element of the passed array.
  2592. */
  2593. Vector2.FromArray = function (array, offset) {
  2594. if (offset === void 0) { offset = 0; }
  2595. return new Vector2(array[offset], array[offset + 1]);
  2596. };
  2597. /**
  2598. * Sets "result" from the passed index element of the passed array.
  2599. */
  2600. Vector2.FromArrayToRef = function (array, offset, result) {
  2601. result.x = array[offset];
  2602. result.y = array[offset + 1];
  2603. };
  2604. /**
  2605. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2606. */
  2607. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2608. var squared = amount * amount;
  2609. var cubed = amount * squared;
  2610. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2611. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2612. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2613. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2614. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2615. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2616. return new Vector2(x, y);
  2617. };
  2618. /**
  2619. * 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".
  2620. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2621. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2622. */
  2623. Vector2.Clamp = function (value, min, max) {
  2624. var x = value.x;
  2625. x = (x > max.x) ? max.x : x;
  2626. x = (x < min.x) ? min.x : x;
  2627. var y = value.y;
  2628. y = (y > max.y) ? max.y : y;
  2629. y = (y < min.y) ? min.y : y;
  2630. return new Vector2(x, y);
  2631. };
  2632. /**
  2633. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2634. */
  2635. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2636. var squared = amount * amount;
  2637. var cubed = amount * squared;
  2638. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2639. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2640. var part3 = (cubed - (2.0 * squared)) + amount;
  2641. var part4 = cubed - squared;
  2642. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2643. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2644. return new Vector2(x, y);
  2645. };
  2646. /**
  2647. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2648. */
  2649. Vector2.Lerp = function (start, end, amount) {
  2650. var x = start.x + ((end.x - start.x) * amount);
  2651. var y = start.y + ((end.y - start.y) * amount);
  2652. return new Vector2(x, y);
  2653. };
  2654. /**
  2655. * Returns the dot product (float) of the vector "left" and the vector "right".
  2656. */
  2657. Vector2.Dot = function (left, right) {
  2658. return left.x * right.x + left.y * right.y;
  2659. };
  2660. /**
  2661. * Returns a new Vector2 equal to the normalized passed vector.
  2662. */
  2663. Vector2.Normalize = function (vector) {
  2664. var newVector = vector.clone();
  2665. newVector.normalize();
  2666. return newVector;
  2667. };
  2668. /**
  2669. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2670. */
  2671. Vector2.Minimize = function (left, right) {
  2672. var x = (left.x < right.x) ? left.x : right.x;
  2673. var y = (left.y < right.y) ? left.y : right.y;
  2674. return new Vector2(x, y);
  2675. };
  2676. /**
  2677. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2678. */
  2679. Vector2.Maximize = function (left, right) {
  2680. var x = (left.x > right.x) ? left.x : right.x;
  2681. var y = (left.y > right.y) ? left.y : right.y;
  2682. return new Vector2(x, y);
  2683. };
  2684. /**
  2685. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2686. */
  2687. Vector2.Transform = function (vector, transformation) {
  2688. var r = Vector2.Zero();
  2689. Vector2.TransformToRef(vector, transformation, r);
  2690. return r;
  2691. };
  2692. /**
  2693. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2694. */
  2695. Vector2.TransformToRef = function (vector, transformation, result) {
  2696. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2697. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2698. result.x = x;
  2699. result.y = y;
  2700. };
  2701. /**
  2702. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2703. */
  2704. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2705. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2706. var sign = a < 0 ? -1 : 1;
  2707. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2708. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2709. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2710. };
  2711. /**
  2712. * Returns the distance (float) between the vectors "value1" and "value2".
  2713. */
  2714. Vector2.Distance = function (value1, value2) {
  2715. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2716. };
  2717. /**
  2718. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2719. */
  2720. Vector2.DistanceSquared = function (value1, value2) {
  2721. var x = value1.x - value2.x;
  2722. var y = value1.y - value2.y;
  2723. return (x * x) + (y * y);
  2724. };
  2725. /**
  2726. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2727. */
  2728. Vector2.Center = function (value1, value2) {
  2729. var center = value1.add(value2);
  2730. center.scaleInPlace(0.5);
  2731. return center;
  2732. };
  2733. /**
  2734. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2735. */
  2736. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2737. var l2 = Vector2.DistanceSquared(segA, segB);
  2738. if (l2 === 0.0) {
  2739. return Vector2.Distance(p, segA);
  2740. }
  2741. var v = segB.subtract(segA);
  2742. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2743. var proj = segA.add(v.multiplyByFloats(t, t));
  2744. return Vector2.Distance(p, proj);
  2745. };
  2746. return Vector2;
  2747. }());
  2748. BABYLON.Vector2 = Vector2;
  2749. /**
  2750. * Classed used to store (x,y,z) vector representation
  2751. * A Vector3 is the main object used in 3D geometry
  2752. * It can represent etiher the coordinates of a point the space, either a direction
  2753. * Reminder: Babylon.js uses a left handed forward facing system
  2754. */
  2755. var Vector3 = /** @class */ (function () {
  2756. /**
  2757. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2758. * @param x defines the first coordinates (on X axis)
  2759. * @param y defines the second coordinates (on Y axis)
  2760. * @param z defines the third coordinates (on Z axis)
  2761. */
  2762. function Vector3(
  2763. /**
  2764. * Defines the first coordinates (on X axis)
  2765. */
  2766. x,
  2767. /**
  2768. * Defines the second coordinates (on Y axis)
  2769. */
  2770. y,
  2771. /**
  2772. * Defines the third coordinates (on Z axis)
  2773. */
  2774. z) {
  2775. this.x = x;
  2776. this.y = y;
  2777. this.z = z;
  2778. }
  2779. /**
  2780. * Creates a string representation of the Vector3
  2781. * @returns a string with the Vector3 coordinates.
  2782. */
  2783. Vector3.prototype.toString = function () {
  2784. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2785. };
  2786. /**
  2787. * Gets the class name
  2788. * @returns the string "Vector3"
  2789. */
  2790. Vector3.prototype.getClassName = function () {
  2791. return "Vector3";
  2792. };
  2793. /**
  2794. * Creates the Vector3 hash code
  2795. * @returns a number which tends to be unique between Vector3 instances
  2796. */
  2797. Vector3.prototype.getHashCode = function () {
  2798. var hash = this.x || 0;
  2799. hash = (hash * 397) ^ (this.y || 0);
  2800. hash = (hash * 397) ^ (this.z || 0);
  2801. return hash;
  2802. };
  2803. // Operators
  2804. /**
  2805. * Creates an array containing three elements : the coordinates of the Vector3
  2806. * @returns a new array of numbers
  2807. */
  2808. Vector3.prototype.asArray = function () {
  2809. var result = [];
  2810. this.toArray(result, 0);
  2811. return result;
  2812. };
  2813. /**
  2814. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2815. * @param array defines the destination array
  2816. * @param index defines the offset in the destination array
  2817. * @returns the current Vector3
  2818. */
  2819. Vector3.prototype.toArray = function (array, index) {
  2820. if (index === void 0) { index = 0; }
  2821. array[index] = this.x;
  2822. array[index + 1] = this.y;
  2823. array[index + 2] = this.z;
  2824. return this;
  2825. };
  2826. /**
  2827. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2828. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2829. */
  2830. Vector3.prototype.toQuaternion = function () {
  2831. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2832. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2833. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2834. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2835. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2836. var cosy = Math.cos(this.y * 0.5);
  2837. var siny = Math.sin(this.y * 0.5);
  2838. result.x = coszMinusx * siny;
  2839. result.y = -sinzMinusx * siny;
  2840. result.z = sinxPlusz * cosy;
  2841. result.w = cosxPlusz * cosy;
  2842. return result;
  2843. };
  2844. /**
  2845. * Adds the passed vector to the current Vector3
  2846. * @param otherVector defines the second operand
  2847. * @returns the current updated Vector3
  2848. */
  2849. Vector3.prototype.addInPlace = function (otherVector) {
  2850. this.x += otherVector.x;
  2851. this.y += otherVector.y;
  2852. this.z += otherVector.z;
  2853. return this;
  2854. };
  2855. /**
  2856. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2857. * @param otherVector defines the second operand
  2858. * @returns the resulting Vector3
  2859. */
  2860. Vector3.prototype.add = function (otherVector) {
  2861. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2862. };
  2863. /**
  2864. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2865. * @param otherVector defines the second operand
  2866. * @param result defines the Vector3 object where to store the result
  2867. * @returns the current Vector3
  2868. */
  2869. Vector3.prototype.addToRef = function (otherVector, result) {
  2870. result.x = this.x + otherVector.x;
  2871. result.y = this.y + otherVector.y;
  2872. result.z = this.z + otherVector.z;
  2873. return this;
  2874. };
  2875. /**
  2876. * Subtract the passed vector from the current Vector3
  2877. * @param otherVector defines the second operand
  2878. * @returns the current updated Vector3
  2879. */
  2880. Vector3.prototype.subtractInPlace = function (otherVector) {
  2881. this.x -= otherVector.x;
  2882. this.y -= otherVector.y;
  2883. this.z -= otherVector.z;
  2884. return this;
  2885. };
  2886. /**
  2887. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2888. * @param otherVector defines the second operand
  2889. * @returns the resulting Vector3
  2890. */
  2891. Vector3.prototype.subtract = function (otherVector) {
  2892. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2893. };
  2894. /**
  2895. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2896. * @param otherVector defines the second operand
  2897. * @param result defines the Vector3 object where to store the result
  2898. * @returns the current Vector3
  2899. */
  2900. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2901. result.x = this.x - otherVector.x;
  2902. result.y = this.y - otherVector.y;
  2903. result.z = this.z - otherVector.z;
  2904. return this;
  2905. };
  2906. /**
  2907. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2908. * @param x defines the x coordinate of the operand
  2909. * @param y defines the y coordinate of the operand
  2910. * @param z defines the z coordinate of the operand
  2911. * @returns the resulting Vector3
  2912. */
  2913. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2914. return new Vector3(this.x - x, this.y - y, this.z - z);
  2915. };
  2916. /**
  2917. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2918. * @param x defines the x coordinate of the operand
  2919. * @param y defines the y coordinate of the operand
  2920. * @param z defines the z coordinate of the operand
  2921. * @param result defines the Vector3 object where to store the result
  2922. * @returns the current Vector3
  2923. */
  2924. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2925. result.x = this.x - x;
  2926. result.y = this.y - y;
  2927. result.z = this.z - z;
  2928. return this;
  2929. };
  2930. /**
  2931. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.negate = function () {
  2935. return new Vector3(-this.x, -this.y, -this.z);
  2936. };
  2937. /**
  2938. * Multiplies the Vector3 coordinates by the float "scale"
  2939. * @param scale defines the multiplier factor
  2940. * @returns the current updated Vector3
  2941. */
  2942. Vector3.prototype.scaleInPlace = function (scale) {
  2943. this.x *= scale;
  2944. this.y *= scale;
  2945. this.z *= scale;
  2946. return this;
  2947. };
  2948. /**
  2949. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2950. * @param scale defines the multiplier factor
  2951. * @returns a new Vector3
  2952. */
  2953. Vector3.prototype.scale = function (scale) {
  2954. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2955. };
  2956. /**
  2957. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2958. * @param scale defines the multiplier factor
  2959. * @param result defines the Vector3 object where to store the result
  2960. * @returns the current Vector3
  2961. */
  2962. Vector3.prototype.scaleToRef = function (scale, result) {
  2963. result.x = this.x * scale;
  2964. result.y = this.y * scale;
  2965. result.z = this.z * scale;
  2966. return this;
  2967. };
  2968. /**
  2969. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2970. * @param scale defines the scale factor
  2971. * @param result defines the Vector3 object where to store the result
  2972. * @returns the unmodified current Vector3
  2973. */
  2974. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2975. result.x += this.x * scale;
  2976. result.y += this.y * scale;
  2977. result.z += this.z * scale;
  2978. return this;
  2979. };
  2980. /**
  2981. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2982. * @param otherVector defines the second operand
  2983. * @returns true if both vectors are equals
  2984. */
  2985. Vector3.prototype.equals = function (otherVector) {
  2986. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2987. };
  2988. /**
  2989. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2990. * @param otherVector defines the second operand
  2991. * @param epsilon defines the minimal distance to define values as equals
  2992. * @returns true if both vectors are distant less than epsilon
  2993. */
  2994. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2995. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2996. 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);
  2997. };
  2998. /**
  2999. * Returns true if the current Vector3 coordinates equals the passed floats
  3000. * @param x defines the x coordinate of the operand
  3001. * @param y defines the y coordinate of the operand
  3002. * @param z defines the z coordinate of the operand
  3003. * @returns true if both vectors are equals
  3004. */
  3005. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3006. return this.x === x && this.y === y && this.z === z;
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 coordinates by the passed ones
  3010. * @param otherVector defines the second operand
  3011. * @returns the current updated Vector3
  3012. */
  3013. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3014. this.x *= otherVector.x;
  3015. this.y *= otherVector.y;
  3016. this.z *= otherVector.z;
  3017. return this;
  3018. };
  3019. /**
  3020. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  3021. * @param otherVector defines the second operand
  3022. * @returns the new Vector3
  3023. */
  3024. Vector3.prototype.multiply = function (otherVector) {
  3025. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3026. };
  3027. /**
  3028. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  3029. * @param otherVector defines the second operand
  3030. * @param result defines the Vector3 object where to store the result
  3031. * @returns the current Vector3
  3032. */
  3033. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3034. result.x = this.x * otherVector.x;
  3035. result.y = this.y * otherVector.y;
  3036. result.z = this.z * otherVector.z;
  3037. return this;
  3038. };
  3039. /**
  3040. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  3041. * @param x defines the x coordinate of the operand
  3042. * @param y defines the y coordinate of the operand
  3043. * @param z defines the z coordinate of the operand
  3044. * @returns the new Vector3
  3045. */
  3046. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3047. return new Vector3(this.x * x, this.y * y, this.z * z);
  3048. };
  3049. /**
  3050. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  3051. * @param otherVector defines the second operand
  3052. * @returns the new Vector3
  3053. */
  3054. Vector3.prototype.divide = function (otherVector) {
  3055. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3056. };
  3057. /**
  3058. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  3059. * @param otherVector defines the second operand
  3060. * @param result defines the Vector3 object where to store the result
  3061. * @returns the current Vector3
  3062. */
  3063. Vector3.prototype.divideToRef = function (otherVector, result) {
  3064. result.x = this.x / otherVector.x;
  3065. result.y = this.y / otherVector.y;
  3066. result.z = this.z / otherVector.z;
  3067. return this;
  3068. };
  3069. /**
  3070. * Divides the current Vector3 coordinates by the passed ones.
  3071. * @param otherVector defines the second operand
  3072. * @returns the current updated Vector3
  3073. */
  3074. Vector3.prototype.divideInPlace = function (otherVector) {
  3075. return this.divideToRef(otherVector, this);
  3076. };
  3077. /**
  3078. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3079. * @param other defines the second operand
  3080. * @returns the current updated Vector3
  3081. */
  3082. Vector3.prototype.minimizeInPlace = function (other) {
  3083. if (other.x < this.x)
  3084. this.x = other.x;
  3085. if (other.y < this.y)
  3086. this.y = other.y;
  3087. if (other.z < this.z)
  3088. this.z = other.z;
  3089. return this;
  3090. };
  3091. /**
  3092. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3093. * @param other defines the second operand
  3094. * @returns the current updated Vector3
  3095. */
  3096. Vector3.prototype.maximizeInPlace = function (other) {
  3097. if (other.x > this.x)
  3098. this.x = other.x;
  3099. if (other.y > this.y)
  3100. this.y = other.y;
  3101. if (other.z > this.z)
  3102. this.z = other.z;
  3103. return this;
  3104. };
  3105. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3106. /**
  3107. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3108. */
  3109. get: function () {
  3110. var absX = Math.abs(this.x);
  3111. var absY = Math.abs(this.y);
  3112. if (absX !== absY) {
  3113. return true;
  3114. }
  3115. var absZ = Math.abs(this.z);
  3116. if (absX !== absZ) {
  3117. return true;
  3118. }
  3119. if (absY !== absZ) {
  3120. return true;
  3121. }
  3122. return false;
  3123. },
  3124. enumerable: true,
  3125. configurable: true
  3126. });
  3127. // Properties
  3128. /**
  3129. * Gets the length of the Vector3
  3130. * @returns the length of the Vecto3
  3131. */
  3132. Vector3.prototype.length = function () {
  3133. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3134. };
  3135. /**
  3136. * Gets the squared length of the Vector3
  3137. * @returns squared length of the Vector3
  3138. */
  3139. Vector3.prototype.lengthSquared = function () {
  3140. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3141. };
  3142. /**
  3143. * Normalize the current Vector3.
  3144. * Please note that this is an in place operation.
  3145. * @returns the current updated Vector3
  3146. */
  3147. Vector3.prototype.normalize = function () {
  3148. var len = this.length();
  3149. if (len === 0 || len === 1.0)
  3150. return this;
  3151. var num = 1.0 / len;
  3152. this.x *= num;
  3153. this.y *= num;
  3154. this.z *= num;
  3155. return this;
  3156. };
  3157. /**
  3158. * Normalize the current Vector3 to a new vector
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.prototype.normalizeToNew = function () {
  3162. var normalized = new Vector3(0, 0, 0);
  3163. this.normalizeToRef(normalized);
  3164. return normalized;
  3165. };
  3166. /**
  3167. * Normalize the current Vector3 to the reference
  3168. * @param reference define the Vector3 to update
  3169. * @returns the updated Vector3
  3170. */
  3171. Vector3.prototype.normalizeToRef = function (reference) {
  3172. var len = this.length();
  3173. if (len === 0 || len === 1.0) {
  3174. reference.set(this.x, this.y, this.z);
  3175. return reference;
  3176. }
  3177. var scale = 1.0 / len;
  3178. this.scaleToRef(scale, reference);
  3179. return reference;
  3180. };
  3181. /**
  3182. * Creates a new Vector3 copied from the current Vector3
  3183. * @returns the new Vector3
  3184. */
  3185. Vector3.prototype.clone = function () {
  3186. return new Vector3(this.x, this.y, this.z);
  3187. };
  3188. /**
  3189. * Copies the passed vector coordinates to the current Vector3 ones
  3190. * @param source defines the source Vector3
  3191. * @returns the current updated Vector3
  3192. */
  3193. Vector3.prototype.copyFrom = function (source) {
  3194. this.x = source.x;
  3195. this.y = source.y;
  3196. this.z = source.z;
  3197. return this;
  3198. };
  3199. /**
  3200. * Copies the passed floats to the current Vector3 coordinates
  3201. * @param x defines the x coordinate of the operand
  3202. * @param y defines the y coordinate of the operand
  3203. * @param z defines the z coordinate of the operand
  3204. * @returns the current updated Vector3
  3205. */
  3206. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3207. this.x = x;
  3208. this.y = y;
  3209. this.z = z;
  3210. return this;
  3211. };
  3212. /**
  3213. * Copies the passed floats to the current Vector3 coordinates
  3214. * @param x defines the x coordinate of the operand
  3215. * @param y defines the y coordinate of the operand
  3216. * @param z defines the z coordinate of the operand
  3217. * @returns the current updated Vector3
  3218. */
  3219. Vector3.prototype.set = function (x, y, z) {
  3220. return this.copyFromFloats(x, y, z);
  3221. };
  3222. // Statics
  3223. /**
  3224. * Get the clip factor between two vectors
  3225. * @param vector0 defines the first operand
  3226. * @param vector1 defines the second operand
  3227. * @param axis defines the axis to use
  3228. * @param size defines the size along the axis
  3229. * @returns the clip factor
  3230. */
  3231. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3232. var d0 = Vector3.Dot(vector0, axis) - size;
  3233. var d1 = Vector3.Dot(vector1, axis) - size;
  3234. var s = d0 / (d0 - d1);
  3235. return s;
  3236. };
  3237. /**
  3238. * Get angle between two vectors
  3239. * @param vector0 angle between vector0 and vector1
  3240. * @param vector1 angle between vector0 and vector1
  3241. * @param normal direction of the normal
  3242. * @return the angle between vector0 and vector1
  3243. */
  3244. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3245. var v0 = vector0.clone().normalize();
  3246. var v1 = vector1.clone().normalize();
  3247. var dot = Vector3.Dot(v0, v1);
  3248. var n = Vector3.Cross(v0, v1);
  3249. if (Vector3.Dot(n, normal) > 0) {
  3250. return Math.acos(dot);
  3251. }
  3252. return -Math.acos(dot);
  3253. };
  3254. /**
  3255. * Returns a new Vector3 set from the index "offset" of the passed array
  3256. * @param array defines the source array
  3257. * @param offset defines the offset in the source array
  3258. * @returns the new Vector3
  3259. */
  3260. Vector3.FromArray = function (array, offset) {
  3261. if (!offset) {
  3262. offset = 0;
  3263. }
  3264. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3265. };
  3266. /**
  3267. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3268. * This function is deprecated. Use FromArray instead
  3269. * @param array defines the source array
  3270. * @param offset defines the offset in the source array
  3271. * @returns the new Vector3
  3272. */
  3273. Vector3.FromFloatArray = function (array, offset) {
  3274. return Vector3.FromArray(array, offset);
  3275. };
  3276. /**
  3277. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3278. * @param array defines the source array
  3279. * @param offset defines the offset in the source array
  3280. * @param result defines the Vector3 where to store the result
  3281. */
  3282. Vector3.FromArrayToRef = function (array, offset, result) {
  3283. result.x = array[offset];
  3284. result.y = array[offset + 1];
  3285. result.z = array[offset + 2];
  3286. };
  3287. /**
  3288. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3289. * This function is deprecated. Use FromArrayToRef instead.
  3290. * @param array defines the source array
  3291. * @param offset defines the offset in the source array
  3292. * @param result defines the Vector3 where to store the result
  3293. */
  3294. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3295. return Vector3.FromArrayToRef(array, offset, result);
  3296. };
  3297. /**
  3298. * Sets the passed vector "result" with the passed floats.
  3299. * @param x defines the x coordinate of the source
  3300. * @param y defines the y coordinate of the source
  3301. * @param z defines the z coordinate of the source
  3302. * @param result defines the Vector3 where to store the result
  3303. */
  3304. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3305. result.x = x;
  3306. result.y = y;
  3307. result.z = z;
  3308. };
  3309. /**
  3310. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3311. * @returns a new empty Vector3
  3312. */
  3313. Vector3.Zero = function () {
  3314. return new Vector3(0.0, 0.0, 0.0);
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3318. * @returns a new unit Vector3
  3319. */
  3320. Vector3.One = function () {
  3321. return new Vector3(1.0, 1.0, 1.0);
  3322. };
  3323. /**
  3324. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3325. * @returns a new up Vector3
  3326. */
  3327. Vector3.Up = function () {
  3328. return new Vector3(0.0, 1.0, 0.0);
  3329. };
  3330. /**
  3331. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3332. * @returns a new forward Vector3
  3333. */
  3334. Vector3.Forward = function () {
  3335. return new Vector3(0.0, 0.0, 1.0);
  3336. };
  3337. /**
  3338. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3339. * @returns a new right Vector3
  3340. */
  3341. Vector3.Right = function () {
  3342. return new Vector3(1.0, 0.0, 0.0);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3346. * @returns a new left Vector3
  3347. */
  3348. Vector3.Left = function () {
  3349. return new Vector3(-1.0, 0.0, 0.0);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @returns the transformed Vector3
  3357. */
  3358. Vector3.TransformCoordinates = function (vector, transformation) {
  3359. var result = Vector3.Zero();
  3360. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3361. return result;
  3362. };
  3363. /**
  3364. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3365. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3366. * @param vector defines the Vector3 to transform
  3367. * @param transformation defines the transformation matrix
  3368. * @param result defines the Vector3 where to store the result
  3369. */
  3370. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3371. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3372. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3373. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3374. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3375. result.x = x / w;
  3376. result.y = y / w;
  3377. result.z = z / w;
  3378. };
  3379. /**
  3380. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3381. * This method computes tranformed coordinates only, not transformed direction vectors
  3382. * @param x define the x coordinate of the source vector
  3383. * @param y define the y coordinate of the source vector
  3384. * @param z define the z coordinate of the source vector
  3385. * @param transformation defines the transformation matrix
  3386. * @param result defines the Vector3 where to store the result
  3387. */
  3388. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3389. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3390. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3391. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3392. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3393. result.x = rx / rw;
  3394. result.y = ry / rw;
  3395. result.z = rz / rw;
  3396. };
  3397. /**
  3398. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @returns the new Vector3
  3403. */
  3404. Vector3.TransformNormal = function (vector, transformation) {
  3405. var result = Vector3.Zero();
  3406. Vector3.TransformNormalToRef(vector, transformation, result);
  3407. return result;
  3408. };
  3409. /**
  3410. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3411. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3412. * @param vector defines the Vector3 to transform
  3413. * @param transformation defines the transformation matrix
  3414. * @param result defines the Vector3 where to store the result
  3415. */
  3416. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3417. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3418. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3419. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3420. result.x = x;
  3421. result.y = y;
  3422. result.z = z;
  3423. };
  3424. /**
  3425. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3426. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3427. * @param x define the x coordinate of the source vector
  3428. * @param y define the y coordinate of the source vector
  3429. * @param z define the z coordinate of the source vector
  3430. * @param transformation defines the transformation matrix
  3431. * @param result defines the Vector3 where to store the result
  3432. */
  3433. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3434. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3435. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3436. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3437. };
  3438. /**
  3439. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3440. * @param value1 defines the first control point
  3441. * @param value2 defines the second control point
  3442. * @param value3 defines the third control point
  3443. * @param value4 defines the fourth control point
  3444. * @param amount defines the amount on the spline to use
  3445. * @returns the new Vector3
  3446. */
  3447. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3448. var squared = amount * amount;
  3449. var cubed = amount * squared;
  3450. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3451. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3452. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3453. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3454. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3455. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3456. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3457. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3458. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3459. return new Vector3(x, y, z);
  3460. };
  3461. /**
  3462. * 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"
  3463. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3464. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3465. * @param value defines the current value
  3466. * @param min defines the lower range value
  3467. * @param max defines the upper range value
  3468. * @returns the new Vector3
  3469. */
  3470. Vector3.Clamp = function (value, min, max) {
  3471. var x = value.x;
  3472. x = (x > max.x) ? max.x : x;
  3473. x = (x < min.x) ? min.x : x;
  3474. var y = value.y;
  3475. y = (y > max.y) ? max.y : y;
  3476. y = (y < min.y) ? min.y : y;
  3477. var z = value.z;
  3478. z = (z > max.z) ? max.z : z;
  3479. z = (z < min.z) ? min.z : z;
  3480. return new Vector3(x, y, z);
  3481. };
  3482. /**
  3483. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3484. * @param value1 defines the first control point
  3485. * @param tangent1 defines the first tangent vector
  3486. * @param value2 defines the second control point
  3487. * @param tangent2 defines the second tangent vector
  3488. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3489. * @returns the new Vector3
  3490. */
  3491. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3492. var squared = amount * amount;
  3493. var cubed = amount * squared;
  3494. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3495. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3496. var part3 = (cubed - (2.0 * squared)) + amount;
  3497. var part4 = cubed - squared;
  3498. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3499. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3500. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3501. return new Vector3(x, y, z);
  3502. };
  3503. /**
  3504. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @returns the new Vector3
  3509. */
  3510. Vector3.Lerp = function (start, end, amount) {
  3511. var result = new Vector3(0, 0, 0);
  3512. Vector3.LerpToRef(start, end, amount, result);
  3513. return result;
  3514. };
  3515. /**
  3516. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3517. * @param start defines the start value
  3518. * @param end defines the end value
  3519. * @param amount max defines amount between both (between 0 and 1)
  3520. * @param result defines the Vector3 where to store the result
  3521. */
  3522. Vector3.LerpToRef = function (start, end, amount, result) {
  3523. result.x = start.x + ((end.x - start.x) * amount);
  3524. result.y = start.y + ((end.y - start.y) * amount);
  3525. result.z = start.z + ((end.z - start.z) * amount);
  3526. };
  3527. /**
  3528. * Returns the dot product (float) between the vectors "left" and "right"
  3529. * @param left defines the left operand
  3530. * @param right defines the right operand
  3531. * @returns the dot product
  3532. */
  3533. Vector3.Dot = function (left, right) {
  3534. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3535. };
  3536. /**
  3537. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @returns the cross product
  3542. */
  3543. Vector3.Cross = function (left, right) {
  3544. var result = Vector3.Zero();
  3545. Vector3.CrossToRef(left, right, result);
  3546. return result;
  3547. };
  3548. /**
  3549. * Sets the passed vector "result" with the cross product of "left" and "right"
  3550. * The cross product is then orthogonal to both "left" and "right"
  3551. * @param left defines the left operand
  3552. * @param right defines the right operand
  3553. * @param result defines the Vector3 where to store the result
  3554. */
  3555. Vector3.CrossToRef = function (left, right, result) {
  3556. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3557. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3558. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3559. result.copyFrom(MathTmp.Vector3[0]);
  3560. };
  3561. /**
  3562. * Returns a new Vector3 as the normalization of the passed vector
  3563. * @param vector defines the Vector3 to normalize
  3564. * @returns the new Vector3
  3565. */
  3566. Vector3.Normalize = function (vector) {
  3567. var result = Vector3.Zero();
  3568. Vector3.NormalizeToRef(vector, result);
  3569. return result;
  3570. };
  3571. /**
  3572. * Sets the passed vector "result" with the normalization of the passed first vector
  3573. * @param vector defines the Vector3 to normalize
  3574. * @param result defines the Vector3 where to store the result
  3575. */
  3576. Vector3.NormalizeToRef = function (vector, result) {
  3577. result.copyFrom(vector);
  3578. result.normalize();
  3579. };
  3580. /**
  3581. * Project a Vector3 onto screen space
  3582. * @param vector defines the Vector3 to project
  3583. * @param world defines the world matrix to use
  3584. * @param transform defines the transform (view x projection) matrix to use
  3585. * @param viewport defines the screen viewport to use
  3586. * @returns the new Vector3
  3587. */
  3588. Vector3.Project = function (vector, world, transform, viewport) {
  3589. var cw = viewport.width;
  3590. var ch = viewport.height;
  3591. var cx = viewport.x;
  3592. var cy = viewport.y;
  3593. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3594. 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);
  3595. var matrix = MathTmp.Matrix[0];
  3596. world.multiplyToRef(transform, matrix);
  3597. matrix.multiplyToRef(viewportMatrix, matrix);
  3598. return Vector3.TransformCoordinates(vector, matrix);
  3599. };
  3600. /**
  3601. * Unproject from screen space to object space
  3602. * @param source defines the screen space Vector3 to use
  3603. * @param viewportWidth defines the current width of the viewport
  3604. * @param viewportHeight defines the current height of the viewport
  3605. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3606. * @param transform defines the transform (view x projection) matrix to use
  3607. * @returns the new Vector3
  3608. */
  3609. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3610. var matrix = MathTmp.Matrix[0];
  3611. world.multiplyToRef(transform, matrix);
  3612. matrix.invert();
  3613. source.x = source.x / viewportWidth * 2 - 1;
  3614. source.y = -(source.y / viewportHeight * 2 - 1);
  3615. var vector = Vector3.TransformCoordinates(source, matrix);
  3616. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3617. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3618. vector = vector.scale(1.0 / num);
  3619. }
  3620. return vector;
  3621. };
  3622. /**
  3623. * Unproject from screen space to object space
  3624. * @param source defines the screen space Vector3 to use
  3625. * @param viewportWidth defines the current width of the viewport
  3626. * @param viewportHeight defines the current height of the viewport
  3627. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3628. * @param view defines the view matrix to use
  3629. * @param projection defines the projection matrix to use
  3630. * @returns the new Vector3
  3631. */
  3632. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3633. var result = Vector3.Zero();
  3634. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3635. return result;
  3636. };
  3637. /**
  3638. * Unproject from screen space to object space
  3639. * @param source defines the screen space Vector3 to use
  3640. * @param viewportWidth defines the current width of the viewport
  3641. * @param viewportHeight defines the current height of the viewport
  3642. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3643. * @param view defines the view matrix to use
  3644. * @param projection defines the projection matrix to use
  3645. * @param result defines the Vector3 where to store the result
  3646. */
  3647. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3648. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3649. };
  3650. /**
  3651. * Unproject from screen space to object space
  3652. * @param sourceX defines the screen space x coordinate to use
  3653. * @param sourceY defines the screen space y coordinate to use
  3654. * @param sourceZ defines the screen space z coordinate to use
  3655. * @param viewportWidth defines the current width of the viewport
  3656. * @param viewportHeight defines the current height of the viewport
  3657. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3658. * @param view defines the view matrix to use
  3659. * @param projection defines the projection matrix to use
  3660. * @param result defines the Vector3 where to store the result
  3661. */
  3662. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3663. var matrix = MathTmp.Matrix[0];
  3664. world.multiplyToRef(view, matrix);
  3665. matrix.multiplyToRef(projection, matrix);
  3666. matrix.invert();
  3667. var screenSource = MathTmp.Vector3[0];
  3668. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3669. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3670. screenSource.z = 2 * sourceZ - 1.0;
  3671. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3672. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3673. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3674. result.scaleInPlace(1.0 / num);
  3675. }
  3676. };
  3677. /**
  3678. * Gets the minimal coordinate values between two Vector3
  3679. * @param left defines the first operand
  3680. * @param right defines the second operand
  3681. * @returns the new Vector3
  3682. */
  3683. Vector3.Minimize = function (left, right) {
  3684. var min = left.clone();
  3685. min.minimizeInPlace(right);
  3686. return min;
  3687. };
  3688. /**
  3689. * Gets the maximal coordinate values between two Vector3
  3690. * @param left defines the first operand
  3691. * @param right defines the second operand
  3692. * @returns the new Vector3
  3693. */
  3694. Vector3.Maximize = function (left, right) {
  3695. var max = left.clone();
  3696. max.maximizeInPlace(right);
  3697. return max;
  3698. };
  3699. /**
  3700. * Returns the distance between the vectors "value1" and "value2"
  3701. * @param value1 defines the first operand
  3702. * @param value2 defines the second operand
  3703. * @returns the distance
  3704. */
  3705. Vector3.Distance = function (value1, value2) {
  3706. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3707. };
  3708. /**
  3709. * Returns the squared distance between the vectors "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the squared distance
  3713. */
  3714. Vector3.DistanceSquared = function (value1, value2) {
  3715. var x = value1.x - value2.x;
  3716. var y = value1.y - value2.y;
  3717. var z = value1.z - value2.z;
  3718. return (x * x) + (y * y) + (z * z);
  3719. };
  3720. /**
  3721. * Returns a new Vector3 located at the center between "value1" and "value2"
  3722. * @param value1 defines the first operand
  3723. * @param value2 defines the second operand
  3724. * @returns the new Vector3
  3725. */
  3726. Vector3.Center = function (value1, value2) {
  3727. var center = value1.add(value2);
  3728. center.scaleInPlace(0.5);
  3729. return center;
  3730. };
  3731. /**
  3732. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3733. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3734. * to something in order to rotate it from its local system to the given target system
  3735. * Note: axis1, axis2 and axis3 are normalized during this operation
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @returns a new Vector3
  3740. */
  3741. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3742. var rotation = Vector3.Zero();
  3743. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3744. return rotation;
  3745. };
  3746. /**
  3747. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3748. * @param axis1 defines the first axis
  3749. * @param axis2 defines the second axis
  3750. * @param axis3 defines the third axis
  3751. * @param ref defines the Vector3 where to store the result
  3752. */
  3753. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3754. var quat = MathTmp.Quaternion[0];
  3755. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3756. quat.toEulerAnglesToRef(ref);
  3757. };
  3758. return Vector3;
  3759. }());
  3760. BABYLON.Vector3 = Vector3;
  3761. //Vector4 class created for EulerAngle class conversion to Quaternion
  3762. var Vector4 = /** @class */ (function () {
  3763. /**
  3764. * Creates a Vector4 object from the passed floats.
  3765. */
  3766. function Vector4(x, y, z, w) {
  3767. this.x = x;
  3768. this.y = y;
  3769. this.z = z;
  3770. this.w = w;
  3771. }
  3772. /**
  3773. * Returns the string with the Vector4 coordinates.
  3774. */
  3775. Vector4.prototype.toString = function () {
  3776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3777. };
  3778. /**
  3779. * Returns the string "Vector4".
  3780. */
  3781. Vector4.prototype.getClassName = function () {
  3782. return "Vector4";
  3783. };
  3784. /**
  3785. * Returns the Vector4 hash code.
  3786. */
  3787. Vector4.prototype.getHashCode = function () {
  3788. var hash = this.x || 0;
  3789. hash = (hash * 397) ^ (this.y || 0);
  3790. hash = (hash * 397) ^ (this.z || 0);
  3791. hash = (hash * 397) ^ (this.w || 0);
  3792. return hash;
  3793. };
  3794. // Operators
  3795. /**
  3796. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3797. */
  3798. Vector4.prototype.asArray = function () {
  3799. var result = new Array();
  3800. this.toArray(result, 0);
  3801. return result;
  3802. };
  3803. /**
  3804. * Populates the passed array from the passed index with the Vector4 coordinates.
  3805. * Returns the Vector4.
  3806. */
  3807. Vector4.prototype.toArray = function (array, index) {
  3808. if (index === undefined) {
  3809. index = 0;
  3810. }
  3811. array[index] = this.x;
  3812. array[index + 1] = this.y;
  3813. array[index + 2] = this.z;
  3814. array[index + 3] = this.w;
  3815. return this;
  3816. };
  3817. /**
  3818. * Adds the passed vector to the current Vector4.
  3819. * Returns the updated Vector4.
  3820. */
  3821. Vector4.prototype.addInPlace = function (otherVector) {
  3822. this.x += otherVector.x;
  3823. this.y += otherVector.y;
  3824. this.z += otherVector.z;
  3825. this.w += otherVector.w;
  3826. return this;
  3827. };
  3828. /**
  3829. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3830. */
  3831. Vector4.prototype.add = function (otherVector) {
  3832. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3833. };
  3834. /**
  3835. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3836. * Returns the current Vector4.
  3837. */
  3838. Vector4.prototype.addToRef = function (otherVector, result) {
  3839. result.x = this.x + otherVector.x;
  3840. result.y = this.y + otherVector.y;
  3841. result.z = this.z + otherVector.z;
  3842. result.w = this.w + otherVector.w;
  3843. return this;
  3844. };
  3845. /**
  3846. * Subtract in place the passed vector from the current Vector4.
  3847. * Returns the updated Vector4.
  3848. */
  3849. Vector4.prototype.subtractInPlace = function (otherVector) {
  3850. this.x -= otherVector.x;
  3851. this.y -= otherVector.y;
  3852. this.z -= otherVector.z;
  3853. this.w -= otherVector.w;
  3854. return this;
  3855. };
  3856. /**
  3857. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3858. */
  3859. Vector4.prototype.subtract = function (otherVector) {
  3860. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3861. };
  3862. /**
  3863. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3864. * Returns the current Vector4.
  3865. */
  3866. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3867. result.x = this.x - otherVector.x;
  3868. result.y = this.y - otherVector.y;
  3869. result.z = this.z - otherVector.z;
  3870. result.w = this.w - otherVector.w;
  3871. return this;
  3872. };
  3873. /**
  3874. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3875. */
  3876. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3877. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3878. };
  3879. /**
  3880. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3881. * Returns the current Vector4.
  3882. */
  3883. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3884. result.x = this.x - x;
  3885. result.y = this.y - y;
  3886. result.z = this.z - z;
  3887. result.w = this.w - w;
  3888. return this;
  3889. };
  3890. /**
  3891. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3892. */
  3893. Vector4.prototype.negate = function () {
  3894. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3895. };
  3896. /**
  3897. * Multiplies the current Vector4 coordinates by scale (float).
  3898. * Returns the updated Vector4.
  3899. */
  3900. Vector4.prototype.scaleInPlace = function (scale) {
  3901. this.x *= scale;
  3902. this.y *= scale;
  3903. this.z *= scale;
  3904. this.w *= scale;
  3905. return this;
  3906. };
  3907. /**
  3908. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3909. */
  3910. Vector4.prototype.scale = function (scale) {
  3911. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3912. };
  3913. /**
  3914. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3915. * Returns the current Vector4.
  3916. */
  3917. Vector4.prototype.scaleToRef = function (scale, result) {
  3918. result.x = this.x * scale;
  3919. result.y = this.y * scale;
  3920. result.z = this.z * scale;
  3921. result.w = this.w * scale;
  3922. return this;
  3923. };
  3924. /**
  3925. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3926. * @param scale defines the scale factor
  3927. * @param result defines the Vector4 object where to store the result
  3928. * @returns the unmodified current Vector4
  3929. */
  3930. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3931. result.x += this.x * scale;
  3932. result.y += this.y * scale;
  3933. result.z += this.z * scale;
  3934. result.w += this.w * scale;
  3935. return this;
  3936. };
  3937. /**
  3938. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3939. */
  3940. Vector4.prototype.equals = function (otherVector) {
  3941. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3942. };
  3943. /**
  3944. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3945. */
  3946. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3947. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3948. return otherVector
  3949. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3950. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3951. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3952. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3953. };
  3954. /**
  3955. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3956. */
  3957. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3958. return this.x === x && this.y === y && this.z === z && this.w === w;
  3959. };
  3960. /**
  3961. * Multiplies in place the current Vector4 by the passed one.
  3962. * Returns the updated Vector4.
  3963. */
  3964. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3965. this.x *= otherVector.x;
  3966. this.y *= otherVector.y;
  3967. this.z *= otherVector.z;
  3968. this.w *= otherVector.w;
  3969. return this;
  3970. };
  3971. /**
  3972. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3973. */
  3974. Vector4.prototype.multiply = function (otherVector) {
  3975. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3976. };
  3977. /**
  3978. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3979. * Returns the current Vector4.
  3980. */
  3981. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3982. result.x = this.x * otherVector.x;
  3983. result.y = this.y * otherVector.y;
  3984. result.z = this.z * otherVector.z;
  3985. result.w = this.w * otherVector.w;
  3986. return this;
  3987. };
  3988. /**
  3989. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3990. */
  3991. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3992. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3993. };
  3994. /**
  3995. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3996. */
  3997. Vector4.prototype.divide = function (otherVector) {
  3998. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3999. };
  4000. /**
  4001. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  4002. * Returns the current Vector4.
  4003. */
  4004. Vector4.prototype.divideToRef = function (otherVector, result) {
  4005. result.x = this.x / otherVector.x;
  4006. result.y = this.y / otherVector.y;
  4007. result.z = this.z / otherVector.z;
  4008. result.w = this.w / otherVector.w;
  4009. return this;
  4010. };
  4011. /**
  4012. * Divides the current Vector3 coordinates by the passed ones.
  4013. * @returns the updated Vector3.
  4014. */
  4015. Vector4.prototype.divideInPlace = function (otherVector) {
  4016. return this.divideToRef(otherVector, this);
  4017. };
  4018. /**
  4019. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  4020. * @param other defines the second operand
  4021. * @returns the current updated Vector4
  4022. */
  4023. Vector4.prototype.minimizeInPlace = function (other) {
  4024. if (other.x < this.x)
  4025. this.x = other.x;
  4026. if (other.y < this.y)
  4027. this.y = other.y;
  4028. if (other.z < this.z)
  4029. this.z = other.z;
  4030. if (other.w < this.w)
  4031. this.w = other.w;
  4032. return this;
  4033. };
  4034. /**
  4035. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  4036. * @param other defines the second operand
  4037. * @returns the current updated Vector4
  4038. */
  4039. Vector4.prototype.maximizeInPlace = function (other) {
  4040. if (other.x > this.x)
  4041. this.x = other.x;
  4042. if (other.y > this.y)
  4043. this.y = other.y;
  4044. if (other.z > this.z)
  4045. this.z = other.z;
  4046. if (other.w > this.w)
  4047. this.w = other.w;
  4048. return this;
  4049. };
  4050. // Properties
  4051. /**
  4052. * Returns the Vector4 length (float).
  4053. */
  4054. Vector4.prototype.length = function () {
  4055. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4056. };
  4057. /**
  4058. * Returns the Vector4 squared length (float).
  4059. */
  4060. Vector4.prototype.lengthSquared = function () {
  4061. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4062. };
  4063. // Methods
  4064. /**
  4065. * Normalizes in place the Vector4.
  4066. * Returns the updated Vector4.
  4067. */
  4068. Vector4.prototype.normalize = function () {
  4069. var len = this.length();
  4070. if (len === 0)
  4071. return this;
  4072. var num = 1.0 / len;
  4073. this.x *= num;
  4074. this.y *= num;
  4075. this.z *= num;
  4076. this.w *= num;
  4077. return this;
  4078. };
  4079. /**
  4080. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4081. */
  4082. Vector4.prototype.toVector3 = function () {
  4083. return new Vector3(this.x, this.y, this.z);
  4084. };
  4085. /**
  4086. * Returns a new Vector4 copied from the current one.
  4087. */
  4088. Vector4.prototype.clone = function () {
  4089. return new Vector4(this.x, this.y, this.z, this.w);
  4090. };
  4091. /**
  4092. * Updates the current Vector4 with the passed one coordinates.
  4093. * Returns the updated Vector4.
  4094. */
  4095. Vector4.prototype.copyFrom = function (source) {
  4096. this.x = source.x;
  4097. this.y = source.y;
  4098. this.z = source.z;
  4099. this.w = source.w;
  4100. return this;
  4101. };
  4102. /**
  4103. * Updates the current Vector4 coordinates with the passed floats.
  4104. * Returns the updated Vector4.
  4105. */
  4106. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4107. this.x = x;
  4108. this.y = y;
  4109. this.z = z;
  4110. this.w = w;
  4111. return this;
  4112. };
  4113. /**
  4114. * Updates the current Vector4 coordinates with the passed floats.
  4115. * Returns the updated Vector4.
  4116. */
  4117. Vector4.prototype.set = function (x, y, z, w) {
  4118. return this.copyFromFloats(x, y, z, w);
  4119. };
  4120. // Statics
  4121. /**
  4122. * Returns a new Vector4 set from the starting index of the passed array.
  4123. */
  4124. Vector4.FromArray = function (array, offset) {
  4125. if (!offset) {
  4126. offset = 0;
  4127. }
  4128. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4129. };
  4130. /**
  4131. * Updates the passed vector "result" from the starting index of the passed array.
  4132. */
  4133. Vector4.FromArrayToRef = function (array, offset, result) {
  4134. result.x = array[offset];
  4135. result.y = array[offset + 1];
  4136. result.z = array[offset + 2];
  4137. result.w = array[offset + 3];
  4138. };
  4139. /**
  4140. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4141. */
  4142. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4143. Vector4.FromArrayToRef(array, offset, result);
  4144. };
  4145. /**
  4146. * Updates the passed vector "result" coordinates from the passed floats.
  4147. */
  4148. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4149. result.x = x;
  4150. result.y = y;
  4151. result.z = z;
  4152. result.w = w;
  4153. };
  4154. /**
  4155. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4156. */
  4157. Vector4.Zero = function () {
  4158. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4159. };
  4160. /**
  4161. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4162. */
  4163. Vector4.One = function () {
  4164. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4165. };
  4166. /**
  4167. * Returns a new normalized Vector4 from the passed one.
  4168. */
  4169. Vector4.Normalize = function (vector) {
  4170. var result = Vector4.Zero();
  4171. Vector4.NormalizeToRef(vector, result);
  4172. return result;
  4173. };
  4174. /**
  4175. * Updates the passed vector "result" from the normalization of the passed one.
  4176. */
  4177. Vector4.NormalizeToRef = function (vector, result) {
  4178. result.copyFrom(vector);
  4179. result.normalize();
  4180. };
  4181. Vector4.Minimize = function (left, right) {
  4182. var min = left.clone();
  4183. min.minimizeInPlace(right);
  4184. return min;
  4185. };
  4186. Vector4.Maximize = function (left, right) {
  4187. var max = left.clone();
  4188. max.maximizeInPlace(right);
  4189. return max;
  4190. };
  4191. /**
  4192. * Returns the distance (float) between the vectors "value1" and "value2".
  4193. */
  4194. Vector4.Distance = function (value1, value2) {
  4195. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4196. };
  4197. /**
  4198. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4199. */
  4200. Vector4.DistanceSquared = function (value1, value2) {
  4201. var x = value1.x - value2.x;
  4202. var y = value1.y - value2.y;
  4203. var z = value1.z - value2.z;
  4204. var w = value1.w - value2.w;
  4205. return (x * x) + (y * y) + (z * z) + (w * w);
  4206. };
  4207. /**
  4208. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4209. */
  4210. Vector4.Center = function (value1, value2) {
  4211. var center = value1.add(value2);
  4212. center.scaleInPlace(0.5);
  4213. return center;
  4214. };
  4215. /**
  4216. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4217. * This methods computes transformed normalized direction vectors only.
  4218. */
  4219. Vector4.TransformNormal = function (vector, transformation) {
  4220. var result = Vector4.Zero();
  4221. Vector4.TransformNormalToRef(vector, transformation, result);
  4222. return result;
  4223. };
  4224. /**
  4225. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4226. * This methods computes transformed normalized direction vectors only.
  4227. */
  4228. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4229. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4230. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4231. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4232. result.x = x;
  4233. result.y = y;
  4234. result.z = z;
  4235. result.w = vector.w;
  4236. };
  4237. /**
  4238. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4239. * This methods computes transformed normalized direction vectors only.
  4240. */
  4241. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4242. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4243. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4244. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4245. result.w = w;
  4246. };
  4247. return Vector4;
  4248. }());
  4249. BABYLON.Vector4 = Vector4;
  4250. var Size = /** @class */ (function () {
  4251. /**
  4252. * Creates a Size object from the passed width and height (floats).
  4253. */
  4254. function Size(width, height) {
  4255. this.width = width;
  4256. this.height = height;
  4257. }
  4258. // Returns a string with the Size width and height.
  4259. Size.prototype.toString = function () {
  4260. return "{W: " + this.width + ", H: " + this.height + "}";
  4261. };
  4262. /**
  4263. * Returns the string "Size"
  4264. */
  4265. Size.prototype.getClassName = function () {
  4266. return "Size";
  4267. };
  4268. /**
  4269. * Returns the Size hash code.
  4270. */
  4271. Size.prototype.getHashCode = function () {
  4272. var hash = this.width || 0;
  4273. hash = (hash * 397) ^ (this.height || 0);
  4274. return hash;
  4275. };
  4276. /**
  4277. * Updates the current size from the passed one.
  4278. * Returns the updated Size.
  4279. */
  4280. Size.prototype.copyFrom = function (src) {
  4281. this.width = src.width;
  4282. this.height = src.height;
  4283. };
  4284. /**
  4285. * Updates in place the current Size from the passed floats.
  4286. * Returns the updated Size.
  4287. */
  4288. Size.prototype.copyFromFloats = function (width, height) {
  4289. this.width = width;
  4290. this.height = height;
  4291. return this;
  4292. };
  4293. /**
  4294. * Updates in place the current Size from the passed floats.
  4295. * Returns the updated Size.
  4296. */
  4297. Size.prototype.set = function (width, height) {
  4298. return this.copyFromFloats(width, height);
  4299. };
  4300. /**
  4301. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4302. */
  4303. Size.prototype.multiplyByFloats = function (w, h) {
  4304. return new Size(this.width * w, this.height * h);
  4305. };
  4306. /**
  4307. * Returns a new Size copied from the passed one.
  4308. */
  4309. Size.prototype.clone = function () {
  4310. return new Size(this.width, this.height);
  4311. };
  4312. /**
  4313. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4314. */
  4315. Size.prototype.equals = function (other) {
  4316. if (!other) {
  4317. return false;
  4318. }
  4319. return (this.width === other.width) && (this.height === other.height);
  4320. };
  4321. Object.defineProperty(Size.prototype, "surface", {
  4322. /**
  4323. * Returns the surface of the Size : width * height (float).
  4324. */
  4325. get: function () {
  4326. return this.width * this.height;
  4327. },
  4328. enumerable: true,
  4329. configurable: true
  4330. });
  4331. /**
  4332. * Returns a new Size set to (0.0, 0.0)
  4333. */
  4334. Size.Zero = function () {
  4335. return new Size(0.0, 0.0);
  4336. };
  4337. /**
  4338. * Returns a new Size set as the addition result of the current Size and the passed one.
  4339. */
  4340. Size.prototype.add = function (otherSize) {
  4341. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4342. return r;
  4343. };
  4344. /**
  4345. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4346. */
  4347. Size.prototype.subtract = function (otherSize) {
  4348. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4349. return r;
  4350. };
  4351. /**
  4352. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4353. */
  4354. Size.Lerp = function (start, end, amount) {
  4355. var w = start.width + ((end.width - start.width) * amount);
  4356. var h = start.height + ((end.height - start.height) * amount);
  4357. return new Size(w, h);
  4358. };
  4359. return Size;
  4360. }());
  4361. BABYLON.Size = Size;
  4362. var Quaternion = /** @class */ (function () {
  4363. /**
  4364. * Creates a new Quaternion from the passed floats.
  4365. */
  4366. function Quaternion(x, y, z, w) {
  4367. if (x === void 0) { x = 0.0; }
  4368. if (y === void 0) { y = 0.0; }
  4369. if (z === void 0) { z = 0.0; }
  4370. if (w === void 0) { w = 1.0; }
  4371. this.x = x;
  4372. this.y = y;
  4373. this.z = z;
  4374. this.w = w;
  4375. }
  4376. /**
  4377. * Returns a string with the Quaternion coordinates.
  4378. */
  4379. Quaternion.prototype.toString = function () {
  4380. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4381. };
  4382. /**
  4383. * Returns the string "Quaternion".
  4384. */
  4385. Quaternion.prototype.getClassName = function () {
  4386. return "Quaternion";
  4387. };
  4388. /**
  4389. * Returns the Quaternion hash code.
  4390. */
  4391. Quaternion.prototype.getHashCode = function () {
  4392. var hash = this.x || 0;
  4393. hash = (hash * 397) ^ (this.y || 0);
  4394. hash = (hash * 397) ^ (this.z || 0);
  4395. hash = (hash * 397) ^ (this.w || 0);
  4396. return hash;
  4397. };
  4398. /**
  4399. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4400. */
  4401. Quaternion.prototype.asArray = function () {
  4402. return [this.x, this.y, this.z, this.w];
  4403. };
  4404. /**
  4405. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4406. */
  4407. Quaternion.prototype.equals = function (otherQuaternion) {
  4408. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4409. };
  4410. /**
  4411. * Returns a new Quaternion copied from the current one.
  4412. */
  4413. Quaternion.prototype.clone = function () {
  4414. return new Quaternion(this.x, this.y, this.z, this.w);
  4415. };
  4416. /**
  4417. * Updates the current Quaternion from the passed one coordinates.
  4418. * Returns the updated Quaterion.
  4419. */
  4420. Quaternion.prototype.copyFrom = function (other) {
  4421. this.x = other.x;
  4422. this.y = other.y;
  4423. this.z = other.z;
  4424. this.w = other.w;
  4425. return this;
  4426. };
  4427. /**
  4428. * Updates the current Quaternion from the passed float coordinates.
  4429. * Returns the updated Quaterion.
  4430. */
  4431. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4432. this.x = x;
  4433. this.y = y;
  4434. this.z = z;
  4435. this.w = w;
  4436. return this;
  4437. };
  4438. /**
  4439. * Updates the current Quaternion from the passed float coordinates.
  4440. * Returns the updated Quaterion.
  4441. */
  4442. Quaternion.prototype.set = function (x, y, z, w) {
  4443. return this.copyFromFloats(x, y, z, w);
  4444. };
  4445. /**
  4446. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4447. */
  4448. Quaternion.prototype.add = function (other) {
  4449. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4450. };
  4451. /**
  4452. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4453. */
  4454. Quaternion.prototype.subtract = function (other) {
  4455. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4456. };
  4457. /**
  4458. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4459. */
  4460. Quaternion.prototype.scale = function (value) {
  4461. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4462. };
  4463. /**
  4464. * Scale the current Quaternion values by a factor to a given Quaternion
  4465. * @param scale defines the scale factor
  4466. * @param result defines the Quaternion object where to store the result
  4467. * @returns the unmodified current Quaternion
  4468. */
  4469. Quaternion.prototype.scaleToRef = function (scale, result) {
  4470. result.x = this.x * scale;
  4471. result.y = this.y * scale;
  4472. result.z = this.z * scale;
  4473. result.w = this.w * scale;
  4474. return this;
  4475. };
  4476. /**
  4477. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4478. * @param scale defines the scale factor
  4479. * @param result defines the Quaternion object where to store the result
  4480. * @returns the unmodified current Quaternion
  4481. */
  4482. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4483. result.x += this.x * scale;
  4484. result.y += this.y * scale;
  4485. result.z += this.z * scale;
  4486. result.w += this.w * scale;
  4487. return this;
  4488. };
  4489. /**
  4490. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4491. */
  4492. Quaternion.prototype.multiply = function (q1) {
  4493. var result = new Quaternion(0, 0, 0, 1.0);
  4494. this.multiplyToRef(q1, result);
  4495. return result;
  4496. };
  4497. /**
  4498. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4499. * Returns the current Quaternion.
  4500. */
  4501. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4502. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4503. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4504. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4505. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4506. result.copyFromFloats(x, y, z, w);
  4507. return this;
  4508. };
  4509. /**
  4510. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4511. * Returns the updated Quaternion.
  4512. */
  4513. Quaternion.prototype.multiplyInPlace = function (q1) {
  4514. this.multiplyToRef(q1, this);
  4515. return this;
  4516. };
  4517. /**
  4518. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4519. * Returns the current Quaternion.
  4520. */
  4521. Quaternion.prototype.conjugateToRef = function (ref) {
  4522. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4523. return this;
  4524. };
  4525. /**
  4526. * Conjugates in place the current Quaternion.
  4527. * Returns the updated Quaternion.
  4528. */
  4529. Quaternion.prototype.conjugateInPlace = function () {
  4530. this.x *= -1;
  4531. this.y *= -1;
  4532. this.z *= -1;
  4533. return this;
  4534. };
  4535. /**
  4536. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4537. */
  4538. Quaternion.prototype.conjugate = function () {
  4539. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4540. return result;
  4541. };
  4542. /**
  4543. * Returns the Quaternion length (float).
  4544. */
  4545. Quaternion.prototype.length = function () {
  4546. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4547. };
  4548. /**
  4549. * Normalize in place the current Quaternion.
  4550. * Returns the updated Quaternion.
  4551. */
  4552. Quaternion.prototype.normalize = function () {
  4553. var length = 1.0 / this.length();
  4554. this.x *= length;
  4555. this.y *= length;
  4556. this.z *= length;
  4557. this.w *= length;
  4558. return this;
  4559. };
  4560. /**
  4561. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4562. * @param order is a reserved parameter and is ignore for now
  4563. * @returns the new Vector3
  4564. */
  4565. Quaternion.prototype.toEulerAngles = function (order) {
  4566. if (order === void 0) { order = "YZX"; }
  4567. var result = Vector3.Zero();
  4568. this.toEulerAnglesToRef(result, order);
  4569. return result;
  4570. };
  4571. /**
  4572. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4573. * @param result defines the vector which will be filled with the Euler angles
  4574. * @param order is a reserved parameter and is ignore for now
  4575. * @returns the current Quaternion
  4576. */
  4577. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4578. if (order === void 0) { order = "YZX"; }
  4579. var qz = this.z;
  4580. var qx = this.x;
  4581. var qy = this.y;
  4582. var qw = this.w;
  4583. var sqw = qw * qw;
  4584. var sqz = qz * qz;
  4585. var sqx = qx * qx;
  4586. var sqy = qy * qy;
  4587. var zAxisY = qy * qz - qx * qw;
  4588. var limit = .4999999;
  4589. if (zAxisY < -limit) {
  4590. result.y = 2 * Math.atan2(qy, qw);
  4591. result.x = Math.PI / 2;
  4592. result.z = 0;
  4593. }
  4594. else if (zAxisY > limit) {
  4595. result.y = 2 * Math.atan2(qy, qw);
  4596. result.x = -Math.PI / 2;
  4597. result.z = 0;
  4598. }
  4599. else {
  4600. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4601. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4602. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4603. }
  4604. return this;
  4605. };
  4606. /**
  4607. * Updates the passed rotation matrix with the current Quaternion values.
  4608. * Returns the current Quaternion.
  4609. */
  4610. Quaternion.prototype.toRotationMatrix = function (result) {
  4611. var xx = this.x * this.x;
  4612. var yy = this.y * this.y;
  4613. var zz = this.z * this.z;
  4614. var xy = this.x * this.y;
  4615. var zw = this.z * this.w;
  4616. var zx = this.z * this.x;
  4617. var yw = this.y * this.w;
  4618. var yz = this.y * this.z;
  4619. var xw = this.x * this.w;
  4620. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4621. result.m[1] = 2.0 * (xy + zw);
  4622. result.m[2] = 2.0 * (zx - yw);
  4623. result.m[3] = 0;
  4624. result.m[4] = 2.0 * (xy - zw);
  4625. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4626. result.m[6] = 2.0 * (yz + xw);
  4627. result.m[7] = 0;
  4628. result.m[8] = 2.0 * (zx + yw);
  4629. result.m[9] = 2.0 * (yz - xw);
  4630. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4631. result.m[11] = 0;
  4632. result.m[12] = 0;
  4633. result.m[13] = 0;
  4634. result.m[14] = 0;
  4635. result.m[15] = 1.0;
  4636. result._markAsUpdated();
  4637. return this;
  4638. };
  4639. /**
  4640. * Updates the current Quaternion from the passed rotation matrix values.
  4641. * Returns the updated Quaternion.
  4642. */
  4643. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4644. Quaternion.FromRotationMatrixToRef(matrix, this);
  4645. return this;
  4646. };
  4647. // Statics
  4648. /**
  4649. * Returns a new Quaternion set from the passed rotation matrix values.
  4650. */
  4651. Quaternion.FromRotationMatrix = function (matrix) {
  4652. var result = new Quaternion();
  4653. Quaternion.FromRotationMatrixToRef(matrix, result);
  4654. return result;
  4655. };
  4656. /**
  4657. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4658. */
  4659. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4660. var data = matrix.m;
  4661. var m11 = data[0], m12 = data[4], m13 = data[8];
  4662. var m21 = data[1], m22 = data[5], m23 = data[9];
  4663. var m31 = data[2], m32 = data[6], m33 = data[10];
  4664. var trace = m11 + m22 + m33;
  4665. var s;
  4666. if (trace > 0) {
  4667. s = 0.5 / Math.sqrt(trace + 1.0);
  4668. result.w = 0.25 / s;
  4669. result.x = (m32 - m23) * s;
  4670. result.y = (m13 - m31) * s;
  4671. result.z = (m21 - m12) * s;
  4672. }
  4673. else if (m11 > m22 && m11 > m33) {
  4674. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4675. result.w = (m32 - m23) / s;
  4676. result.x = 0.25 * s;
  4677. result.y = (m12 + m21) / s;
  4678. result.z = (m13 + m31) / s;
  4679. }
  4680. else if (m22 > m33) {
  4681. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4682. result.w = (m13 - m31) / s;
  4683. result.x = (m12 + m21) / s;
  4684. result.y = 0.25 * s;
  4685. result.z = (m23 + m32) / s;
  4686. }
  4687. else {
  4688. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4689. result.w = (m21 - m12) / s;
  4690. result.x = (m13 + m31) / s;
  4691. result.y = (m23 + m32) / s;
  4692. result.z = 0.25 * s;
  4693. }
  4694. };
  4695. /**
  4696. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4697. */
  4698. Quaternion.Zero = function () {
  4699. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4700. };
  4701. /**
  4702. * Returns a new Quaternion as the inverted current Quaternion.
  4703. */
  4704. Quaternion.Inverse = function (q) {
  4705. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4706. };
  4707. /**
  4708. * Returns the identity Quaternion.
  4709. */
  4710. Quaternion.Identity = function () {
  4711. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4712. };
  4713. Quaternion.IsIdentity = function (quaternion) {
  4714. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4715. };
  4716. /**
  4717. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4718. */
  4719. Quaternion.RotationAxis = function (axis, angle) {
  4720. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4721. };
  4722. /**
  4723. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4724. */
  4725. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4726. var sin = Math.sin(angle / 2);
  4727. axis.normalize();
  4728. result.w = Math.cos(angle / 2);
  4729. result.x = axis.x * sin;
  4730. result.y = axis.y * sin;
  4731. result.z = axis.z * sin;
  4732. return result;
  4733. };
  4734. /**
  4735. * Retuns a new Quaternion set from the starting index of the passed array.
  4736. */
  4737. Quaternion.FromArray = function (array, offset) {
  4738. if (!offset) {
  4739. offset = 0;
  4740. }
  4741. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4742. };
  4743. /**
  4744. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4745. */
  4746. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4747. var q = new Quaternion();
  4748. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4749. return q;
  4750. };
  4751. /**
  4752. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4753. */
  4754. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4755. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4756. var halfRoll = roll * 0.5;
  4757. var halfPitch = pitch * 0.5;
  4758. var halfYaw = yaw * 0.5;
  4759. var sinRoll = Math.sin(halfRoll);
  4760. var cosRoll = Math.cos(halfRoll);
  4761. var sinPitch = Math.sin(halfPitch);
  4762. var cosPitch = Math.cos(halfPitch);
  4763. var sinYaw = Math.sin(halfYaw);
  4764. var cosYaw = Math.cos(halfYaw);
  4765. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4766. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4767. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4768. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4769. };
  4770. /**
  4771. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4772. */
  4773. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4774. var result = new Quaternion();
  4775. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4776. return result;
  4777. };
  4778. /**
  4779. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4780. */
  4781. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4782. // Produces a quaternion from Euler angles in the z-x-z orientation
  4783. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4784. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4785. var halfBeta = beta * 0.5;
  4786. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4787. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4788. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4789. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4790. };
  4791. /**
  4792. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4793. * cf to Vector3.RotationFromAxis() documentation.
  4794. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4795. */
  4796. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4797. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4798. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4799. return quat;
  4800. };
  4801. /**
  4802. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4803. * cf to Vector3.RotationFromAxis() documentation.
  4804. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4805. */
  4806. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4807. var rotMat = MathTmp.Matrix[0];
  4808. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4809. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4810. };
  4811. Quaternion.Slerp = function (left, right, amount) {
  4812. var result = Quaternion.Identity();
  4813. Quaternion.SlerpToRef(left, right, amount, result);
  4814. return result;
  4815. };
  4816. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4817. var num2;
  4818. var num3;
  4819. var num = amount;
  4820. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4821. var flag = false;
  4822. if (num4 < 0) {
  4823. flag = true;
  4824. num4 = -num4;
  4825. }
  4826. if (num4 > 0.999999) {
  4827. num3 = 1 - num;
  4828. num2 = flag ? -num : num;
  4829. }
  4830. else {
  4831. var num5 = Math.acos(num4);
  4832. var num6 = (1.0 / Math.sin(num5));
  4833. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4834. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4835. }
  4836. result.x = (num3 * left.x) + (num2 * right.x);
  4837. result.y = (num3 * left.y) + (num2 * right.y);
  4838. result.z = (num3 * left.z) + (num2 * right.z);
  4839. result.w = (num3 * left.w) + (num2 * right.w);
  4840. };
  4841. /**
  4842. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4843. */
  4844. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4845. var squared = amount * amount;
  4846. var cubed = amount * squared;
  4847. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4848. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4849. var part3 = (cubed - (2.0 * squared)) + amount;
  4850. var part4 = cubed - squared;
  4851. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4852. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4853. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4854. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4855. return new Quaternion(x, y, z, w);
  4856. };
  4857. return Quaternion;
  4858. }());
  4859. BABYLON.Quaternion = Quaternion;
  4860. var Matrix = /** @class */ (function () {
  4861. function Matrix() {
  4862. this._isIdentity = false;
  4863. this._isIdentityDirty = true;
  4864. this.m = new Float32Array(16);
  4865. this._markAsUpdated();
  4866. }
  4867. Matrix.prototype._markAsUpdated = function () {
  4868. this.updateFlag = Matrix._updateFlagSeed++;
  4869. this._isIdentityDirty = true;
  4870. };
  4871. // Properties
  4872. /**
  4873. * Boolean : True is the matrix is the identity matrix
  4874. */
  4875. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4876. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4877. if (this._isIdentityDirty) {
  4878. this._isIdentityDirty = false;
  4879. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4880. this._isIdentity = false;
  4881. }
  4882. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4883. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4884. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4885. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4886. this._isIdentity = false;
  4887. }
  4888. else {
  4889. this._isIdentity = true;
  4890. }
  4891. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4892. this._isIdentity = false;
  4893. }
  4894. }
  4895. return this._isIdentity;
  4896. };
  4897. /**
  4898. * Returns the matrix determinant (float).
  4899. */
  4900. Matrix.prototype.determinant = function () {
  4901. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4902. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4903. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4904. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4905. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4906. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4907. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4908. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4909. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4910. };
  4911. // Methods
  4912. /**
  4913. * Returns the matrix underlying array.
  4914. */
  4915. Matrix.prototype.toArray = function () {
  4916. return this.m;
  4917. };
  4918. /**
  4919. * Returns the matrix underlying array.
  4920. */
  4921. Matrix.prototype.asArray = function () {
  4922. return this.toArray();
  4923. };
  4924. /**
  4925. * Inverts in place the Matrix.
  4926. * Returns the Matrix inverted.
  4927. */
  4928. Matrix.prototype.invert = function () {
  4929. this.invertToRef(this);
  4930. return this;
  4931. };
  4932. /**
  4933. * Sets all the matrix elements to zero.
  4934. * Returns the Matrix.
  4935. */
  4936. Matrix.prototype.reset = function () {
  4937. for (var index = 0; index < 16; index++) {
  4938. this.m[index] = 0.0;
  4939. }
  4940. this._markAsUpdated();
  4941. return this;
  4942. };
  4943. /**
  4944. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4945. */
  4946. Matrix.prototype.add = function (other) {
  4947. var result = new Matrix();
  4948. this.addToRef(other, result);
  4949. return result;
  4950. };
  4951. /**
  4952. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4953. * Returns the Matrix.
  4954. */
  4955. Matrix.prototype.addToRef = function (other, result) {
  4956. for (var index = 0; index < 16; index++) {
  4957. result.m[index] = this.m[index] + other.m[index];
  4958. }
  4959. result._markAsUpdated();
  4960. return this;
  4961. };
  4962. /**
  4963. * Adds in place the passed matrix to the current Matrix.
  4964. * Returns the updated Matrix.
  4965. */
  4966. Matrix.prototype.addToSelf = function (other) {
  4967. for (var index = 0; index < 16; index++) {
  4968. this.m[index] += other.m[index];
  4969. }
  4970. this._markAsUpdated();
  4971. return this;
  4972. };
  4973. /**
  4974. * Sets the passed matrix with the current inverted Matrix.
  4975. * Returns the unmodified current Matrix.
  4976. */
  4977. Matrix.prototype.invertToRef = function (other) {
  4978. var l1 = this.m[0];
  4979. var l2 = this.m[1];
  4980. var l3 = this.m[2];
  4981. var l4 = this.m[3];
  4982. var l5 = this.m[4];
  4983. var l6 = this.m[5];
  4984. var l7 = this.m[6];
  4985. var l8 = this.m[7];
  4986. var l9 = this.m[8];
  4987. var l10 = this.m[9];
  4988. var l11 = this.m[10];
  4989. var l12 = this.m[11];
  4990. var l13 = this.m[12];
  4991. var l14 = this.m[13];
  4992. var l15 = this.m[14];
  4993. var l16 = this.m[15];
  4994. var l17 = (l11 * l16) - (l12 * l15);
  4995. var l18 = (l10 * l16) - (l12 * l14);
  4996. var l19 = (l10 * l15) - (l11 * l14);
  4997. var l20 = (l9 * l16) - (l12 * l13);
  4998. var l21 = (l9 * l15) - (l11 * l13);
  4999. var l22 = (l9 * l14) - (l10 * l13);
  5000. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5001. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5002. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5003. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5004. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5005. var l28 = (l7 * l16) - (l8 * l15);
  5006. var l29 = (l6 * l16) - (l8 * l14);
  5007. var l30 = (l6 * l15) - (l7 * l14);
  5008. var l31 = (l5 * l16) - (l8 * l13);
  5009. var l32 = (l5 * l15) - (l7 * l13);
  5010. var l33 = (l5 * l14) - (l6 * l13);
  5011. var l34 = (l7 * l12) - (l8 * l11);
  5012. var l35 = (l6 * l12) - (l8 * l10);
  5013. var l36 = (l6 * l11) - (l7 * l10);
  5014. var l37 = (l5 * l12) - (l8 * l9);
  5015. var l38 = (l5 * l11) - (l7 * l9);
  5016. var l39 = (l5 * l10) - (l6 * l9);
  5017. other.m[0] = l23 * l27;
  5018. other.m[4] = l24 * l27;
  5019. other.m[8] = l25 * l27;
  5020. other.m[12] = l26 * l27;
  5021. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5022. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5023. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5024. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5025. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5026. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5027. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5028. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5029. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5030. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5031. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5032. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5033. other._markAsUpdated();
  5034. return this;
  5035. };
  5036. /**
  5037. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  5038. * Returns the updated Matrix.
  5039. */
  5040. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5041. this.m[12] = x;
  5042. this.m[13] = y;
  5043. this.m[14] = z;
  5044. this._markAsUpdated();
  5045. return this;
  5046. };
  5047. /**
  5048. * Inserts the translation vector in the current Matrix.
  5049. * Returns the updated Matrix.
  5050. */
  5051. Matrix.prototype.setTranslation = function (vector3) {
  5052. this.m[12] = vector3.x;
  5053. this.m[13] = vector3.y;
  5054. this.m[14] = vector3.z;
  5055. this._markAsUpdated();
  5056. return this;
  5057. };
  5058. /**
  5059. * Returns a new Vector3 as the extracted translation from the Matrix.
  5060. */
  5061. Matrix.prototype.getTranslation = function () {
  5062. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5063. };
  5064. /**
  5065. * Fill a Vector3 with the extracted translation from the Matrix.
  5066. */
  5067. Matrix.prototype.getTranslationToRef = function (result) {
  5068. result.x = this.m[12];
  5069. result.y = this.m[13];
  5070. result.z = this.m[14];
  5071. return this;
  5072. };
  5073. /**
  5074. * Remove rotation and scaling part from the Matrix.
  5075. * Returns the updated Matrix.
  5076. */
  5077. Matrix.prototype.removeRotationAndScaling = function () {
  5078. this.setRowFromFloats(0, 1, 0, 0, 0);
  5079. this.setRowFromFloats(1, 0, 1, 0, 0);
  5080. this.setRowFromFloats(2, 0, 0, 1, 0);
  5081. return this;
  5082. };
  5083. /**
  5084. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  5085. */
  5086. Matrix.prototype.multiply = function (other) {
  5087. var result = new Matrix();
  5088. this.multiplyToRef(other, result);
  5089. return result;
  5090. };
  5091. /**
  5092. * Updates the current Matrix from the passed one values.
  5093. * Returns the updated Matrix.
  5094. */
  5095. Matrix.prototype.copyFrom = function (other) {
  5096. for (var index = 0; index < 16; index++) {
  5097. this.m[index] = other.m[index];
  5098. }
  5099. this._markAsUpdated();
  5100. return this;
  5101. };
  5102. /**
  5103. * Populates the passed array from the starting index with the Matrix values.
  5104. * Returns the Matrix.
  5105. */
  5106. Matrix.prototype.copyToArray = function (array, offset) {
  5107. if (offset === void 0) { offset = 0; }
  5108. for (var index = 0; index < 16; index++) {
  5109. array[offset + index] = this.m[index];
  5110. }
  5111. return this;
  5112. };
  5113. /**
  5114. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5115. */
  5116. Matrix.prototype.multiplyToRef = function (other, result) {
  5117. this.multiplyToArray(other, result.m, 0);
  5118. result._markAsUpdated();
  5119. return this;
  5120. };
  5121. /**
  5122. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5123. */
  5124. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5125. var tm0 = this.m[0];
  5126. var tm1 = this.m[1];
  5127. var tm2 = this.m[2];
  5128. var tm3 = this.m[3];
  5129. var tm4 = this.m[4];
  5130. var tm5 = this.m[5];
  5131. var tm6 = this.m[6];
  5132. var tm7 = this.m[7];
  5133. var tm8 = this.m[8];
  5134. var tm9 = this.m[9];
  5135. var tm10 = this.m[10];
  5136. var tm11 = this.m[11];
  5137. var tm12 = this.m[12];
  5138. var tm13 = this.m[13];
  5139. var tm14 = this.m[14];
  5140. var tm15 = this.m[15];
  5141. var om0 = other.m[0];
  5142. var om1 = other.m[1];
  5143. var om2 = other.m[2];
  5144. var om3 = other.m[3];
  5145. var om4 = other.m[4];
  5146. var om5 = other.m[5];
  5147. var om6 = other.m[6];
  5148. var om7 = other.m[7];
  5149. var om8 = other.m[8];
  5150. var om9 = other.m[9];
  5151. var om10 = other.m[10];
  5152. var om11 = other.m[11];
  5153. var om12 = other.m[12];
  5154. var om13 = other.m[13];
  5155. var om14 = other.m[14];
  5156. var om15 = other.m[15];
  5157. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5158. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5159. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5160. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5161. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5162. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5163. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5164. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5165. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5166. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5167. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5168. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5169. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5170. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5171. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5172. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5173. return this;
  5174. };
  5175. /**
  5176. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5177. */
  5178. Matrix.prototype.equals = function (value) {
  5179. return value &&
  5180. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5181. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5182. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5183. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5184. };
  5185. /**
  5186. * Returns a new Matrix from the current Matrix.
  5187. */
  5188. Matrix.prototype.clone = function () {
  5189. 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]);
  5190. };
  5191. /**
  5192. * Returns the string "Matrix"
  5193. */
  5194. Matrix.prototype.getClassName = function () {
  5195. return "Matrix";
  5196. };
  5197. /**
  5198. * Returns the Matrix hash code.
  5199. */
  5200. Matrix.prototype.getHashCode = function () {
  5201. var hash = this.m[0] || 0;
  5202. for (var i = 1; i < 16; i++) {
  5203. hash = (hash * 397) ^ (this.m[i] || 0);
  5204. }
  5205. return hash;
  5206. };
  5207. /**
  5208. * Decomposes the current Matrix into :
  5209. * - a scale vector3 passed as a reference to update,
  5210. * - a rotation quaternion passed as a reference to update,
  5211. * - a translation vector3 passed as a reference to update.
  5212. * Returns the true if operation was successful.
  5213. */
  5214. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5215. translation.x = this.m[12];
  5216. translation.y = this.m[13];
  5217. translation.z = this.m[14];
  5218. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5219. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5220. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5221. if (this.determinant() <= 0) {
  5222. scale.y *= -1;
  5223. }
  5224. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5225. rotation.x = 0;
  5226. rotation.y = 0;
  5227. rotation.z = 0;
  5228. rotation.w = 1;
  5229. return false;
  5230. }
  5231. 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]);
  5232. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5233. return true;
  5234. };
  5235. /**
  5236. * Returns the index-th row of the current matrix as a new Vector4.
  5237. */
  5238. Matrix.prototype.getRow = function (index) {
  5239. if (index < 0 || index > 3) {
  5240. return null;
  5241. }
  5242. var i = index * 4;
  5243. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5244. };
  5245. /**
  5246. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5247. * Returns the updated Matrix.
  5248. */
  5249. Matrix.prototype.setRow = function (index, row) {
  5250. if (index < 0 || index > 3) {
  5251. return this;
  5252. }
  5253. var i = index * 4;
  5254. this.m[i + 0] = row.x;
  5255. this.m[i + 1] = row.y;
  5256. this.m[i + 2] = row.z;
  5257. this.m[i + 3] = row.w;
  5258. this._markAsUpdated();
  5259. return this;
  5260. };
  5261. /**
  5262. * Compute the transpose of the matrix.
  5263. * Returns a new Matrix.
  5264. */
  5265. Matrix.prototype.transpose = function () {
  5266. return Matrix.Transpose(this);
  5267. };
  5268. /**
  5269. * Compute the transpose of the matrix.
  5270. * Returns the current matrix.
  5271. */
  5272. Matrix.prototype.transposeToRef = function (result) {
  5273. Matrix.TransposeToRef(this, result);
  5274. return this;
  5275. };
  5276. /**
  5277. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5278. * Returns the updated Matrix.
  5279. */
  5280. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5281. if (index < 0 || index > 3) {
  5282. return this;
  5283. }
  5284. var i = index * 4;
  5285. this.m[i + 0] = x;
  5286. this.m[i + 1] = y;
  5287. this.m[i + 2] = z;
  5288. this.m[i + 3] = w;
  5289. this._markAsUpdated();
  5290. return this;
  5291. };
  5292. /**
  5293. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5294. * @param scale defines the scale factor
  5295. * @returns a new Matrix
  5296. */
  5297. Matrix.prototype.scale = function (scale) {
  5298. var result = new Matrix();
  5299. this.scaleToRef(scale, result);
  5300. return result;
  5301. };
  5302. /**
  5303. * Scale the current Matrix values by a factor to a given result Matrix
  5304. * @param scale defines the scale factor
  5305. * @param result defines the Matrix to store the result
  5306. * @returns the current Matrix
  5307. */
  5308. Matrix.prototype.scaleToRef = function (scale, result) {
  5309. for (var index = 0; index < 16; index++) {
  5310. result.m[index] = this.m[index] * scale;
  5311. }
  5312. result._markAsUpdated();
  5313. return this;
  5314. };
  5315. /**
  5316. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5317. * @param scale defines the scale factor
  5318. * @param result defines the Matrix to store the result
  5319. * @returns the current Matrix
  5320. */
  5321. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5322. for (var index = 0; index < 16; index++) {
  5323. result.m[index] += this.m[index] * scale;
  5324. }
  5325. result._markAsUpdated();
  5326. return this;
  5327. };
  5328. /**
  5329. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5330. * @param ref matrix to store the result
  5331. */
  5332. Matrix.prototype.toNormalMatrix = function (ref) {
  5333. this.invertToRef(ref);
  5334. ref.transpose();
  5335. var m = ref.m;
  5336. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5337. };
  5338. /**
  5339. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5340. */
  5341. Matrix.prototype.getRotationMatrix = function () {
  5342. var result = Matrix.Identity();
  5343. this.getRotationMatrixToRef(result);
  5344. return result;
  5345. };
  5346. /**
  5347. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5348. * Returns the current Matrix.
  5349. */
  5350. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5351. var m = this.m;
  5352. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5353. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5354. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5355. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5356. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5357. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5358. 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);
  5359. return this;
  5360. };
  5361. // Statics
  5362. /**
  5363. * Returns a new Matrix set from the starting index of the passed array.
  5364. */
  5365. Matrix.FromArray = function (array, offset) {
  5366. var result = new Matrix();
  5367. if (!offset) {
  5368. offset = 0;
  5369. }
  5370. Matrix.FromArrayToRef(array, offset, result);
  5371. return result;
  5372. };
  5373. /**
  5374. * Sets the passed "result" matrix from the starting index of the passed array.
  5375. */
  5376. Matrix.FromArrayToRef = function (array, offset, result) {
  5377. for (var index = 0; index < 16; index++) {
  5378. result.m[index] = array[index + offset];
  5379. }
  5380. result._markAsUpdated();
  5381. };
  5382. /**
  5383. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5384. */
  5385. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5386. for (var index = 0; index < 16; index++) {
  5387. result.m[index] = array[index + offset] * scale;
  5388. }
  5389. result._markAsUpdated();
  5390. };
  5391. /**
  5392. * Sets the passed matrix "result" with the 16 passed floats.
  5393. */
  5394. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5395. result.m[0] = initialM11;
  5396. result.m[1] = initialM12;
  5397. result.m[2] = initialM13;
  5398. result.m[3] = initialM14;
  5399. result.m[4] = initialM21;
  5400. result.m[5] = initialM22;
  5401. result.m[6] = initialM23;
  5402. result.m[7] = initialM24;
  5403. result.m[8] = initialM31;
  5404. result.m[9] = initialM32;
  5405. result.m[10] = initialM33;
  5406. result.m[11] = initialM34;
  5407. result.m[12] = initialM41;
  5408. result.m[13] = initialM42;
  5409. result.m[14] = initialM43;
  5410. result.m[15] = initialM44;
  5411. result._markAsUpdated();
  5412. };
  5413. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5414. /**
  5415. * Static identity matrix to be used as readonly matrix
  5416. * Must not be updated.
  5417. */
  5418. get: function () {
  5419. return Matrix._identityReadOnly;
  5420. },
  5421. enumerable: true,
  5422. configurable: true
  5423. });
  5424. /**
  5425. * Returns a new Matrix set from the 16 passed floats.
  5426. */
  5427. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5428. var result = new Matrix();
  5429. result.m[0] = initialM11;
  5430. result.m[1] = initialM12;
  5431. result.m[2] = initialM13;
  5432. result.m[3] = initialM14;
  5433. result.m[4] = initialM21;
  5434. result.m[5] = initialM22;
  5435. result.m[6] = initialM23;
  5436. result.m[7] = initialM24;
  5437. result.m[8] = initialM31;
  5438. result.m[9] = initialM32;
  5439. result.m[10] = initialM33;
  5440. result.m[11] = initialM34;
  5441. result.m[12] = initialM41;
  5442. result.m[13] = initialM42;
  5443. result.m[14] = initialM43;
  5444. result.m[15] = initialM44;
  5445. return result;
  5446. };
  5447. /**
  5448. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5449. */
  5450. Matrix.Compose = function (scale, rotation, translation) {
  5451. var result = Matrix.Identity();
  5452. Matrix.ComposeToRef(scale, rotation, translation, result);
  5453. return result;
  5454. };
  5455. /**
  5456. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5457. */
  5458. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5459. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5460. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5461. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5462. result.setTranslation(translation);
  5463. };
  5464. /**
  5465. * Returns a new indentity Matrix.
  5466. */
  5467. Matrix.Identity = function () {
  5468. 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);
  5469. };
  5470. /**
  5471. * Sets the passed "result" as an identity matrix.
  5472. */
  5473. Matrix.IdentityToRef = function (result) {
  5474. 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);
  5475. };
  5476. /**
  5477. * Returns a new zero Matrix.
  5478. */
  5479. Matrix.Zero = function () {
  5480. 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);
  5481. };
  5482. /**
  5483. * Returns a new rotation matrix for "angle" radians around the X axis.
  5484. */
  5485. Matrix.RotationX = function (angle) {
  5486. var result = new Matrix();
  5487. Matrix.RotationXToRef(angle, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Returns a new Matrix as the passed inverted one.
  5492. */
  5493. Matrix.Invert = function (source) {
  5494. var result = new Matrix();
  5495. source.invertToRef(result);
  5496. return result;
  5497. };
  5498. /**
  5499. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5500. */
  5501. Matrix.RotationXToRef = function (angle, result) {
  5502. var s = Math.sin(angle);
  5503. var c = Math.cos(angle);
  5504. result.m[0] = 1.0;
  5505. result.m[15] = 1.0;
  5506. result.m[5] = c;
  5507. result.m[10] = c;
  5508. result.m[9] = -s;
  5509. result.m[6] = s;
  5510. result.m[1] = 0.0;
  5511. result.m[2] = 0.0;
  5512. result.m[3] = 0.0;
  5513. result.m[4] = 0.0;
  5514. result.m[7] = 0.0;
  5515. result.m[8] = 0.0;
  5516. result.m[11] = 0.0;
  5517. result.m[12] = 0.0;
  5518. result.m[13] = 0.0;
  5519. result.m[14] = 0.0;
  5520. result._markAsUpdated();
  5521. };
  5522. /**
  5523. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5524. */
  5525. Matrix.RotationY = function (angle) {
  5526. var result = new Matrix();
  5527. Matrix.RotationYToRef(angle, result);
  5528. return result;
  5529. };
  5530. /**
  5531. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5532. */
  5533. Matrix.RotationYToRef = function (angle, result) {
  5534. var s = Math.sin(angle);
  5535. var c = Math.cos(angle);
  5536. result.m[5] = 1.0;
  5537. result.m[15] = 1.0;
  5538. result.m[0] = c;
  5539. result.m[2] = -s;
  5540. result.m[8] = s;
  5541. result.m[10] = c;
  5542. result.m[1] = 0.0;
  5543. result.m[3] = 0.0;
  5544. result.m[4] = 0.0;
  5545. result.m[6] = 0.0;
  5546. result.m[7] = 0.0;
  5547. result.m[9] = 0.0;
  5548. result.m[11] = 0.0;
  5549. result.m[12] = 0.0;
  5550. result.m[13] = 0.0;
  5551. result.m[14] = 0.0;
  5552. result._markAsUpdated();
  5553. };
  5554. /**
  5555. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5556. */
  5557. Matrix.RotationZ = function (angle) {
  5558. var result = new Matrix();
  5559. Matrix.RotationZToRef(angle, result);
  5560. return result;
  5561. };
  5562. /**
  5563. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5564. */
  5565. Matrix.RotationZToRef = function (angle, result) {
  5566. var s = Math.sin(angle);
  5567. var c = Math.cos(angle);
  5568. result.m[10] = 1.0;
  5569. result.m[15] = 1.0;
  5570. result.m[0] = c;
  5571. result.m[1] = s;
  5572. result.m[4] = -s;
  5573. result.m[5] = c;
  5574. result.m[2] = 0.0;
  5575. result.m[3] = 0.0;
  5576. result.m[6] = 0.0;
  5577. result.m[7] = 0.0;
  5578. result.m[8] = 0.0;
  5579. result.m[9] = 0.0;
  5580. result.m[11] = 0.0;
  5581. result.m[12] = 0.0;
  5582. result.m[13] = 0.0;
  5583. result.m[14] = 0.0;
  5584. result._markAsUpdated();
  5585. };
  5586. /**
  5587. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5588. */
  5589. Matrix.RotationAxis = function (axis, angle) {
  5590. var result = Matrix.Zero();
  5591. Matrix.RotationAxisToRef(axis, angle, result);
  5592. return result;
  5593. };
  5594. /**
  5595. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5596. */
  5597. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5598. var s = Math.sin(-angle);
  5599. var c = Math.cos(-angle);
  5600. var c1 = 1 - c;
  5601. axis.normalize();
  5602. result.m[0] = (axis.x * axis.x) * c1 + c;
  5603. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5604. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5605. result.m[3] = 0.0;
  5606. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5607. result.m[5] = (axis.y * axis.y) * c1 + c;
  5608. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5609. result.m[7] = 0.0;
  5610. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5611. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5612. result.m[10] = (axis.z * axis.z) * c1 + c;
  5613. result.m[11] = 0.0;
  5614. result.m[15] = 1.0;
  5615. result._markAsUpdated();
  5616. };
  5617. /**
  5618. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5619. */
  5620. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5621. var result = new Matrix();
  5622. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5623. return result;
  5624. };
  5625. /**
  5626. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5627. */
  5628. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5629. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5630. this._tempQuaternion.toRotationMatrix(result);
  5631. };
  5632. /**
  5633. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5634. */
  5635. Matrix.Scaling = function (x, y, z) {
  5636. var result = Matrix.Zero();
  5637. Matrix.ScalingToRef(x, y, z, result);
  5638. return result;
  5639. };
  5640. /**
  5641. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5642. */
  5643. Matrix.ScalingToRef = function (x, y, z, result) {
  5644. result.m[0] = x;
  5645. result.m[1] = 0.0;
  5646. result.m[2] = 0.0;
  5647. result.m[3] = 0.0;
  5648. result.m[4] = 0.0;
  5649. result.m[5] = y;
  5650. result.m[6] = 0.0;
  5651. result.m[7] = 0.0;
  5652. result.m[8] = 0.0;
  5653. result.m[9] = 0.0;
  5654. result.m[10] = z;
  5655. result.m[11] = 0.0;
  5656. result.m[12] = 0.0;
  5657. result.m[13] = 0.0;
  5658. result.m[14] = 0.0;
  5659. result.m[15] = 1.0;
  5660. result._markAsUpdated();
  5661. };
  5662. /**
  5663. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5664. */
  5665. Matrix.Translation = function (x, y, z) {
  5666. var result = Matrix.Identity();
  5667. Matrix.TranslationToRef(x, y, z, result);
  5668. return result;
  5669. };
  5670. /**
  5671. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5672. */
  5673. Matrix.TranslationToRef = function (x, y, z, result) {
  5674. 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);
  5675. };
  5676. /**
  5677. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5678. * @param startValue defines the start value
  5679. * @param endValue defines the end value
  5680. * @param gradient defines the gradient factor
  5681. * @returns the new matrix
  5682. */
  5683. Matrix.Lerp = function (startValue, endValue, gradient) {
  5684. var result = Matrix.Zero();
  5685. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5686. return result;
  5687. };
  5688. /**
  5689. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5690. * @param startValue defines the start value
  5691. * @param endValue defines the end value
  5692. * @param gradient defines the gradient factor
  5693. * @param result defines the Matrix object where to store data
  5694. */
  5695. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5696. for (var index = 0; index < 16; index++) {
  5697. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5698. }
  5699. result._markAsUpdated();
  5700. };
  5701. /**
  5702. * Returns a new Matrix whose values are computed by :
  5703. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5704. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5705. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5706. */
  5707. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5708. var startScale = new Vector3(0, 0, 0);
  5709. var startRotation = new Quaternion();
  5710. var startTranslation = new Vector3(0, 0, 0);
  5711. startValue.decompose(startScale, startRotation, startTranslation);
  5712. var endScale = new Vector3(0, 0, 0);
  5713. var endRotation = new Quaternion();
  5714. var endTranslation = new Vector3(0, 0, 0);
  5715. endValue.decompose(endScale, endRotation, endTranslation);
  5716. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5717. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5718. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5719. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5720. };
  5721. /**
  5722. * 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".
  5723. * This methods works for a Left-Handed system.
  5724. */
  5725. Matrix.LookAtLH = function (eye, target, up) {
  5726. var result = Matrix.Zero();
  5727. Matrix.LookAtLHToRef(eye, target, up, result);
  5728. return result;
  5729. };
  5730. /**
  5731. * 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".
  5732. * This methods works for a Left-Handed system.
  5733. */
  5734. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5735. // Z axis
  5736. target.subtractToRef(eye, this._zAxis);
  5737. this._zAxis.normalize();
  5738. // X axis
  5739. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5740. if (this._xAxis.lengthSquared() === 0) {
  5741. this._xAxis.x = 1.0;
  5742. }
  5743. else {
  5744. this._xAxis.normalize();
  5745. }
  5746. // Y axis
  5747. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5748. this._yAxis.normalize();
  5749. // Eye angles
  5750. var ex = -Vector3.Dot(this._xAxis, eye);
  5751. var ey = -Vector3.Dot(this._yAxis, eye);
  5752. var ez = -Vector3.Dot(this._zAxis, eye);
  5753. 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);
  5754. };
  5755. /**
  5756. * 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".
  5757. * This methods works for a Right-Handed system.
  5758. */
  5759. Matrix.LookAtRH = function (eye, target, up) {
  5760. var result = Matrix.Zero();
  5761. Matrix.LookAtRHToRef(eye, target, up, result);
  5762. return result;
  5763. };
  5764. /**
  5765. * 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".
  5766. * This methods works for a Left-Handed system.
  5767. */
  5768. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5769. // Z axis
  5770. eye.subtractToRef(target, this._zAxis);
  5771. this._zAxis.normalize();
  5772. // X axis
  5773. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5774. if (this._xAxis.lengthSquared() === 0) {
  5775. this._xAxis.x = 1.0;
  5776. }
  5777. else {
  5778. this._xAxis.normalize();
  5779. }
  5780. // Y axis
  5781. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5782. this._yAxis.normalize();
  5783. // Eye angles
  5784. var ex = -Vector3.Dot(this._xAxis, eye);
  5785. var ey = -Vector3.Dot(this._yAxis, eye);
  5786. var ez = -Vector3.Dot(this._zAxis, eye);
  5787. 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);
  5788. };
  5789. /**
  5790. * 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.
  5791. */
  5792. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5793. var matrix = Matrix.Zero();
  5794. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5795. return matrix;
  5796. };
  5797. /**
  5798. * 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.
  5799. */
  5800. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5801. var n = znear;
  5802. var f = zfar;
  5803. var a = 2.0 / width;
  5804. var b = 2.0 / height;
  5805. var c = 2.0 / (f - n);
  5806. var d = -(f + n) / (f - n);
  5807. 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);
  5808. };
  5809. /**
  5810. * 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.
  5811. */
  5812. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5813. var matrix = Matrix.Zero();
  5814. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5815. return matrix;
  5816. };
  5817. /**
  5818. * 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.
  5819. */
  5820. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5821. var n = znear;
  5822. var f = zfar;
  5823. var a = 2.0 / (right - left);
  5824. var b = 2.0 / (top - bottom);
  5825. var c = 2.0 / (f - n);
  5826. var d = -(f + n) / (f - n);
  5827. var i0 = (left + right) / (left - right);
  5828. var i1 = (top + bottom) / (bottom - top);
  5829. 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);
  5830. };
  5831. /**
  5832. * 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.
  5833. */
  5834. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5835. var matrix = Matrix.Zero();
  5836. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5837. return matrix;
  5838. };
  5839. /**
  5840. * 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.
  5841. */
  5842. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5843. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5844. result.m[10] *= -1.0;
  5845. };
  5846. /**
  5847. * 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.
  5848. */
  5849. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5850. var matrix = Matrix.Zero();
  5851. var n = znear;
  5852. var f = zfar;
  5853. var a = 2.0 * n / width;
  5854. var b = 2.0 * n / height;
  5855. var c = (f + n) / (f - n);
  5856. var d = -2.0 * f * n / (f - n);
  5857. 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);
  5858. return matrix;
  5859. };
  5860. /**
  5861. * 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.
  5862. */
  5863. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5864. var matrix = Matrix.Zero();
  5865. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5866. return matrix;
  5867. };
  5868. /**
  5869. * 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.
  5870. */
  5871. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5872. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5873. var n = znear;
  5874. var f = zfar;
  5875. var t = 1.0 / (Math.tan(fov * 0.5));
  5876. var a = isVerticalFovFixed ? (t / aspect) : t;
  5877. var b = isVerticalFovFixed ? t : (t * aspect);
  5878. var c = (f + n) / (f - n);
  5879. var d = -2.0 * f * n / (f - n);
  5880. 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);
  5881. };
  5882. /**
  5883. * 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.
  5884. */
  5885. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5886. var matrix = Matrix.Zero();
  5887. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5888. return matrix;
  5889. };
  5890. /**
  5891. * 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.
  5892. */
  5893. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5894. //alternatively this could be expressed as:
  5895. // m = PerspectiveFovLHToRef
  5896. // m[10] *= -1.0;
  5897. // m[11] *= -1.0;
  5898. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5899. var n = znear;
  5900. var f = zfar;
  5901. var t = 1.0 / (Math.tan(fov * 0.5));
  5902. var a = isVerticalFovFixed ? (t / aspect) : t;
  5903. var b = isVerticalFovFixed ? t : (t * aspect);
  5904. var c = -(f + n) / (f - n);
  5905. var d = -2 * f * n / (f - n);
  5906. 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);
  5907. };
  5908. /**
  5909. * 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.
  5910. */
  5911. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5912. if (rightHanded === void 0) { rightHanded = false; }
  5913. var rightHandedFactor = rightHanded ? -1 : 1;
  5914. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5915. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5916. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5917. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5918. var xScale = 2.0 / (leftTan + rightTan);
  5919. var yScale = 2.0 / (upTan + downTan);
  5920. result.m[0] = xScale;
  5921. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5922. result.m[5] = yScale;
  5923. result.m[6] = result.m[7] = 0.0;
  5924. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5925. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5926. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5927. result.m[10] = -zfar / (znear - zfar);
  5928. result.m[11] = 1.0 * rightHandedFactor;
  5929. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5930. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5931. // result.m[14] = (znear * zfar) / (znear - zfar);
  5932. result._markAsUpdated();
  5933. };
  5934. /**
  5935. * Returns the final transformation matrix : world * view * projection * viewport
  5936. */
  5937. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5938. var cw = viewport.width;
  5939. var ch = viewport.height;
  5940. var cx = viewport.x;
  5941. var cy = viewport.y;
  5942. 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);
  5943. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5944. };
  5945. /**
  5946. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5947. */
  5948. Matrix.GetAsMatrix2x2 = function (matrix) {
  5949. return new Float32Array([
  5950. matrix.m[0], matrix.m[1],
  5951. matrix.m[4], matrix.m[5]
  5952. ]);
  5953. };
  5954. /**
  5955. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5956. */
  5957. Matrix.GetAsMatrix3x3 = function (matrix) {
  5958. return new Float32Array([
  5959. matrix.m[0], matrix.m[1], matrix.m[2],
  5960. matrix.m[4], matrix.m[5], matrix.m[6],
  5961. matrix.m[8], matrix.m[9], matrix.m[10]
  5962. ]);
  5963. };
  5964. /**
  5965. * Compute the transpose of the passed Matrix.
  5966. * Returns a new Matrix.
  5967. */
  5968. Matrix.Transpose = function (matrix) {
  5969. var result = new Matrix();
  5970. Matrix.TransposeToRef(matrix, result);
  5971. return result;
  5972. };
  5973. /**
  5974. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5975. */
  5976. Matrix.TransposeToRef = function (matrix, result) {
  5977. result.m[0] = matrix.m[0];
  5978. result.m[1] = matrix.m[4];
  5979. result.m[2] = matrix.m[8];
  5980. result.m[3] = matrix.m[12];
  5981. result.m[4] = matrix.m[1];
  5982. result.m[5] = matrix.m[5];
  5983. result.m[6] = matrix.m[9];
  5984. result.m[7] = matrix.m[13];
  5985. result.m[8] = matrix.m[2];
  5986. result.m[9] = matrix.m[6];
  5987. result.m[10] = matrix.m[10];
  5988. result.m[11] = matrix.m[14];
  5989. result.m[12] = matrix.m[3];
  5990. result.m[13] = matrix.m[7];
  5991. result.m[14] = matrix.m[11];
  5992. result.m[15] = matrix.m[15];
  5993. };
  5994. /**
  5995. * Returns a new Matrix as the reflection matrix across the passed plane.
  5996. */
  5997. Matrix.Reflection = function (plane) {
  5998. var matrix = new Matrix();
  5999. Matrix.ReflectionToRef(plane, matrix);
  6000. return matrix;
  6001. };
  6002. /**
  6003. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  6004. */
  6005. Matrix.ReflectionToRef = function (plane, result) {
  6006. plane.normalize();
  6007. var x = plane.normal.x;
  6008. var y = plane.normal.y;
  6009. var z = plane.normal.z;
  6010. var temp = -2 * x;
  6011. var temp2 = -2 * y;
  6012. var temp3 = -2 * z;
  6013. result.m[0] = (temp * x) + 1;
  6014. result.m[1] = temp2 * x;
  6015. result.m[2] = temp3 * x;
  6016. result.m[3] = 0.0;
  6017. result.m[4] = temp * y;
  6018. result.m[5] = (temp2 * y) + 1;
  6019. result.m[6] = temp3 * y;
  6020. result.m[7] = 0.0;
  6021. result.m[8] = temp * z;
  6022. result.m[9] = temp2 * z;
  6023. result.m[10] = (temp3 * z) + 1;
  6024. result.m[11] = 0.0;
  6025. result.m[12] = temp * plane.d;
  6026. result.m[13] = temp2 * plane.d;
  6027. result.m[14] = temp3 * plane.d;
  6028. result.m[15] = 1.0;
  6029. result._markAsUpdated();
  6030. };
  6031. /**
  6032. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  6033. */
  6034. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6035. result.m[0] = xaxis.x;
  6036. result.m[1] = xaxis.y;
  6037. result.m[2] = xaxis.z;
  6038. result.m[3] = 0.0;
  6039. result.m[4] = yaxis.x;
  6040. result.m[5] = yaxis.y;
  6041. result.m[6] = yaxis.z;
  6042. result.m[7] = 0.0;
  6043. result.m[8] = zaxis.x;
  6044. result.m[9] = zaxis.y;
  6045. result.m[10] = zaxis.z;
  6046. result.m[11] = 0.0;
  6047. result.m[12] = 0.0;
  6048. result.m[13] = 0.0;
  6049. result.m[14] = 0.0;
  6050. result.m[15] = 1.0;
  6051. result._markAsUpdated();
  6052. };
  6053. /**
  6054. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  6055. */
  6056. Matrix.FromQuaternionToRef = function (quat, result) {
  6057. var xx = quat.x * quat.x;
  6058. var yy = quat.y * quat.y;
  6059. var zz = quat.z * quat.z;
  6060. var xy = quat.x * quat.y;
  6061. var zw = quat.z * quat.w;
  6062. var zx = quat.z * quat.x;
  6063. var yw = quat.y * quat.w;
  6064. var yz = quat.y * quat.z;
  6065. var xw = quat.x * quat.w;
  6066. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6067. result.m[1] = 2.0 * (xy + zw);
  6068. result.m[2] = 2.0 * (zx - yw);
  6069. result.m[3] = 0.0;
  6070. result.m[4] = 2.0 * (xy - zw);
  6071. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6072. result.m[6] = 2.0 * (yz + xw);
  6073. result.m[7] = 0.0;
  6074. result.m[8] = 2.0 * (zx + yw);
  6075. result.m[9] = 2.0 * (yz - xw);
  6076. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6077. result.m[11] = 0.0;
  6078. result.m[12] = 0.0;
  6079. result.m[13] = 0.0;
  6080. result.m[14] = 0.0;
  6081. result.m[15] = 1.0;
  6082. result._markAsUpdated();
  6083. };
  6084. Matrix._tempQuaternion = new Quaternion();
  6085. Matrix._xAxis = Vector3.Zero();
  6086. Matrix._yAxis = Vector3.Zero();
  6087. Matrix._zAxis = Vector3.Zero();
  6088. Matrix._updateFlagSeed = 0;
  6089. Matrix._identityReadOnly = Matrix.Identity();
  6090. return Matrix;
  6091. }());
  6092. BABYLON.Matrix = Matrix;
  6093. var Plane = /** @class */ (function () {
  6094. /**
  6095. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6096. */
  6097. function Plane(a, b, c, d) {
  6098. this.normal = new Vector3(a, b, c);
  6099. this.d = d;
  6100. }
  6101. /**
  6102. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6103. */
  6104. Plane.prototype.asArray = function () {
  6105. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6106. };
  6107. // Methods
  6108. /**
  6109. * Returns a new plane copied from the current Plane.
  6110. */
  6111. Plane.prototype.clone = function () {
  6112. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6113. };
  6114. /**
  6115. * Returns the string "Plane".
  6116. */
  6117. Plane.prototype.getClassName = function () {
  6118. return "Plane";
  6119. };
  6120. /**
  6121. * Returns the Plane hash code.
  6122. */
  6123. Plane.prototype.getHashCode = function () {
  6124. var hash = this.normal.getHashCode();
  6125. hash = (hash * 397) ^ (this.d || 0);
  6126. return hash;
  6127. };
  6128. /**
  6129. * Normalize the current Plane in place.
  6130. * Returns the updated Plane.
  6131. */
  6132. Plane.prototype.normalize = function () {
  6133. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6134. var magnitude = 0.0;
  6135. if (norm !== 0) {
  6136. magnitude = 1.0 / norm;
  6137. }
  6138. this.normal.x *= magnitude;
  6139. this.normal.y *= magnitude;
  6140. this.normal.z *= magnitude;
  6141. this.d *= magnitude;
  6142. return this;
  6143. };
  6144. /**
  6145. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6146. */
  6147. Plane.prototype.transform = function (transformation) {
  6148. var transposedMatrix = Matrix.Transpose(transformation);
  6149. var x = this.normal.x;
  6150. var y = this.normal.y;
  6151. var z = this.normal.z;
  6152. var d = this.d;
  6153. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6154. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6155. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6156. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6157. return new Plane(normalX, normalY, normalZ, finalD);
  6158. };
  6159. /**
  6160. * Returns the dot product (float) of the point coordinates and the plane normal.
  6161. */
  6162. Plane.prototype.dotCoordinate = function (point) {
  6163. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6164. };
  6165. /**
  6166. * Updates the current Plane from the plane defined by the three passed points.
  6167. * Returns the updated Plane.
  6168. */
  6169. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6170. var x1 = point2.x - point1.x;
  6171. var y1 = point2.y - point1.y;
  6172. var z1 = point2.z - point1.z;
  6173. var x2 = point3.x - point1.x;
  6174. var y2 = point3.y - point1.y;
  6175. var z2 = point3.z - point1.z;
  6176. var yz = (y1 * z2) - (z1 * y2);
  6177. var xz = (z1 * x2) - (x1 * z2);
  6178. var xy = (x1 * y2) - (y1 * x2);
  6179. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6180. var invPyth;
  6181. if (pyth !== 0) {
  6182. invPyth = 1.0 / pyth;
  6183. }
  6184. else {
  6185. invPyth = 0.0;
  6186. }
  6187. this.normal.x = yz * invPyth;
  6188. this.normal.y = xz * invPyth;
  6189. this.normal.z = xy * invPyth;
  6190. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6191. return this;
  6192. };
  6193. /**
  6194. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6195. */
  6196. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6197. var dot = Vector3.Dot(this.normal, direction);
  6198. return (dot <= epsilon);
  6199. };
  6200. /**
  6201. * Returns the signed distance (float) from the passed point to the Plane.
  6202. */
  6203. Plane.prototype.signedDistanceTo = function (point) {
  6204. return Vector3.Dot(point, this.normal) + this.d;
  6205. };
  6206. // Statics
  6207. /**
  6208. * Returns a new Plane from the passed array.
  6209. */
  6210. Plane.FromArray = function (array) {
  6211. return new Plane(array[0], array[1], array[2], array[3]);
  6212. };
  6213. /**
  6214. * Returns a new Plane defined by the three passed points.
  6215. */
  6216. Plane.FromPoints = function (point1, point2, point3) {
  6217. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6218. result.copyFromPoints(point1, point2, point3);
  6219. return result;
  6220. };
  6221. /**
  6222. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6223. * Note : the vector "normal" is updated because normalized.
  6224. */
  6225. Plane.FromPositionAndNormal = function (origin, normal) {
  6226. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6227. normal.normalize();
  6228. result.normal = normal;
  6229. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6230. return result;
  6231. };
  6232. /**
  6233. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6234. */
  6235. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6236. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6237. return Vector3.Dot(point, normal) + d;
  6238. };
  6239. return Plane;
  6240. }());
  6241. BABYLON.Plane = Plane;
  6242. var Viewport = /** @class */ (function () {
  6243. /**
  6244. * Creates a Viewport object located at (x, y) and sized (width, height).
  6245. */
  6246. function Viewport(x, y, width, height) {
  6247. this.x = x;
  6248. this.y = y;
  6249. this.width = width;
  6250. this.height = height;
  6251. }
  6252. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6253. if (renderWidthOrEngine.getRenderWidth) {
  6254. var engine = renderWidthOrEngine;
  6255. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6256. }
  6257. var renderWidth = renderWidthOrEngine;
  6258. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6259. };
  6260. /**
  6261. * Returns a new Viewport copied from the current one.
  6262. */
  6263. Viewport.prototype.clone = function () {
  6264. return new Viewport(this.x, this.y, this.width, this.height);
  6265. };
  6266. return Viewport;
  6267. }());
  6268. BABYLON.Viewport = Viewport;
  6269. var Frustum = /** @class */ (function () {
  6270. function Frustum() {
  6271. }
  6272. /**
  6273. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6274. */
  6275. Frustum.GetPlanes = function (transform) {
  6276. var frustumPlanes = [];
  6277. for (var index = 0; index < 6; index++) {
  6278. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6279. }
  6280. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6281. return frustumPlanes;
  6282. };
  6283. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6284. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6285. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6286. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6287. frustumPlane.d = transform.m[15] + transform.m[14];
  6288. frustumPlane.normalize();
  6289. };
  6290. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6291. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6292. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6293. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6294. frustumPlane.d = transform.m[15] - transform.m[14];
  6295. frustumPlane.normalize();
  6296. };
  6297. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6298. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6299. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6300. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6301. frustumPlane.d = transform.m[15] + transform.m[12];
  6302. frustumPlane.normalize();
  6303. };
  6304. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6305. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6306. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6307. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6308. frustumPlane.d = transform.m[15] - transform.m[12];
  6309. frustumPlane.normalize();
  6310. };
  6311. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6312. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6313. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6314. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6315. frustumPlane.d = transform.m[15] - transform.m[13];
  6316. frustumPlane.normalize();
  6317. };
  6318. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6319. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6320. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6321. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6322. frustumPlane.d = transform.m[15] + transform.m[13];
  6323. frustumPlane.normalize();
  6324. };
  6325. /**
  6326. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6327. */
  6328. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6329. // Near
  6330. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6331. // Far
  6332. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6333. // Left
  6334. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6335. // Right
  6336. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6337. // Top
  6338. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6339. // Bottom
  6340. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6341. };
  6342. return Frustum;
  6343. }());
  6344. BABYLON.Frustum = Frustum;
  6345. var Space;
  6346. (function (Space) {
  6347. Space[Space["LOCAL"] = 0] = "LOCAL";
  6348. Space[Space["WORLD"] = 1] = "WORLD";
  6349. Space[Space["BONE"] = 2] = "BONE";
  6350. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6351. var Axis = /** @class */ (function () {
  6352. function Axis() {
  6353. }
  6354. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6355. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6356. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6357. return Axis;
  6358. }());
  6359. BABYLON.Axis = Axis;
  6360. ;
  6361. var BezierCurve = /** @class */ (function () {
  6362. function BezierCurve() {
  6363. }
  6364. /**
  6365. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6366. */
  6367. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6368. // Extract X (which is equal to time here)
  6369. var f0 = 1 - 3 * x2 + 3 * x1;
  6370. var f1 = 3 * x2 - 6 * x1;
  6371. var f2 = 3 * x1;
  6372. var refinedT = t;
  6373. for (var i = 0; i < 5; i++) {
  6374. var refinedT2 = refinedT * refinedT;
  6375. var refinedT3 = refinedT2 * refinedT;
  6376. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6377. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6378. refinedT -= (x - t) * slope;
  6379. refinedT = Math.min(1, Math.max(0, refinedT));
  6380. }
  6381. // Resolve cubic bezier for the given x
  6382. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6383. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6384. Math.pow(refinedT, 3);
  6385. };
  6386. return BezierCurve;
  6387. }());
  6388. BABYLON.BezierCurve = BezierCurve;
  6389. var Orientation;
  6390. (function (Orientation) {
  6391. Orientation[Orientation["CW"] = 0] = "CW";
  6392. Orientation[Orientation["CCW"] = 1] = "CCW";
  6393. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6394. var Angle = /** @class */ (function () {
  6395. /**
  6396. * Creates an Angle object of "radians" radians (float).
  6397. */
  6398. function Angle(radians) {
  6399. var _this = this;
  6400. /**
  6401. * Returns the Angle value in degrees (float).
  6402. */
  6403. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6404. /**
  6405. * Returns the Angle value in radians (float).
  6406. */
  6407. this.radians = function () { return _this._radians; };
  6408. this._radians = radians;
  6409. if (this._radians < 0.0)
  6410. this._radians += (2.0 * Math.PI);
  6411. }
  6412. /**
  6413. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6414. */
  6415. Angle.BetweenTwoPoints = function (a, b) {
  6416. var delta = b.subtract(a);
  6417. var theta = Math.atan2(delta.y, delta.x);
  6418. return new Angle(theta);
  6419. };
  6420. /**
  6421. * Returns a new Angle object from the passed float in radians.
  6422. */
  6423. Angle.FromRadians = function (radians) {
  6424. return new Angle(radians);
  6425. };
  6426. /**
  6427. * Returns a new Angle object from the passed float in degrees.
  6428. */
  6429. Angle.FromDegrees = function (degrees) {
  6430. return new Angle(degrees * Math.PI / 180.0);
  6431. };
  6432. return Angle;
  6433. }());
  6434. BABYLON.Angle = Angle;
  6435. var Arc2 = /** @class */ (function () {
  6436. /**
  6437. * Creates an Arc object from the three passed points : start, middle and end.
  6438. */
  6439. function Arc2(startPoint, midPoint, endPoint) {
  6440. this.startPoint = startPoint;
  6441. this.midPoint = midPoint;
  6442. this.endPoint = endPoint;
  6443. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6444. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6445. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6446. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6447. 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);
  6448. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6449. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6450. var a1 = this.startAngle.degrees();
  6451. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6452. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6453. // angles correction
  6454. if (a2 - a1 > +180.0)
  6455. a2 -= 360.0;
  6456. if (a2 - a1 < -180.0)
  6457. a2 += 360.0;
  6458. if (a3 - a2 > +180.0)
  6459. a3 -= 360.0;
  6460. if (a3 - a2 < -180.0)
  6461. a3 += 360.0;
  6462. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6463. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6464. }
  6465. return Arc2;
  6466. }());
  6467. BABYLON.Arc2 = Arc2;
  6468. var Path2 = /** @class */ (function () {
  6469. /**
  6470. * Creates a Path2 object from the starting 2D coordinates x and y.
  6471. */
  6472. function Path2(x, y) {
  6473. this._points = new Array();
  6474. this._length = 0.0;
  6475. this.closed = false;
  6476. this._points.push(new Vector2(x, y));
  6477. }
  6478. /**
  6479. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6480. * Returns the updated Path2.
  6481. */
  6482. Path2.prototype.addLineTo = function (x, y) {
  6483. if (this.closed) {
  6484. return this;
  6485. }
  6486. var newPoint = new Vector2(x, y);
  6487. var previousPoint = this._points[this._points.length - 1];
  6488. this._points.push(newPoint);
  6489. this._length += newPoint.subtract(previousPoint).length();
  6490. return this;
  6491. };
  6492. /**
  6493. * 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.
  6494. * Returns the updated Path2.
  6495. */
  6496. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6497. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6498. if (this.closed) {
  6499. return this;
  6500. }
  6501. var startPoint = this._points[this._points.length - 1];
  6502. var midPoint = new Vector2(midX, midY);
  6503. var endPoint = new Vector2(endX, endY);
  6504. var arc = new Arc2(startPoint, midPoint, endPoint);
  6505. var increment = arc.angle.radians() / numberOfSegments;
  6506. if (arc.orientation === Orientation.CW)
  6507. increment *= -1;
  6508. var currentAngle = arc.startAngle.radians() + increment;
  6509. for (var i = 0; i < numberOfSegments; i++) {
  6510. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6511. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6512. this.addLineTo(x, y);
  6513. currentAngle += increment;
  6514. }
  6515. return this;
  6516. };
  6517. /**
  6518. * Closes the Path2.
  6519. * Returns the Path2.
  6520. */
  6521. Path2.prototype.close = function () {
  6522. this.closed = true;
  6523. return this;
  6524. };
  6525. /**
  6526. * Returns the Path2 total length (float).
  6527. */
  6528. Path2.prototype.length = function () {
  6529. var result = this._length;
  6530. if (!this.closed) {
  6531. var lastPoint = this._points[this._points.length - 1];
  6532. var firstPoint = this._points[0];
  6533. result += (firstPoint.subtract(lastPoint).length());
  6534. }
  6535. return result;
  6536. };
  6537. /**
  6538. * Returns the Path2 internal array of points.
  6539. */
  6540. Path2.prototype.getPoints = function () {
  6541. return this._points;
  6542. };
  6543. /**
  6544. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6545. */
  6546. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6547. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6548. return Vector2.Zero();
  6549. }
  6550. var lengthPosition = normalizedLengthPosition * this.length();
  6551. var previousOffset = 0;
  6552. for (var i = 0; i < this._points.length; i++) {
  6553. var j = (i + 1) % this._points.length;
  6554. var a = this._points[i];
  6555. var b = this._points[j];
  6556. var bToA = b.subtract(a);
  6557. var nextOffset = (bToA.length() + previousOffset);
  6558. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6559. var dir = bToA.normalize();
  6560. var localOffset = lengthPosition - previousOffset;
  6561. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6562. }
  6563. previousOffset = nextOffset;
  6564. }
  6565. return Vector2.Zero();
  6566. };
  6567. /**
  6568. * Returns a new Path2 starting at the coordinates (x, y).
  6569. */
  6570. Path2.StartingAt = function (x, y) {
  6571. return new Path2(x, y);
  6572. };
  6573. return Path2;
  6574. }());
  6575. BABYLON.Path2 = Path2;
  6576. var Path3D = /** @class */ (function () {
  6577. /**
  6578. * new Path3D(path, normal, raw)
  6579. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6580. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6581. * path : an array of Vector3, the curve axis of the Path3D
  6582. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6583. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6584. */
  6585. function Path3D(path, firstNormal, raw) {
  6586. if (firstNormal === void 0) { firstNormal = null; }
  6587. this.path = path;
  6588. this._curve = new Array();
  6589. this._distances = new Array();
  6590. this._tangents = new Array();
  6591. this._normals = new Array();
  6592. this._binormals = new Array();
  6593. for (var p = 0; p < path.length; p++) {
  6594. this._curve[p] = path[p].clone(); // hard copy
  6595. }
  6596. this._raw = raw || false;
  6597. this._compute(firstNormal);
  6598. }
  6599. /**
  6600. * Returns the Path3D array of successive Vector3 designing its curve.
  6601. */
  6602. Path3D.prototype.getCurve = function () {
  6603. return this._curve;
  6604. };
  6605. /**
  6606. * Returns an array populated with tangent vectors on each Path3D curve point.
  6607. */
  6608. Path3D.prototype.getTangents = function () {
  6609. return this._tangents;
  6610. };
  6611. /**
  6612. * Returns an array populated with normal vectors on each Path3D curve point.
  6613. */
  6614. Path3D.prototype.getNormals = function () {
  6615. return this._normals;
  6616. };
  6617. /**
  6618. * Returns an array populated with binormal vectors on each Path3D curve point.
  6619. */
  6620. Path3D.prototype.getBinormals = function () {
  6621. return this._binormals;
  6622. };
  6623. /**
  6624. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6625. */
  6626. Path3D.prototype.getDistances = function () {
  6627. return this._distances;
  6628. };
  6629. /**
  6630. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6631. * Returns the same object updated.
  6632. */
  6633. Path3D.prototype.update = function (path, firstNormal) {
  6634. if (firstNormal === void 0) { firstNormal = null; }
  6635. for (var p = 0; p < path.length; p++) {
  6636. this._curve[p].x = path[p].x;
  6637. this._curve[p].y = path[p].y;
  6638. this._curve[p].z = path[p].z;
  6639. }
  6640. this._compute(firstNormal);
  6641. return this;
  6642. };
  6643. // private function compute() : computes tangents, normals and binormals
  6644. Path3D.prototype._compute = function (firstNormal) {
  6645. var l = this._curve.length;
  6646. // first and last tangents
  6647. this._tangents[0] = this._getFirstNonNullVector(0);
  6648. if (!this._raw) {
  6649. this._tangents[0].normalize();
  6650. }
  6651. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6652. if (!this._raw) {
  6653. this._tangents[l - 1].normalize();
  6654. }
  6655. // normals and binormals at first point : arbitrary vector with _normalVector()
  6656. var tg0 = this._tangents[0];
  6657. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6658. this._normals[0] = pp0;
  6659. if (!this._raw) {
  6660. this._normals[0].normalize();
  6661. }
  6662. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6663. if (!this._raw) {
  6664. this._binormals[0].normalize();
  6665. }
  6666. this._distances[0] = 0.0;
  6667. // normals and binormals : next points
  6668. var prev; // previous vector (segment)
  6669. var cur; // current vector (segment)
  6670. var curTang; // current tangent
  6671. // previous normal
  6672. var prevBinor; // previous binormal
  6673. for (var i = 1; i < l; i++) {
  6674. // tangents
  6675. prev = this._getLastNonNullVector(i);
  6676. if (i < l - 1) {
  6677. cur = this._getFirstNonNullVector(i);
  6678. this._tangents[i] = prev.add(cur);
  6679. this._tangents[i].normalize();
  6680. }
  6681. this._distances[i] = this._distances[i - 1] + prev.length();
  6682. // normals and binormals
  6683. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6684. curTang = this._tangents[i];
  6685. prevBinor = this._binormals[i - 1];
  6686. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6687. if (!this._raw) {
  6688. this._normals[i].normalize();
  6689. }
  6690. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6691. if (!this._raw) {
  6692. this._binormals[i].normalize();
  6693. }
  6694. }
  6695. };
  6696. // private function getFirstNonNullVector(index)
  6697. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6698. Path3D.prototype._getFirstNonNullVector = function (index) {
  6699. var i = 1;
  6700. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6701. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6702. i++;
  6703. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6704. }
  6705. return nNVector;
  6706. };
  6707. // private function getLastNonNullVector(index)
  6708. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6709. Path3D.prototype._getLastNonNullVector = function (index) {
  6710. var i = 1;
  6711. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6712. while (nLVector.length() === 0 && index > i + 1) {
  6713. i++;
  6714. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6715. }
  6716. return nLVector;
  6717. };
  6718. // private function normalVector(v0, vt, va) :
  6719. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6720. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6721. Path3D.prototype._normalVector = function (v0, vt, va) {
  6722. var normal0;
  6723. var tgl = vt.length();
  6724. if (tgl === 0.0) {
  6725. tgl = 1.0;
  6726. }
  6727. if (va === undefined || va === null) {
  6728. var point;
  6729. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6730. point = new Vector3(0.0, -1.0, 0.0);
  6731. }
  6732. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6733. point = new Vector3(1.0, 0.0, 0.0);
  6734. }
  6735. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6736. point = new Vector3(0.0, 0.0, 1.0);
  6737. }
  6738. else {
  6739. point = Vector3.Zero();
  6740. }
  6741. normal0 = Vector3.Cross(vt, point);
  6742. }
  6743. else {
  6744. normal0 = Vector3.Cross(vt, va);
  6745. Vector3.CrossToRef(normal0, vt, normal0);
  6746. }
  6747. normal0.normalize();
  6748. return normal0;
  6749. };
  6750. return Path3D;
  6751. }());
  6752. BABYLON.Path3D = Path3D;
  6753. var Curve3 = /** @class */ (function () {
  6754. /**
  6755. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6756. * A Curve3 is designed from a series of successive Vector3.
  6757. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6758. */
  6759. function Curve3(points) {
  6760. this._length = 0.0;
  6761. this._points = points;
  6762. this._length = this._computeLength(points);
  6763. }
  6764. /**
  6765. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6766. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6767. * @param v1 (Vector3) the control point
  6768. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6769. * @param nbPoints (integer) the wanted number of points in the curve
  6770. */
  6771. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6772. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6773. var bez = new Array();
  6774. var equation = function (t, val0, val1, val2) {
  6775. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6776. return res;
  6777. };
  6778. for (var i = 0; i <= nbPoints; i++) {
  6779. 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)));
  6780. }
  6781. return new Curve3(bez);
  6782. };
  6783. /**
  6784. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6785. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6786. * @param v1 (Vector3) the first control point
  6787. * @param v2 (Vector3) the second control point
  6788. * @param v3 (Vector3) the end point of the Cubic Bezier
  6789. * @param nbPoints (integer) the wanted number of points in the curve
  6790. */
  6791. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6792. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6793. var bez = new Array();
  6794. var equation = function (t, val0, val1, val2, val3) {
  6795. 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;
  6796. return res;
  6797. };
  6798. for (var i = 0; i <= nbPoints; i++) {
  6799. 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)));
  6800. }
  6801. return new Curve3(bez);
  6802. };
  6803. /**
  6804. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6805. * @param p1 (Vector3) the origin point of the Hermite Spline
  6806. * @param t1 (Vector3) the tangent vector at the origin point
  6807. * @param p2 (Vector3) the end point of the Hermite Spline
  6808. * @param t2 (Vector3) the tangent vector at the end point
  6809. * @param nbPoints (integer) the wanted number of points in the curve
  6810. */
  6811. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6812. var hermite = new Array();
  6813. var step = 1.0 / nbPoints;
  6814. for (var i = 0; i <= nbPoints; i++) {
  6815. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6816. }
  6817. return new Curve3(hermite);
  6818. };
  6819. /**
  6820. * Returns a Curve3 object along a CatmullRom Spline curve :
  6821. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6822. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6823. */
  6824. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6825. var totalPoints = new Array();
  6826. totalPoints.push(points[0].clone());
  6827. Array.prototype.push.apply(totalPoints, points);
  6828. totalPoints.push(points[points.length - 1].clone());
  6829. var catmullRom = new Array();
  6830. var step = 1.0 / nbPoints;
  6831. var amount = 0.0;
  6832. for (var i = 0; i < totalPoints.length - 3; i++) {
  6833. amount = 0;
  6834. for (var c = 0; c < nbPoints; c++) {
  6835. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6836. amount += step;
  6837. }
  6838. }
  6839. i--;
  6840. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6841. return new Curve3(catmullRom);
  6842. };
  6843. /**
  6844. * Returns the Curve3 stored array of successive Vector3
  6845. */
  6846. Curve3.prototype.getPoints = function () {
  6847. return this._points;
  6848. };
  6849. /**
  6850. * Returns the computed length (float) of the curve.
  6851. */
  6852. Curve3.prototype.length = function () {
  6853. return this._length;
  6854. };
  6855. /**
  6856. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6857. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6858. * curveA and curveB keep unchanged.
  6859. */
  6860. Curve3.prototype.continue = function (curve) {
  6861. var lastPoint = this._points[this._points.length - 1];
  6862. var continuedPoints = this._points.slice();
  6863. var curvePoints = curve.getPoints();
  6864. for (var i = 1; i < curvePoints.length; i++) {
  6865. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6866. }
  6867. var continuedCurve = new Curve3(continuedPoints);
  6868. return continuedCurve;
  6869. };
  6870. Curve3.prototype._computeLength = function (path) {
  6871. var l = 0;
  6872. for (var i = 1; i < path.length; i++) {
  6873. l += (path[i].subtract(path[i - 1])).length();
  6874. }
  6875. return l;
  6876. };
  6877. return Curve3;
  6878. }());
  6879. BABYLON.Curve3 = Curve3;
  6880. // Vertex formats
  6881. var PositionNormalVertex = /** @class */ (function () {
  6882. function PositionNormalVertex(position, normal) {
  6883. if (position === void 0) { position = Vector3.Zero(); }
  6884. if (normal === void 0) { normal = Vector3.Up(); }
  6885. this.position = position;
  6886. this.normal = normal;
  6887. }
  6888. PositionNormalVertex.prototype.clone = function () {
  6889. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6890. };
  6891. return PositionNormalVertex;
  6892. }());
  6893. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6894. var PositionNormalTextureVertex = /** @class */ (function () {
  6895. function PositionNormalTextureVertex(position, normal, uv) {
  6896. if (position === void 0) { position = Vector3.Zero(); }
  6897. if (normal === void 0) { normal = Vector3.Up(); }
  6898. if (uv === void 0) { uv = Vector2.Zero(); }
  6899. this.position = position;
  6900. this.normal = normal;
  6901. this.uv = uv;
  6902. }
  6903. PositionNormalTextureVertex.prototype.clone = function () {
  6904. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6905. };
  6906. return PositionNormalTextureVertex;
  6907. }());
  6908. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6909. // Temporary pre-allocated objects for engine internal use
  6910. // usage in any internal function :
  6911. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6912. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6913. var Tmp = /** @class */ (function () {
  6914. function Tmp() {
  6915. }
  6916. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6917. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6918. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6919. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6920. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6921. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6922. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6923. Matrix.Zero(), Matrix.Zero(),
  6924. Matrix.Zero(), Matrix.Zero(),
  6925. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6926. return Tmp;
  6927. }());
  6928. BABYLON.Tmp = Tmp;
  6929. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6930. var MathTmp = /** @class */ (function () {
  6931. function MathTmp() {
  6932. }
  6933. MathTmp.Vector3 = [Vector3.Zero()];
  6934. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6935. MathTmp.Quaternion = [Quaternion.Zero()];
  6936. return MathTmp;
  6937. }());
  6938. })(BABYLON || (BABYLON = {}));
  6939. //# sourceMappingURL=babylon.math.js.map
  6940. var BABYLON;
  6941. (function (BABYLON) {
  6942. var Scalar = /** @class */ (function () {
  6943. function Scalar() {
  6944. }
  6945. /**
  6946. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6947. */
  6948. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6949. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6950. var num = a - b;
  6951. return -epsilon <= num && num <= epsilon;
  6952. };
  6953. /**
  6954. * Returns a string : the upper case translation of the number i to hexadecimal.
  6955. */
  6956. Scalar.ToHex = function (i) {
  6957. var str = i.toString(16);
  6958. if (i <= 15) {
  6959. return ("0" + str).toUpperCase();
  6960. }
  6961. return str.toUpperCase();
  6962. };
  6963. /**
  6964. * Returns -1 if value is negative and +1 is value is positive.
  6965. * Returns the value itself if it's equal to zero.
  6966. */
  6967. Scalar.Sign = function (value) {
  6968. value = +value; // convert to a number
  6969. if (value === 0 || isNaN(value))
  6970. return value;
  6971. return value > 0 ? 1 : -1;
  6972. };
  6973. /**
  6974. * Returns the value itself if it's between min and max.
  6975. * Returns min if the value is lower than min.
  6976. * Returns max if the value is greater than max.
  6977. */
  6978. Scalar.Clamp = function (value, min, max) {
  6979. if (min === void 0) { min = 0; }
  6980. if (max === void 0) { max = 1; }
  6981. return Math.min(max, Math.max(min, value));
  6982. };
  6983. /**
  6984. * Returns the log2 of value.
  6985. */
  6986. Scalar.Log2 = function (value) {
  6987. return Math.log(value) * Math.LOG2E;
  6988. };
  6989. /**
  6990. * Loops the value, so that it is never larger than length and never smaller than 0.
  6991. *
  6992. * This is similar to the modulo operator but it works with floating point numbers.
  6993. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6994. * With t = 5 and length = 2.5, the result would be 0.0.
  6995. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6996. */
  6997. Scalar.Repeat = function (value, length) {
  6998. return value - Math.floor(value / length) * length;
  6999. };
  7000. /**
  7001. * Normalize the value between 0.0 and 1.0 using min and max values
  7002. */
  7003. Scalar.Normalize = function (value, min, max) {
  7004. return (value - min) / (max - min);
  7005. };
  7006. /**
  7007. * Denormalize the value from 0.0 and 1.0 using min and max values
  7008. */
  7009. Scalar.Denormalize = function (normalized, min, max) {
  7010. return (normalized * (max - min) + min);
  7011. };
  7012. /**
  7013. * Calculates the shortest difference between two given angles given in degrees.
  7014. */
  7015. Scalar.DeltaAngle = function (current, target) {
  7016. var num = Scalar.Repeat(target - current, 360.0);
  7017. if (num > 180.0) {
  7018. num -= 360.0;
  7019. }
  7020. return num;
  7021. };
  7022. /**
  7023. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7024. *
  7025. * The returned value will move back and forth between 0 and length
  7026. */
  7027. Scalar.PingPong = function (tx, length) {
  7028. var t = Scalar.Repeat(tx, length * 2.0);
  7029. return length - Math.abs(t - length);
  7030. };
  7031. /**
  7032. * Interpolates between min and max with smoothing at the limits.
  7033. *
  7034. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7035. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7036. */
  7037. Scalar.SmoothStep = function (from, to, tx) {
  7038. var t = Scalar.Clamp(tx);
  7039. t = -2.0 * t * t * t + 3.0 * t * t;
  7040. return to * t + from * (1.0 - t);
  7041. };
  7042. /**
  7043. * Moves a value current towards target.
  7044. *
  7045. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7046. * Negative values of maxDelta pushes the value away from target.
  7047. */
  7048. Scalar.MoveTowards = function (current, target, maxDelta) {
  7049. var result = 0;
  7050. if (Math.abs(target - current) <= maxDelta) {
  7051. result = target;
  7052. }
  7053. else {
  7054. result = current + Scalar.Sign(target - current) * maxDelta;
  7055. }
  7056. return result;
  7057. };
  7058. /**
  7059. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7060. *
  7061. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7062. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7063. */
  7064. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7065. var num = Scalar.DeltaAngle(current, target);
  7066. var result = 0;
  7067. if (-maxDelta < num && num < maxDelta) {
  7068. result = target;
  7069. }
  7070. else {
  7071. target = current + num;
  7072. result = Scalar.MoveTowards(current, target, maxDelta);
  7073. }
  7074. return result;
  7075. };
  7076. /**
  7077. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7078. */
  7079. Scalar.Lerp = function (start, end, amount) {
  7080. return start + ((end - start) * amount);
  7081. };
  7082. /**
  7083. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7084. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7085. */
  7086. Scalar.LerpAngle = function (start, end, amount) {
  7087. var num = Scalar.Repeat(end - start, 360.0);
  7088. if (num > 180.0) {
  7089. num -= 360.0;
  7090. }
  7091. return start + num * Scalar.Clamp(amount);
  7092. };
  7093. /**
  7094. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7095. */
  7096. Scalar.InverseLerp = function (a, b, value) {
  7097. var result = 0;
  7098. if (a != b) {
  7099. result = Scalar.Clamp((value - a) / (b - a));
  7100. }
  7101. else {
  7102. result = 0.0;
  7103. }
  7104. return result;
  7105. };
  7106. /**
  7107. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7108. */
  7109. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7110. var squared = amount * amount;
  7111. var cubed = amount * squared;
  7112. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7113. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7114. var part3 = (cubed - (2.0 * squared)) + amount;
  7115. var part4 = cubed - squared;
  7116. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7117. };
  7118. /**
  7119. * Returns a random float number between and min and max values
  7120. */
  7121. Scalar.RandomRange = function (min, max) {
  7122. if (min === max)
  7123. return min;
  7124. return ((Math.random() * (max - min)) + min);
  7125. };
  7126. /**
  7127. * This function returns percentage of a number in a given range.
  7128. *
  7129. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7130. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7131. */
  7132. Scalar.RangeToPercent = function (number, min, max) {
  7133. return ((number - min) / (max - min));
  7134. };
  7135. /**
  7136. * This function returns number that corresponds to the percentage in a given range.
  7137. *
  7138. * PercentToRange(0.34,0,100) will return 34.
  7139. */
  7140. Scalar.PercentToRange = function (percent, min, max) {
  7141. return ((max - min) * percent + min);
  7142. };
  7143. /**
  7144. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7145. * @param angle The angle to normalize in radian.
  7146. * @return The converted angle.
  7147. */
  7148. Scalar.NormalizeRadians = function (angle) {
  7149. // More precise but slower version kept for reference.
  7150. // angle = angle % Tools.TwoPi;
  7151. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7152. //if (angle > Math.PI) {
  7153. // angle -= Tools.TwoPi;
  7154. //}
  7155. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7156. return angle;
  7157. };
  7158. /**
  7159. * Two pi constants convenient for computation.
  7160. */
  7161. Scalar.TwoPi = Math.PI * 2;
  7162. return Scalar;
  7163. }());
  7164. BABYLON.Scalar = Scalar;
  7165. })(BABYLON || (BABYLON = {}));
  7166. //# sourceMappingURL=babylon.math.scalar.js.map
  7167. //# sourceMappingURL=babylon.mixins.js.map
  7168. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7169. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7170. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7171. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7172. //# sourceMappingURL=babylon.webgl2.js.map
  7173. var BABYLON;
  7174. (function (BABYLON) {
  7175. var __decoratorInitialStore = {};
  7176. var __mergedStore = {};
  7177. var _copySource = function (creationFunction, source, instanciate) {
  7178. var destination = creationFunction();
  7179. // Tags
  7180. if (BABYLON.Tags) {
  7181. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7182. }
  7183. var classStore = getMergedStore(destination);
  7184. // Properties
  7185. for (var property in classStore) {
  7186. var propertyDescriptor = classStore[property];
  7187. var sourceProperty = source[property];
  7188. var propertyType = propertyDescriptor.type;
  7189. if (sourceProperty !== undefined && sourceProperty !== null) {
  7190. switch (propertyType) {
  7191. case 0: // Value
  7192. case 6:// Mesh reference
  7193. destination[property] = sourceProperty;
  7194. break;
  7195. case 1:// Texture
  7196. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7197. break;
  7198. case 2: // Color3
  7199. case 3: // FresnelParameters
  7200. case 4: // Vector2
  7201. case 5: // Vector3
  7202. case 7: // Color Curves
  7203. case 10:// Quaternion
  7204. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7205. break;
  7206. }
  7207. }
  7208. }
  7209. return destination;
  7210. };
  7211. function getDirectStore(target) {
  7212. var classKey = target.getClassName();
  7213. if (!__decoratorInitialStore[classKey]) {
  7214. __decoratorInitialStore[classKey] = {};
  7215. }
  7216. return __decoratorInitialStore[classKey];
  7217. }
  7218. /**
  7219. * Return the list of properties flagged as serializable
  7220. * @param target: host object
  7221. */
  7222. function getMergedStore(target) {
  7223. var classKey = target.getClassName();
  7224. if (__mergedStore[classKey]) {
  7225. return __mergedStore[classKey];
  7226. }
  7227. __mergedStore[classKey] = {};
  7228. var store = __mergedStore[classKey];
  7229. var currentTarget = target;
  7230. var currentKey = classKey;
  7231. while (currentKey) {
  7232. var initialStore = __decoratorInitialStore[currentKey];
  7233. for (var property in initialStore) {
  7234. store[property] = initialStore[property];
  7235. }
  7236. var parent_1 = void 0;
  7237. var done = false;
  7238. do {
  7239. parent_1 = Object.getPrototypeOf(currentTarget);
  7240. if (!parent_1.getClassName) {
  7241. done = true;
  7242. break;
  7243. }
  7244. if (parent_1.getClassName() !== currentKey) {
  7245. break;
  7246. }
  7247. currentTarget = parent_1;
  7248. } while (parent_1);
  7249. if (done) {
  7250. break;
  7251. }
  7252. currentKey = parent_1.getClassName();
  7253. currentTarget = parent_1;
  7254. }
  7255. return store;
  7256. }
  7257. function generateSerializableMember(type, sourceName) {
  7258. return function (target, propertyKey) {
  7259. var classStore = getDirectStore(target);
  7260. if (!classStore[propertyKey]) {
  7261. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7262. }
  7263. };
  7264. }
  7265. function generateExpandMember(setCallback, targetKey) {
  7266. if (targetKey === void 0) { targetKey = null; }
  7267. return function (target, propertyKey) {
  7268. var key = targetKey || ("_" + propertyKey);
  7269. Object.defineProperty(target, propertyKey, {
  7270. get: function () {
  7271. return this[key];
  7272. },
  7273. set: function (value) {
  7274. if (this[key] === value) {
  7275. return;
  7276. }
  7277. this[key] = value;
  7278. target[setCallback].apply(this);
  7279. },
  7280. enumerable: true,
  7281. configurable: true
  7282. });
  7283. };
  7284. }
  7285. function expandToProperty(callback, targetKey) {
  7286. if (targetKey === void 0) { targetKey = null; }
  7287. return generateExpandMember(callback, targetKey);
  7288. }
  7289. BABYLON.expandToProperty = expandToProperty;
  7290. function serialize(sourceName) {
  7291. return generateSerializableMember(0, sourceName); // value member
  7292. }
  7293. BABYLON.serialize = serialize;
  7294. function serializeAsTexture(sourceName) {
  7295. return generateSerializableMember(1, sourceName); // texture member
  7296. }
  7297. BABYLON.serializeAsTexture = serializeAsTexture;
  7298. function serializeAsColor3(sourceName) {
  7299. return generateSerializableMember(2, sourceName); // color3 member
  7300. }
  7301. BABYLON.serializeAsColor3 = serializeAsColor3;
  7302. function serializeAsFresnelParameters(sourceName) {
  7303. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7304. }
  7305. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7306. function serializeAsVector2(sourceName) {
  7307. return generateSerializableMember(4, sourceName); // vector2 member
  7308. }
  7309. BABYLON.serializeAsVector2 = serializeAsVector2;
  7310. function serializeAsVector3(sourceName) {
  7311. return generateSerializableMember(5, sourceName); // vector3 member
  7312. }
  7313. BABYLON.serializeAsVector3 = serializeAsVector3;
  7314. function serializeAsMeshReference(sourceName) {
  7315. return generateSerializableMember(6, sourceName); // mesh reference member
  7316. }
  7317. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7318. function serializeAsColorCurves(sourceName) {
  7319. return generateSerializableMember(7, sourceName); // color curves
  7320. }
  7321. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7322. function serializeAsColor4(sourceName) {
  7323. return generateSerializableMember(8, sourceName); // color 4
  7324. }
  7325. BABYLON.serializeAsColor4 = serializeAsColor4;
  7326. function serializeAsImageProcessingConfiguration(sourceName) {
  7327. return generateSerializableMember(9, sourceName); // image processing
  7328. }
  7329. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7330. function serializeAsQuaternion(sourceName) {
  7331. return generateSerializableMember(10, sourceName); // quaternion member
  7332. }
  7333. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7334. var SerializationHelper = /** @class */ (function () {
  7335. function SerializationHelper() {
  7336. }
  7337. SerializationHelper.Serialize = function (entity, serializationObject) {
  7338. if (!serializationObject) {
  7339. serializationObject = {};
  7340. }
  7341. // Tags
  7342. if (BABYLON.Tags) {
  7343. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7344. }
  7345. var serializedProperties = getMergedStore(entity);
  7346. // Properties
  7347. for (var property in serializedProperties) {
  7348. var propertyDescriptor = serializedProperties[property];
  7349. var targetPropertyName = propertyDescriptor.sourceName || property;
  7350. var propertyType = propertyDescriptor.type;
  7351. var sourceProperty = entity[property];
  7352. if (sourceProperty !== undefined && sourceProperty !== null) {
  7353. switch (propertyType) {
  7354. case 0:// Value
  7355. serializationObject[targetPropertyName] = sourceProperty;
  7356. break;
  7357. case 1:// Texture
  7358. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7359. break;
  7360. case 2:// Color3
  7361. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7362. break;
  7363. case 3:// FresnelParameters
  7364. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7365. break;
  7366. case 4:// Vector2
  7367. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7368. break;
  7369. case 5:// Vector3
  7370. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7371. break;
  7372. case 6:// Mesh reference
  7373. serializationObject[targetPropertyName] = sourceProperty.id;
  7374. break;
  7375. case 7:// Color Curves
  7376. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7377. break;
  7378. case 8:// Color 4
  7379. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7380. break;
  7381. case 9:// Image Processing
  7382. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7383. break;
  7384. }
  7385. }
  7386. }
  7387. return serializationObject;
  7388. };
  7389. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7390. if (rootUrl === void 0) { rootUrl = null; }
  7391. var destination = creationFunction();
  7392. if (!rootUrl) {
  7393. rootUrl = "";
  7394. }
  7395. // Tags
  7396. if (BABYLON.Tags) {
  7397. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7398. }
  7399. var classStore = getMergedStore(destination);
  7400. // Properties
  7401. for (var property in classStore) {
  7402. var propertyDescriptor = classStore[property];
  7403. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7404. var propertyType = propertyDescriptor.type;
  7405. if (sourceProperty !== undefined && sourceProperty !== null) {
  7406. var dest = destination;
  7407. switch (propertyType) {
  7408. case 0:// Value
  7409. dest[property] = sourceProperty;
  7410. break;
  7411. case 1:// Texture
  7412. if (scene) {
  7413. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7414. }
  7415. break;
  7416. case 2:// Color3
  7417. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7418. break;
  7419. case 3:// FresnelParameters
  7420. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7421. break;
  7422. case 4:// Vector2
  7423. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7424. break;
  7425. case 5:// Vector3
  7426. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7427. break;
  7428. case 6:// Mesh reference
  7429. if (scene) {
  7430. dest[property] = scene.getLastMeshByID(sourceProperty);
  7431. }
  7432. break;
  7433. case 7:// Color Curves
  7434. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7435. break;
  7436. case 8:// Color 4
  7437. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7438. break;
  7439. case 9:// Image Processing
  7440. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7441. break;
  7442. }
  7443. }
  7444. }
  7445. return destination;
  7446. };
  7447. SerializationHelper.Clone = function (creationFunction, source) {
  7448. return _copySource(creationFunction, source, false);
  7449. };
  7450. SerializationHelper.Instanciate = function (creationFunction, source) {
  7451. return _copySource(creationFunction, source, true);
  7452. };
  7453. return SerializationHelper;
  7454. }());
  7455. BABYLON.SerializationHelper = SerializationHelper;
  7456. })(BABYLON || (BABYLON = {}));
  7457. //# sourceMappingURL=babylon.decorators.js.map
  7458. var BABYLON;
  7459. (function (BABYLON) {
  7460. /**
  7461. * Wrapper class for promise with external resolve and reject.
  7462. */
  7463. var Deferred = /** @class */ (function () {
  7464. /**
  7465. * Constructor for this deferred object.
  7466. */
  7467. function Deferred() {
  7468. var _this = this;
  7469. this.promise = new Promise(function (resolve, reject) {
  7470. _this._resolve = resolve;
  7471. _this._reject = reject;
  7472. });
  7473. }
  7474. Object.defineProperty(Deferred.prototype, "resolve", {
  7475. /**
  7476. * The resolve method of the promise associated with this deferred object.
  7477. */
  7478. get: function () {
  7479. return this._resolve;
  7480. },
  7481. enumerable: true,
  7482. configurable: true
  7483. });
  7484. Object.defineProperty(Deferred.prototype, "reject", {
  7485. /**
  7486. * The reject method of the promise associated with this deferred object.
  7487. */
  7488. get: function () {
  7489. return this._reject;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. return Deferred;
  7495. }());
  7496. BABYLON.Deferred = Deferred;
  7497. })(BABYLON || (BABYLON = {}));
  7498. //# sourceMappingURL=babylon.deferred.js.map
  7499. var BABYLON;
  7500. (function (BABYLON) {
  7501. /**
  7502. * A class serves as a medium between the observable and its observers
  7503. */
  7504. var EventState = /** @class */ (function () {
  7505. /**
  7506. * Create a new EventState
  7507. * @param mask defines the mask associated with this state
  7508. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7509. * @param target defines the original target of the state
  7510. * @param currentTarget defines the current target of the state
  7511. */
  7512. function EventState(mask, skipNextObservers, target, currentTarget) {
  7513. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7514. this.initalize(mask, skipNextObservers, target, currentTarget);
  7515. }
  7516. /**
  7517. * Initialize the current event state
  7518. * @param mask defines the mask associated with this state
  7519. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7520. * @param target defines the original target of the state
  7521. * @param currentTarget defines the current target of the state
  7522. * @returns the current event state
  7523. */
  7524. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7525. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7526. this.mask = mask;
  7527. this.skipNextObservers = skipNextObservers;
  7528. this.target = target;
  7529. this.currentTarget = currentTarget;
  7530. return this;
  7531. };
  7532. return EventState;
  7533. }());
  7534. BABYLON.EventState = EventState;
  7535. /**
  7536. * Represent an Observer registered to a given Observable object.
  7537. */
  7538. var Observer = /** @class */ (function () {
  7539. /**
  7540. * Creates a new observer
  7541. * @param callback defines the callback to call when the observer is notified
  7542. * @param mask defines the mask of the observer (used to filter notifications)
  7543. * @param scope defines the current scope used to restore the JS context
  7544. */
  7545. function Observer(
  7546. /**
  7547. * Defines the callback to call when the observer is notified
  7548. */
  7549. callback,
  7550. /**
  7551. * Defines the mask of the observer (used to filter notifications)
  7552. */
  7553. mask,
  7554. /**
  7555. * Defines the current scope used to restore the JS context
  7556. */
  7557. scope) {
  7558. if (scope === void 0) { scope = null; }
  7559. this.callback = callback;
  7560. this.mask = mask;
  7561. this.scope = scope;
  7562. /** @ignore */
  7563. this._willBeUnregistered = false;
  7564. /**
  7565. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7566. */
  7567. this.unregisterOnNextCall = false;
  7568. }
  7569. return Observer;
  7570. }());
  7571. BABYLON.Observer = Observer;
  7572. /**
  7573. * Represent a list of observers registered to multiple Observables object.
  7574. */
  7575. var MultiObserver = /** @class */ (function () {
  7576. function MultiObserver() {
  7577. }
  7578. /**
  7579. * Release associated resources
  7580. */
  7581. MultiObserver.prototype.dispose = function () {
  7582. if (this._observers && this._observables) {
  7583. for (var index = 0; index < this._observers.length; index++) {
  7584. this._observables[index].remove(this._observers[index]);
  7585. }
  7586. }
  7587. this._observers = null;
  7588. this._observables = null;
  7589. };
  7590. /**
  7591. * Raise a callback when one of the observable will notify
  7592. * @param observables defines a list of observables to watch
  7593. * @param callback defines the callback to call on notification
  7594. * @param mask defines the mask used to filter notifications
  7595. * @param scope defines the current scope used to restore the JS context
  7596. * @returns the new MultiObserver
  7597. */
  7598. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7599. if (mask === void 0) { mask = -1; }
  7600. if (scope === void 0) { scope = null; }
  7601. var result = new MultiObserver();
  7602. result._observers = new Array();
  7603. result._observables = observables;
  7604. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7605. var observable = observables_1[_i];
  7606. var observer = observable.add(callback, mask, false, scope);
  7607. if (observer) {
  7608. result._observers.push(observer);
  7609. }
  7610. }
  7611. return result;
  7612. };
  7613. return MultiObserver;
  7614. }());
  7615. BABYLON.MultiObserver = MultiObserver;
  7616. /**
  7617. * The Observable class is a simple implementation of the Observable pattern.
  7618. * 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.
  7619. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7620. * 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).
  7621. * 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.
  7622. */
  7623. var Observable = /** @class */ (function () {
  7624. /**
  7625. * Creates a new observable
  7626. * @param onObserverAdded defines a callback to call when a new observer is added
  7627. */
  7628. function Observable(onObserverAdded) {
  7629. this._observers = new Array();
  7630. this._eventState = new EventState(0);
  7631. if (onObserverAdded) {
  7632. this._onObserverAdded = onObserverAdded;
  7633. }
  7634. }
  7635. /**
  7636. * Create a new Observer with the specified callback
  7637. * @param callback the callback that will be executed for that Observer
  7638. * @param mask the mask used to filter observers
  7639. * @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.
  7640. * @param scope optional scope for the callback to be called from
  7641. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7642. * @returns the new observer created for the callback
  7643. */
  7644. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7645. if (mask === void 0) { mask = -1; }
  7646. if (insertFirst === void 0) { insertFirst = false; }
  7647. if (scope === void 0) { scope = null; }
  7648. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7649. if (!callback) {
  7650. return null;
  7651. }
  7652. var observer = new Observer(callback, mask, scope);
  7653. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7654. if (insertFirst) {
  7655. this._observers.unshift(observer);
  7656. }
  7657. else {
  7658. this._observers.push(observer);
  7659. }
  7660. if (this._onObserverAdded) {
  7661. this._onObserverAdded(observer);
  7662. }
  7663. return observer;
  7664. };
  7665. /**
  7666. * Remove an Observer from the Observable object
  7667. * @param observer the instance of the Observer to remove
  7668. * @returns false if it doesn't belong to this Observable
  7669. */
  7670. Observable.prototype.remove = function (observer) {
  7671. if (!observer) {
  7672. return false;
  7673. }
  7674. var index = this._observers.indexOf(observer);
  7675. if (index !== -1) {
  7676. this._observers.splice(index, 1);
  7677. return true;
  7678. }
  7679. return false;
  7680. };
  7681. /**
  7682. * Remove a callback from the Observable object
  7683. * @param callback the callback to remove
  7684. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7685. * @returns false if it doesn't belong to this Observable
  7686. */
  7687. Observable.prototype.removeCallback = function (callback, scope) {
  7688. for (var index = 0; index < this._observers.length; index++) {
  7689. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7690. this._observers.splice(index, 1);
  7691. return true;
  7692. }
  7693. }
  7694. return false;
  7695. };
  7696. Observable.prototype._deferUnregister = function (observer) {
  7697. var _this = this;
  7698. observer.unregisterOnNextCall = false;
  7699. observer._willBeUnregistered = true;
  7700. BABYLON.Tools.SetImmediate(function () {
  7701. _this.remove(observer);
  7702. });
  7703. };
  7704. /**
  7705. * Notify all Observers by calling their respective callback with the given data
  7706. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7707. * @param eventData defines the data to send to all observers
  7708. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7709. * @param target defines the original target of the state
  7710. * @param currentTarget defines the current target of the state
  7711. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7712. */
  7713. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7714. if (mask === void 0) { mask = -1; }
  7715. if (!this._observers.length) {
  7716. return true;
  7717. }
  7718. var state = this._eventState;
  7719. state.mask = mask;
  7720. state.target = target;
  7721. state.currentTarget = currentTarget;
  7722. state.skipNextObservers = false;
  7723. state.lastReturnValue = eventData;
  7724. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7725. var obs = _a[_i];
  7726. if (obs._willBeUnregistered) {
  7727. continue;
  7728. }
  7729. if (obs.mask & mask) {
  7730. if (obs.scope) {
  7731. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7732. }
  7733. else {
  7734. state.lastReturnValue = obs.callback(eventData, state);
  7735. }
  7736. if (obs.unregisterOnNextCall) {
  7737. this._deferUnregister(obs);
  7738. }
  7739. }
  7740. if (state.skipNextObservers) {
  7741. return false;
  7742. }
  7743. }
  7744. return true;
  7745. };
  7746. /**
  7747. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7748. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7749. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7750. * and it is crucial that all callbacks will be executed.
  7751. * The order of the callbacks is kept, callbacks are not executed parallel.
  7752. *
  7753. * @param eventData The data to be sent to each callback
  7754. * @param mask is used to filter observers defaults to -1
  7755. * @param target defines the callback target (see EventState)
  7756. * @param currentTarget defines he current object in the bubbling phase
  7757. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7758. */
  7759. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7760. var _this = this;
  7761. if (mask === void 0) { mask = -1; }
  7762. // create an empty promise
  7763. var p = Promise.resolve(eventData);
  7764. // no observers? return this promise.
  7765. if (!this._observers.length) {
  7766. return p;
  7767. }
  7768. var state = this._eventState;
  7769. state.mask = mask;
  7770. state.target = target;
  7771. state.currentTarget = currentTarget;
  7772. state.skipNextObservers = false;
  7773. // execute one callback after another (not using Promise.all, the order is important)
  7774. this._observers.forEach(function (obs) {
  7775. if (state.skipNextObservers) {
  7776. return;
  7777. }
  7778. if (obs._willBeUnregistered) {
  7779. return;
  7780. }
  7781. if (obs.mask & mask) {
  7782. if (obs.scope) {
  7783. p = p.then(function (lastReturnedValue) {
  7784. state.lastReturnValue = lastReturnedValue;
  7785. return obs.callback.apply(obs.scope, [eventData, state]);
  7786. });
  7787. }
  7788. else {
  7789. p = p.then(function (lastReturnedValue) {
  7790. state.lastReturnValue = lastReturnedValue;
  7791. return obs.callback(eventData, state);
  7792. });
  7793. }
  7794. if (obs.unregisterOnNextCall) {
  7795. _this._deferUnregister(obs);
  7796. }
  7797. }
  7798. });
  7799. // return the eventData
  7800. return p.then(function () { return eventData; });
  7801. };
  7802. /**
  7803. * Notify a specific observer
  7804. * @param observer defines the observer to notify
  7805. * @param eventData defines the data to be sent to each callback
  7806. * @param mask is used to filter observers defaults to -1
  7807. */
  7808. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7809. if (mask === void 0) { mask = -1; }
  7810. var state = this._eventState;
  7811. state.mask = mask;
  7812. state.skipNextObservers = false;
  7813. observer.callback(eventData, state);
  7814. };
  7815. /**
  7816. * Gets a boolean indicating if the observable has at least one observer
  7817. * @returns true is the Observable has at least one Observer registered
  7818. */
  7819. Observable.prototype.hasObservers = function () {
  7820. return this._observers.length > 0;
  7821. };
  7822. /**
  7823. * Clear the list of observers
  7824. */
  7825. Observable.prototype.clear = function () {
  7826. this._observers = new Array();
  7827. this._onObserverAdded = null;
  7828. };
  7829. /**
  7830. * Clone the current observable
  7831. * @returns a new observable
  7832. */
  7833. Observable.prototype.clone = function () {
  7834. var result = new Observable();
  7835. result._observers = this._observers.slice(0);
  7836. return result;
  7837. };
  7838. /**
  7839. * Does this observable handles observer registered with a given mask
  7840. * @param mask defines the mask to be tested
  7841. * @return whether or not one observer registered with the given mask is handeled
  7842. **/
  7843. Observable.prototype.hasSpecificMask = function (mask) {
  7844. if (mask === void 0) { mask = -1; }
  7845. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7846. var obs = _a[_i];
  7847. if (obs.mask & mask || obs.mask === mask) {
  7848. return true;
  7849. }
  7850. }
  7851. return false;
  7852. };
  7853. return Observable;
  7854. }());
  7855. BABYLON.Observable = Observable;
  7856. })(BABYLON || (BABYLON = {}));
  7857. //# sourceMappingURL=babylon.observable.js.map
  7858. var BABYLON;
  7859. (function (BABYLON) {
  7860. var SmartArray = /** @class */ (function () {
  7861. function SmartArray(capacity) {
  7862. this.length = 0;
  7863. this.data = new Array(capacity);
  7864. this._id = SmartArray._GlobalId++;
  7865. }
  7866. SmartArray.prototype.push = function (value) {
  7867. this.data[this.length++] = value;
  7868. if (this.length > this.data.length) {
  7869. this.data.length *= 2;
  7870. }
  7871. };
  7872. SmartArray.prototype.forEach = function (func) {
  7873. for (var index = 0; index < this.length; index++) {
  7874. func(this.data[index]);
  7875. }
  7876. };
  7877. SmartArray.prototype.sort = function (compareFn) {
  7878. this.data.sort(compareFn);
  7879. };
  7880. SmartArray.prototype.reset = function () {
  7881. this.length = 0;
  7882. };
  7883. SmartArray.prototype.dispose = function () {
  7884. this.reset();
  7885. if (this.data) {
  7886. this.data.length = 0;
  7887. this.data = [];
  7888. }
  7889. };
  7890. SmartArray.prototype.concat = function (array) {
  7891. if (array.length === 0) {
  7892. return;
  7893. }
  7894. if (this.length + array.length > this.data.length) {
  7895. this.data.length = (this.length + array.length) * 2;
  7896. }
  7897. for (var index = 0; index < array.length; index++) {
  7898. this.data[this.length++] = (array.data || array)[index];
  7899. }
  7900. };
  7901. SmartArray.prototype.indexOf = function (value) {
  7902. var position = this.data.indexOf(value);
  7903. if (position >= this.length) {
  7904. return -1;
  7905. }
  7906. return position;
  7907. };
  7908. SmartArray.prototype.contains = function (value) {
  7909. return this.data.indexOf(value) !== -1;
  7910. };
  7911. // Statics
  7912. SmartArray._GlobalId = 0;
  7913. return SmartArray;
  7914. }());
  7915. BABYLON.SmartArray = SmartArray;
  7916. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7917. __extends(SmartArrayNoDuplicate, _super);
  7918. function SmartArrayNoDuplicate() {
  7919. var _this = _super !== null && _super.apply(this, arguments) || this;
  7920. _this._duplicateId = 0;
  7921. return _this;
  7922. }
  7923. SmartArrayNoDuplicate.prototype.push = function (value) {
  7924. _super.prototype.push.call(this, value);
  7925. if (!value.__smartArrayFlags) {
  7926. value.__smartArrayFlags = {};
  7927. }
  7928. value.__smartArrayFlags[this._id] = this._duplicateId;
  7929. };
  7930. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7931. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7932. return false;
  7933. }
  7934. this.push(value);
  7935. return true;
  7936. };
  7937. SmartArrayNoDuplicate.prototype.reset = function () {
  7938. _super.prototype.reset.call(this);
  7939. this._duplicateId++;
  7940. };
  7941. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7942. if (array.length === 0) {
  7943. return;
  7944. }
  7945. if (this.length + array.length > this.data.length) {
  7946. this.data.length = (this.length + array.length) * 2;
  7947. }
  7948. for (var index = 0; index < array.length; index++) {
  7949. var item = (array.data || array)[index];
  7950. this.pushNoDuplicate(item);
  7951. }
  7952. };
  7953. return SmartArrayNoDuplicate;
  7954. }(SmartArray));
  7955. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7956. })(BABYLON || (BABYLON = {}));
  7957. //# sourceMappingURL=babylon.smartArray.js.map
  7958. var BABYLON;
  7959. (function (BABYLON) {
  7960. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7961. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7962. var LoadFileError = /** @class */ (function (_super) {
  7963. __extends(LoadFileError, _super);
  7964. function LoadFileError(message, request) {
  7965. var _this = _super.call(this, message) || this;
  7966. _this.request = request;
  7967. _this.name = "LoadFileError";
  7968. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7969. return _this;
  7970. }
  7971. // Polyfill for Object.setPrototypeOf if necessary.
  7972. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7973. return LoadFileError;
  7974. }(Error));
  7975. BABYLON.LoadFileError = LoadFileError;
  7976. var RetryStrategy = /** @class */ (function () {
  7977. function RetryStrategy() {
  7978. }
  7979. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7980. if (maxRetries === void 0) { maxRetries = 3; }
  7981. if (baseInterval === void 0) { baseInterval = 500; }
  7982. return function (url, request, retryIndex) {
  7983. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7984. return -1;
  7985. }
  7986. return Math.pow(2, retryIndex) * baseInterval;
  7987. };
  7988. };
  7989. return RetryStrategy;
  7990. }());
  7991. BABYLON.RetryStrategy = RetryStrategy;
  7992. // Screenshots
  7993. var screenshotCanvas;
  7994. var cloneValue = function (source, destinationObject) {
  7995. if (!source)
  7996. return null;
  7997. if (source instanceof BABYLON.Mesh) {
  7998. return null;
  7999. }
  8000. if (source instanceof BABYLON.SubMesh) {
  8001. return source.clone(destinationObject);
  8002. }
  8003. else if (source.clone) {
  8004. return source.clone();
  8005. }
  8006. return null;
  8007. };
  8008. var Tools = /** @class */ (function () {
  8009. function Tools() {
  8010. }
  8011. /**
  8012. * Interpolates between a and b via alpha
  8013. * @param a The lower value (returned when alpha = 0)
  8014. * @param b The upper value (returned when alpha = 1)
  8015. * @param alpha The interpolation-factor
  8016. * @return The mixed value
  8017. */
  8018. Tools.Mix = function (a, b, alpha) {
  8019. return a * (1 - alpha) + b * alpha;
  8020. };
  8021. Tools.Instantiate = function (className) {
  8022. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8023. return Tools.RegisteredExternalClasses[className];
  8024. }
  8025. var arr = className.split(".");
  8026. var fn = (window || this);
  8027. for (var i = 0, len = arr.length; i < len; i++) {
  8028. fn = fn[arr[i]];
  8029. }
  8030. if (typeof fn !== "function") {
  8031. return null;
  8032. }
  8033. return fn;
  8034. };
  8035. /**
  8036. * Provides a slice function that will work even on IE
  8037. * @param data defines the array to slice
  8038. * @returns the new sliced array
  8039. */
  8040. Tools.Slice = function (data) {
  8041. if (data.slice) {
  8042. return data.slice();
  8043. }
  8044. return Array.prototype.slice.call(data);
  8045. };
  8046. Tools.SetImmediate = function (action) {
  8047. if (window.setImmediate) {
  8048. window.setImmediate(action);
  8049. }
  8050. else {
  8051. setTimeout(action, 1);
  8052. }
  8053. };
  8054. Tools.IsExponentOfTwo = function (value) {
  8055. var count = 1;
  8056. do {
  8057. count *= 2;
  8058. } while (count < value);
  8059. return count === value;
  8060. };
  8061. /**
  8062. * Find the next highest power of two.
  8063. * @param x Number to start search from.
  8064. * @return Next highest power of two.
  8065. */
  8066. Tools.CeilingPOT = function (x) {
  8067. x--;
  8068. x |= x >> 1;
  8069. x |= x >> 2;
  8070. x |= x >> 4;
  8071. x |= x >> 8;
  8072. x |= x >> 16;
  8073. x++;
  8074. return x;
  8075. };
  8076. /**
  8077. * Find the next lowest power of two.
  8078. * @param x Number to start search from.
  8079. * @return Next lowest power of two.
  8080. */
  8081. Tools.FloorPOT = function (x) {
  8082. x = x | (x >> 1);
  8083. x = x | (x >> 2);
  8084. x = x | (x >> 4);
  8085. x = x | (x >> 8);
  8086. x = x | (x >> 16);
  8087. return x - (x >> 1);
  8088. };
  8089. /**
  8090. * Find the nearest power of two.
  8091. * @param x Number to start search from.
  8092. * @return Next nearest power of two.
  8093. */
  8094. Tools.NearestPOT = function (x) {
  8095. var c = Tools.CeilingPOT(x);
  8096. var f = Tools.FloorPOT(x);
  8097. return (c - x) > (x - f) ? f : c;
  8098. };
  8099. Tools.GetExponentOfTwo = function (value, max, mode) {
  8100. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8101. var pot;
  8102. switch (mode) {
  8103. case BABYLON.Engine.SCALEMODE_FLOOR:
  8104. pot = Tools.FloorPOT(value);
  8105. break;
  8106. case BABYLON.Engine.SCALEMODE_NEAREST:
  8107. pot = Tools.NearestPOT(value);
  8108. break;
  8109. case BABYLON.Engine.SCALEMODE_CEILING:
  8110. default:
  8111. pot = Tools.CeilingPOT(value);
  8112. break;
  8113. }
  8114. return Math.min(pot, max);
  8115. };
  8116. Tools.GetFilename = function (path) {
  8117. var index = path.lastIndexOf("/");
  8118. if (index < 0)
  8119. return path;
  8120. return path.substring(index + 1);
  8121. };
  8122. /**
  8123. * Extracts the "folder" part of a path (everything before the filename).
  8124. * @param uri The URI to extract the info from
  8125. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8126. * @returns The "folder" part of the path
  8127. */
  8128. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8129. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8130. var index = uri.lastIndexOf("/");
  8131. if (index < 0) {
  8132. if (returnUnchangedIfNoSlash) {
  8133. return uri;
  8134. }
  8135. return "";
  8136. }
  8137. return uri.substring(0, index + 1);
  8138. };
  8139. Tools.GetDOMTextContent = function (element) {
  8140. var result = "";
  8141. var child = element.firstChild;
  8142. while (child) {
  8143. if (child.nodeType === 3) {
  8144. result += child.textContent;
  8145. }
  8146. child = child.nextSibling;
  8147. }
  8148. return result;
  8149. };
  8150. Tools.ToDegrees = function (angle) {
  8151. return angle * 180 / Math.PI;
  8152. };
  8153. Tools.ToRadians = function (angle) {
  8154. return angle * Math.PI / 180;
  8155. };
  8156. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8157. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8158. var output = "";
  8159. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8160. var i = 0;
  8161. var bytes = new Uint8Array(buffer);
  8162. while (i < bytes.length) {
  8163. chr1 = bytes[i++];
  8164. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8165. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8166. enc1 = chr1 >> 2;
  8167. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8168. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8169. enc4 = chr3 & 63;
  8170. if (isNaN(chr2)) {
  8171. enc3 = enc4 = 64;
  8172. }
  8173. else if (isNaN(chr3)) {
  8174. enc4 = 64;
  8175. }
  8176. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8177. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8178. }
  8179. return "data:image/png;base64," + output;
  8180. };
  8181. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8182. if (bias === void 0) { bias = null; }
  8183. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8184. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8185. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8186. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8187. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8188. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8189. }
  8190. if (bias) {
  8191. minimum.x -= minimum.x * bias.x + bias.y;
  8192. minimum.y -= minimum.y * bias.x + bias.y;
  8193. minimum.z -= minimum.z * bias.x + bias.y;
  8194. maximum.x += maximum.x * bias.x + bias.y;
  8195. maximum.y += maximum.y * bias.x + bias.y;
  8196. maximum.z += maximum.z * bias.x + bias.y;
  8197. }
  8198. return {
  8199. minimum: minimum,
  8200. maximum: maximum
  8201. };
  8202. };
  8203. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8204. if (bias === void 0) { bias = null; }
  8205. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8206. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8207. if (!stride) {
  8208. stride = 3;
  8209. }
  8210. for (var index = start; index < start + count; index++) {
  8211. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8212. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8213. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8214. }
  8215. if (bias) {
  8216. minimum.x -= minimum.x * bias.x + bias.y;
  8217. minimum.y -= minimum.y * bias.x + bias.y;
  8218. minimum.z -= minimum.z * bias.x + bias.y;
  8219. maximum.x += maximum.x * bias.x + bias.y;
  8220. maximum.y += maximum.y * bias.x + bias.y;
  8221. maximum.z += maximum.z * bias.x + bias.y;
  8222. }
  8223. return {
  8224. minimum: minimum,
  8225. maximum: maximum
  8226. };
  8227. };
  8228. Tools.Vector2ArrayFeeder = function (array) {
  8229. return function (index) {
  8230. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8231. var length = isFloatArray ? array.length / 2 : array.length;
  8232. if (index >= length) {
  8233. return null;
  8234. }
  8235. if (isFloatArray) {
  8236. var fa = array;
  8237. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8238. }
  8239. var a = array;
  8240. return a[index];
  8241. };
  8242. };
  8243. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8244. if (bias === void 0) { bias = null; }
  8245. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8246. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8247. var i = 0;
  8248. var cur = feeder(i++);
  8249. while (cur) {
  8250. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8251. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8252. cur = feeder(i++);
  8253. }
  8254. if (bias) {
  8255. minimum.x -= minimum.x * bias.x + bias.y;
  8256. minimum.y -= minimum.y * bias.x + bias.y;
  8257. maximum.x += maximum.x * bias.x + bias.y;
  8258. maximum.y += maximum.y * bias.x + bias.y;
  8259. }
  8260. return {
  8261. minimum: minimum,
  8262. maximum: maximum
  8263. };
  8264. };
  8265. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8266. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8267. return null;
  8268. return Array.isArray(obj) ? obj : [obj];
  8269. };
  8270. // Misc.
  8271. Tools.GetPointerPrefix = function () {
  8272. var eventPrefix = "pointer";
  8273. // Check if pointer events are supported
  8274. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8275. eventPrefix = "mouse";
  8276. }
  8277. return eventPrefix;
  8278. };
  8279. /**
  8280. * @param func - the function to be called
  8281. * @param requester - the object that will request the next frame. Falls back to window.
  8282. */
  8283. Tools.QueueNewFrame = function (func, requester) {
  8284. if (!Tools.IsWindowObjectExist()) {
  8285. return setTimeout(func, 16);
  8286. }
  8287. if (!requester) {
  8288. requester = window;
  8289. }
  8290. if (requester.requestAnimationFrame) {
  8291. return requester.requestAnimationFrame(func);
  8292. }
  8293. else if (requester.msRequestAnimationFrame) {
  8294. return requester.msRequestAnimationFrame(func);
  8295. }
  8296. else if (requester.webkitRequestAnimationFrame) {
  8297. return requester.webkitRequestAnimationFrame(func);
  8298. }
  8299. else if (requester.mozRequestAnimationFrame) {
  8300. return requester.mozRequestAnimationFrame(func);
  8301. }
  8302. else if (requester.oRequestAnimationFrame) {
  8303. return requester.oRequestAnimationFrame(func);
  8304. }
  8305. else {
  8306. return window.setTimeout(func, 16);
  8307. }
  8308. };
  8309. Tools.RequestFullscreen = function (element) {
  8310. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8311. if (!requestFunction)
  8312. return;
  8313. requestFunction.call(element);
  8314. };
  8315. Tools.ExitFullscreen = function () {
  8316. if (document.exitFullscreen) {
  8317. document.exitFullscreen();
  8318. }
  8319. else if (document.mozCancelFullScreen) {
  8320. document.mozCancelFullScreen();
  8321. }
  8322. else if (document.webkitCancelFullScreen) {
  8323. document.webkitCancelFullScreen();
  8324. }
  8325. else if (document.msCancelFullScreen) {
  8326. document.msCancelFullScreen();
  8327. }
  8328. };
  8329. Tools.SetCorsBehavior = function (url, element) {
  8330. if (url && url.indexOf("data:") === 0) {
  8331. return;
  8332. }
  8333. if (Tools.CorsBehavior) {
  8334. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8335. element.crossOrigin = Tools.CorsBehavior;
  8336. }
  8337. else {
  8338. var result = Tools.CorsBehavior(url);
  8339. if (result) {
  8340. element.crossOrigin = result;
  8341. }
  8342. }
  8343. }
  8344. };
  8345. // External files
  8346. Tools.CleanUrl = function (url) {
  8347. url = url.replace(/#/mg, "%23");
  8348. return url;
  8349. };
  8350. Tools.LoadImage = function (url, onLoad, onError, database) {
  8351. if (url instanceof ArrayBuffer) {
  8352. url = Tools.EncodeArrayBufferTobase64(url);
  8353. }
  8354. url = Tools.CleanUrl(url);
  8355. url = Tools.PreprocessUrl(url);
  8356. var img = new Image();
  8357. Tools.SetCorsBehavior(url, img);
  8358. var loadHandler = function () {
  8359. img.removeEventListener("load", loadHandler);
  8360. img.removeEventListener("error", errorHandler);
  8361. onLoad(img);
  8362. };
  8363. var errorHandler = function (err) {
  8364. img.removeEventListener("load", loadHandler);
  8365. img.removeEventListener("error", errorHandler);
  8366. Tools.Error("Error while trying to load image: " + url);
  8367. if (onError) {
  8368. onError("Error while trying to load image: " + url, err);
  8369. }
  8370. };
  8371. img.addEventListener("load", loadHandler);
  8372. img.addEventListener("error", errorHandler);
  8373. var noIndexedDB = function () {
  8374. img.src = url;
  8375. };
  8376. var loadFromIndexedDB = function () {
  8377. if (database) {
  8378. database.loadImageFromDB(url, img);
  8379. }
  8380. };
  8381. //ANY database to do!
  8382. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8383. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8384. }
  8385. else {
  8386. if (url.indexOf("file:") !== -1) {
  8387. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8388. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8389. try {
  8390. var blobURL;
  8391. try {
  8392. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8393. }
  8394. catch (ex) {
  8395. // Chrome doesn't support oneTimeOnly parameter
  8396. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8397. }
  8398. img.src = blobURL;
  8399. }
  8400. catch (e) {
  8401. img.src = "";
  8402. }
  8403. return img;
  8404. }
  8405. }
  8406. noIndexedDB();
  8407. }
  8408. return img;
  8409. };
  8410. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8411. url = Tools.CleanUrl(url);
  8412. url = Tools.PreprocessUrl(url);
  8413. // If file and file input are set
  8414. if (url.indexOf("file:") !== -1) {
  8415. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8416. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8417. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8418. }
  8419. }
  8420. var loadUrl = Tools.BaseUrl + url;
  8421. var aborted = false;
  8422. var fileRequest = {
  8423. onCompleteObservable: new BABYLON.Observable(),
  8424. abort: function () { return aborted = true; },
  8425. };
  8426. var requestFile = function () {
  8427. var request = new XMLHttpRequest();
  8428. var retryHandle = null;
  8429. fileRequest.abort = function () {
  8430. aborted = true;
  8431. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8432. request.abort();
  8433. }
  8434. if (retryHandle !== null) {
  8435. clearTimeout(retryHandle);
  8436. retryHandle = null;
  8437. }
  8438. };
  8439. var retryLoop = function (retryIndex) {
  8440. request.open('GET', loadUrl, true);
  8441. if (useArrayBuffer) {
  8442. request.responseType = "arraybuffer";
  8443. }
  8444. if (onProgress) {
  8445. request.addEventListener("progress", onProgress);
  8446. }
  8447. var onLoadEnd = function () {
  8448. request.removeEventListener("loadend", onLoadEnd);
  8449. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8450. fileRequest.onCompleteObservable.clear();
  8451. };
  8452. request.addEventListener("loadend", onLoadEnd);
  8453. var onReadyStateChange = function () {
  8454. if (aborted) {
  8455. return;
  8456. }
  8457. // In case of undefined state in some browsers.
  8458. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8459. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8460. request.removeEventListener("readystatechange", onReadyStateChange);
  8461. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8462. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8463. return;
  8464. }
  8465. var retryStrategy = Tools.DefaultRetryStrategy;
  8466. if (retryStrategy) {
  8467. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8468. if (waitTime !== -1) {
  8469. // Prevent the request from completing for retry.
  8470. request.removeEventListener("loadend", onLoadEnd);
  8471. request = new XMLHttpRequest();
  8472. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8473. return;
  8474. }
  8475. }
  8476. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8477. if (onError) {
  8478. onError(request, e);
  8479. }
  8480. else {
  8481. throw e;
  8482. }
  8483. }
  8484. };
  8485. request.addEventListener("readystatechange", onReadyStateChange);
  8486. request.send();
  8487. };
  8488. retryLoop(0);
  8489. };
  8490. // Caching all files
  8491. if (database && database.enableSceneOffline) {
  8492. var noIndexedDB_1 = function () {
  8493. if (!aborted) {
  8494. requestFile();
  8495. }
  8496. };
  8497. var loadFromIndexedDB = function () {
  8498. // TODO: database needs to support aborting and should return a IFileRequest
  8499. if (aborted) {
  8500. return;
  8501. }
  8502. if (database) {
  8503. database.loadFileFromDB(url, function (data) {
  8504. if (!aborted) {
  8505. onSuccess(data);
  8506. }
  8507. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8508. }, onProgress ? function (event) {
  8509. if (!aborted) {
  8510. onProgress(event);
  8511. }
  8512. } : undefined, noIndexedDB_1, useArrayBuffer);
  8513. }
  8514. };
  8515. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8516. }
  8517. else {
  8518. requestFile();
  8519. }
  8520. return fileRequest;
  8521. };
  8522. /**
  8523. * Load a script (identified by an url). When the url returns, the
  8524. * content of this file is added into a new script element, attached to the DOM (body element)
  8525. */
  8526. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8527. var head = document.getElementsByTagName('head')[0];
  8528. var script = document.createElement('script');
  8529. script.type = 'text/javascript';
  8530. script.src = scriptUrl;
  8531. script.onload = function () {
  8532. if (onSuccess) {
  8533. onSuccess();
  8534. }
  8535. };
  8536. script.onerror = function (e) {
  8537. if (onError) {
  8538. onError("Unable to load script", e);
  8539. }
  8540. };
  8541. head.appendChild(script);
  8542. };
  8543. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8544. var reader = new FileReader();
  8545. var request = {
  8546. onCompleteObservable: new BABYLON.Observable(),
  8547. abort: function () { return reader.abort(); },
  8548. };
  8549. reader.onloadend = function (e) {
  8550. request.onCompleteObservable.notifyObservers(request);
  8551. };
  8552. reader.onload = function (e) {
  8553. //target doesn't have result from ts 1.3
  8554. callback(e.target['result']);
  8555. };
  8556. reader.onprogress = progressCallback;
  8557. reader.readAsDataURL(fileToLoad);
  8558. return request;
  8559. };
  8560. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8561. var reader = new FileReader();
  8562. var request = {
  8563. onCompleteObservable: new BABYLON.Observable(),
  8564. abort: function () { return reader.abort(); },
  8565. };
  8566. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8567. reader.onerror = function (e) {
  8568. Tools.Log("Error while reading file: " + fileToLoad.name);
  8569. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8570. };
  8571. reader.onload = function (e) {
  8572. //target doesn't have result from ts 1.3
  8573. callback(e.target['result']);
  8574. };
  8575. if (progressCallBack) {
  8576. reader.onprogress = progressCallBack;
  8577. }
  8578. if (!useArrayBuffer) {
  8579. // Asynchronous read
  8580. reader.readAsText(fileToLoad);
  8581. }
  8582. else {
  8583. reader.readAsArrayBuffer(fileToLoad);
  8584. }
  8585. return request;
  8586. };
  8587. //returns a downloadable url to a file content.
  8588. Tools.FileAsURL = function (content) {
  8589. var fileBlob = new Blob([content]);
  8590. var url = window.URL || window.webkitURL;
  8591. var link = url.createObjectURL(fileBlob);
  8592. return link;
  8593. };
  8594. // Misc.
  8595. Tools.Format = function (value, decimals) {
  8596. if (decimals === void 0) { decimals = 2; }
  8597. return value.toFixed(decimals);
  8598. };
  8599. Tools.CheckExtends = function (v, min, max) {
  8600. if (v.x < min.x)
  8601. min.x = v.x;
  8602. if (v.y < min.y)
  8603. min.y = v.y;
  8604. if (v.z < min.z)
  8605. min.z = v.z;
  8606. if (v.x > max.x)
  8607. max.x = v.x;
  8608. if (v.y > max.y)
  8609. max.y = v.y;
  8610. if (v.z > max.z)
  8611. max.z = v.z;
  8612. };
  8613. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8614. for (var prop in source) {
  8615. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8616. continue;
  8617. }
  8618. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8619. continue;
  8620. }
  8621. var sourceValue = source[prop];
  8622. var typeOfSourceValue = typeof sourceValue;
  8623. if (typeOfSourceValue === "function") {
  8624. continue;
  8625. }
  8626. if (typeOfSourceValue === "object") {
  8627. if (sourceValue instanceof Array) {
  8628. destination[prop] = [];
  8629. if (sourceValue.length > 0) {
  8630. if (typeof sourceValue[0] == "object") {
  8631. for (var index = 0; index < sourceValue.length; index++) {
  8632. var clonedValue = cloneValue(sourceValue[index], destination);
  8633. if (destination[prop].indexOf(clonedValue) === -1) {
  8634. destination[prop].push(clonedValue);
  8635. }
  8636. }
  8637. }
  8638. else {
  8639. destination[prop] = sourceValue.slice(0);
  8640. }
  8641. }
  8642. }
  8643. else {
  8644. destination[prop] = cloneValue(sourceValue, destination);
  8645. }
  8646. }
  8647. else {
  8648. destination[prop] = sourceValue;
  8649. }
  8650. }
  8651. };
  8652. Tools.IsEmpty = function (obj) {
  8653. for (var i in obj) {
  8654. if (obj.hasOwnProperty(i)) {
  8655. return false;
  8656. }
  8657. }
  8658. return true;
  8659. };
  8660. Tools.RegisterTopRootEvents = function (events) {
  8661. for (var index = 0; index < events.length; index++) {
  8662. var event = events[index];
  8663. window.addEventListener(event.name, event.handler, false);
  8664. try {
  8665. if (window.parent) {
  8666. window.parent.addEventListener(event.name, event.handler, false);
  8667. }
  8668. }
  8669. catch (e) {
  8670. // Silently fails...
  8671. }
  8672. }
  8673. };
  8674. Tools.UnregisterTopRootEvents = function (events) {
  8675. for (var index = 0; index < events.length; index++) {
  8676. var event = events[index];
  8677. window.removeEventListener(event.name, event.handler);
  8678. try {
  8679. if (window.parent) {
  8680. window.parent.removeEventListener(event.name, event.handler);
  8681. }
  8682. }
  8683. catch (e) {
  8684. // Silently fails...
  8685. }
  8686. }
  8687. };
  8688. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8689. if (mimeType === void 0) { mimeType = "image/png"; }
  8690. // Read the contents of the framebuffer
  8691. var numberOfChannelsByLine = width * 4;
  8692. var halfHeight = height / 2;
  8693. //Reading datas from WebGL
  8694. var data = engine.readPixels(0, 0, width, height);
  8695. //To flip image on Y axis.
  8696. for (var i = 0; i < halfHeight; i++) {
  8697. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8698. var currentCell = j + i * numberOfChannelsByLine;
  8699. var targetLine = height - i - 1;
  8700. var targetCell = j + targetLine * numberOfChannelsByLine;
  8701. var temp = data[currentCell];
  8702. data[currentCell] = data[targetCell];
  8703. data[targetCell] = temp;
  8704. }
  8705. }
  8706. // Create a 2D canvas to store the result
  8707. if (!screenshotCanvas) {
  8708. screenshotCanvas = document.createElement('canvas');
  8709. }
  8710. screenshotCanvas.width = width;
  8711. screenshotCanvas.height = height;
  8712. var context = screenshotCanvas.getContext('2d');
  8713. if (context) {
  8714. // Copy the pixels to a 2D canvas
  8715. var imageData = context.createImageData(width, height);
  8716. var castData = (imageData.data);
  8717. castData.set(data);
  8718. context.putImageData(imageData, 0, 0);
  8719. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8720. }
  8721. };
  8722. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8723. if (mimeType === void 0) { mimeType = "image/png"; }
  8724. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8725. if (successCallback) {
  8726. successCallback(base64Image);
  8727. }
  8728. else {
  8729. // We need HTMLCanvasElement.toBlob for HD screenshots
  8730. if (!screenshotCanvas.toBlob) {
  8731. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8732. screenshotCanvas.toBlob = function (callback, type, quality) {
  8733. var _this = this;
  8734. setTimeout(function () {
  8735. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8736. for (var i = 0; i < len; i++) {
  8737. arr[i] = binStr.charCodeAt(i);
  8738. }
  8739. callback(new Blob([arr], { type: type || 'image/png' }));
  8740. });
  8741. };
  8742. }
  8743. screenshotCanvas.toBlob(function (blob) {
  8744. var url = URL.createObjectURL(blob);
  8745. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8746. if (("download" in document.createElement("a"))) {
  8747. var a = window.document.createElement("a");
  8748. a.href = url;
  8749. if (fileName) {
  8750. a.setAttribute("download", fileName);
  8751. }
  8752. else {
  8753. var date = new Date();
  8754. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8755. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8756. }
  8757. window.document.body.appendChild(a);
  8758. a.addEventListener("click", function () {
  8759. if (a.parentElement) {
  8760. a.parentElement.removeChild(a);
  8761. }
  8762. });
  8763. a.click();
  8764. }
  8765. else {
  8766. var newWindow = window.open("");
  8767. if (!newWindow)
  8768. return;
  8769. var img = newWindow.document.createElement("img");
  8770. img.onload = function () {
  8771. // no longer need to read the blob so it's revoked
  8772. URL.revokeObjectURL(url);
  8773. };
  8774. img.src = url;
  8775. newWindow.document.body.appendChild(img);
  8776. }
  8777. });
  8778. }
  8779. };
  8780. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8781. if (mimeType === void 0) { mimeType = "image/png"; }
  8782. var width;
  8783. var height;
  8784. // If a precision value is specified
  8785. if (size.precision) {
  8786. width = Math.round(engine.getRenderWidth() * size.precision);
  8787. height = Math.round(width / engine.getAspectRatio(camera));
  8788. }
  8789. else if (size.width && size.height) {
  8790. width = size.width;
  8791. height = size.height;
  8792. }
  8793. else if (size.width && !size.height) {
  8794. width = size.width;
  8795. height = Math.round(width / engine.getAspectRatio(camera));
  8796. }
  8797. else if (size.height && !size.width) {
  8798. height = size.height;
  8799. width = Math.round(height * engine.getAspectRatio(camera));
  8800. }
  8801. else if (!isNaN(size)) {
  8802. height = size;
  8803. width = size;
  8804. }
  8805. else {
  8806. Tools.Error("Invalid 'size' parameter !");
  8807. return;
  8808. }
  8809. if (!screenshotCanvas) {
  8810. screenshotCanvas = document.createElement('canvas');
  8811. }
  8812. screenshotCanvas.width = width;
  8813. screenshotCanvas.height = height;
  8814. var renderContext = screenshotCanvas.getContext("2d");
  8815. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8816. var newWidth = width;
  8817. var newHeight = newWidth / ratio;
  8818. if (newHeight > height) {
  8819. newHeight = height;
  8820. newWidth = newHeight * ratio;
  8821. }
  8822. var offsetX = Math.max(0, width - newWidth) / 2;
  8823. var offsetY = Math.max(0, height - newHeight) / 2;
  8824. var renderingCanvas = engine.getRenderingCanvas();
  8825. if (renderContext && renderingCanvas) {
  8826. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8827. }
  8828. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8829. };
  8830. /**
  8831. * Generates an image screenshot from the specified camera.
  8832. *
  8833. * @param engine The engine to use for rendering
  8834. * @param camera The camera to use for rendering
  8835. * @param size This parameter can be set to a single number or to an object with the
  8836. * following (optional) properties: precision, width, height. If a single number is passed,
  8837. * it will be used for both width and height. If an object is passed, the screenshot size
  8838. * will be derived from the parameters. The precision property is a multiplier allowing
  8839. * rendering at a higher or lower resolution.
  8840. * @param successCallback The callback receives a single parameter which contains the
  8841. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8842. * src parameter of an <img> to display it.
  8843. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8844. * Check your browser for supported MIME types.
  8845. * @param samples Texture samples (default: 1)
  8846. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8847. * @param fileName A name for for the downloaded file.
  8848. * @constructor
  8849. */
  8850. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8851. if (mimeType === void 0) { mimeType = "image/png"; }
  8852. if (samples === void 0) { samples = 1; }
  8853. if (antialiasing === void 0) { antialiasing = false; }
  8854. var width;
  8855. var height;
  8856. //If a precision value is specified
  8857. if (size.precision) {
  8858. width = Math.round(engine.getRenderWidth() * size.precision);
  8859. height = Math.round(width / engine.getAspectRatio(camera));
  8860. size = { width: width, height: height };
  8861. }
  8862. else if (size.width && size.height) {
  8863. width = size.width;
  8864. height = size.height;
  8865. }
  8866. else if (size.width && !size.height) {
  8867. width = size.width;
  8868. height = Math.round(width / engine.getAspectRatio(camera));
  8869. size = { width: width, height: height };
  8870. }
  8871. else if (size.height && !size.width) {
  8872. height = size.height;
  8873. width = Math.round(height * engine.getAspectRatio(camera));
  8874. size = { width: width, height: height };
  8875. }
  8876. else if (!isNaN(size)) {
  8877. height = size;
  8878. width = size;
  8879. }
  8880. else {
  8881. Tools.Error("Invalid 'size' parameter !");
  8882. return;
  8883. }
  8884. var scene = camera.getScene();
  8885. var previousCamera = null;
  8886. if (scene.activeCamera !== camera) {
  8887. previousCamera = scene.activeCamera;
  8888. scene.activeCamera = camera;
  8889. }
  8890. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8891. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8892. texture.renderList = null;
  8893. texture.samples = samples;
  8894. if (antialiasing) {
  8895. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8896. }
  8897. texture.onAfterRenderObservable.add(function () {
  8898. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8899. });
  8900. scene.incrementRenderId();
  8901. scene.resetCachedMaterial();
  8902. texture.render(true);
  8903. texture.dispose();
  8904. if (previousCamera) {
  8905. scene.activeCamera = previousCamera;
  8906. }
  8907. camera.getProjectionMatrix(true); // Force cache refresh;
  8908. };
  8909. // XHR response validator for local file scenario
  8910. Tools.ValidateXHRData = function (xhr, dataType) {
  8911. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8912. if (dataType === void 0) { dataType = 7; }
  8913. try {
  8914. if (dataType & 1) {
  8915. if (xhr.responseText && xhr.responseText.length > 0) {
  8916. return true;
  8917. }
  8918. else if (dataType === 1) {
  8919. return false;
  8920. }
  8921. }
  8922. if (dataType & 2) {
  8923. // Check header width and height since there is no "TGA" magic number
  8924. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8925. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8926. return true;
  8927. }
  8928. else if (dataType === 2) {
  8929. return false;
  8930. }
  8931. }
  8932. if (dataType & 4) {
  8933. // Check for the "DDS" magic number
  8934. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8935. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8936. return true;
  8937. }
  8938. else {
  8939. return false;
  8940. }
  8941. }
  8942. }
  8943. catch (e) {
  8944. // Global protection
  8945. }
  8946. return false;
  8947. };
  8948. /**
  8949. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8950. * Be aware Math.random() could cause collisions, but:
  8951. * "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"
  8952. */
  8953. Tools.RandomId = function () {
  8954. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8955. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8956. return v.toString(16);
  8957. });
  8958. };
  8959. /**
  8960. * Test if the given uri is a base64 string.
  8961. * @param uri The uri to test
  8962. * @return True if the uri is a base64 string or false otherwise.
  8963. */
  8964. Tools.IsBase64 = function (uri) {
  8965. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8966. };
  8967. /**
  8968. * Decode the given base64 uri.
  8969. * @param uri The uri to decode
  8970. * @return The decoded base64 data.
  8971. */
  8972. Tools.DecodeBase64 = function (uri) {
  8973. var decodedString = atob(uri.split(",")[1]);
  8974. var bufferLength = decodedString.length;
  8975. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8976. for (var i = 0; i < bufferLength; i++) {
  8977. bufferView[i] = decodedString.charCodeAt(i);
  8978. }
  8979. return bufferView.buffer;
  8980. };
  8981. Object.defineProperty(Tools, "NoneLogLevel", {
  8982. get: function () {
  8983. return Tools._NoneLogLevel;
  8984. },
  8985. enumerable: true,
  8986. configurable: true
  8987. });
  8988. Object.defineProperty(Tools, "MessageLogLevel", {
  8989. get: function () {
  8990. return Tools._MessageLogLevel;
  8991. },
  8992. enumerable: true,
  8993. configurable: true
  8994. });
  8995. Object.defineProperty(Tools, "WarningLogLevel", {
  8996. get: function () {
  8997. return Tools._WarningLogLevel;
  8998. },
  8999. enumerable: true,
  9000. configurable: true
  9001. });
  9002. Object.defineProperty(Tools, "ErrorLogLevel", {
  9003. get: function () {
  9004. return Tools._ErrorLogLevel;
  9005. },
  9006. enumerable: true,
  9007. configurable: true
  9008. });
  9009. Object.defineProperty(Tools, "AllLogLevel", {
  9010. get: function () {
  9011. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9012. },
  9013. enumerable: true,
  9014. configurable: true
  9015. });
  9016. Tools._AddLogEntry = function (entry) {
  9017. Tools._LogCache = entry + Tools._LogCache;
  9018. if (Tools.OnNewCacheEntry) {
  9019. Tools.OnNewCacheEntry(entry);
  9020. }
  9021. };
  9022. Tools._FormatMessage = function (message) {
  9023. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9024. var date = new Date();
  9025. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9026. };
  9027. Tools._LogDisabled = function (message) {
  9028. // nothing to do
  9029. };
  9030. Tools._LogEnabled = function (message) {
  9031. var formattedMessage = Tools._FormatMessage(message);
  9032. console.log("BJS - " + formattedMessage);
  9033. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9034. Tools._AddLogEntry(entry);
  9035. };
  9036. Tools._WarnDisabled = function (message) {
  9037. // nothing to do
  9038. };
  9039. Tools._WarnEnabled = function (message) {
  9040. var formattedMessage = Tools._FormatMessage(message);
  9041. console.warn("BJS - " + formattedMessage);
  9042. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9043. Tools._AddLogEntry(entry);
  9044. };
  9045. Tools._ErrorDisabled = function (message) {
  9046. // nothing to do
  9047. };
  9048. Tools._ErrorEnabled = function (message) {
  9049. Tools.errorsCount++;
  9050. var formattedMessage = Tools._FormatMessage(message);
  9051. console.error("BJS - " + formattedMessage);
  9052. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9053. Tools._AddLogEntry(entry);
  9054. };
  9055. Object.defineProperty(Tools, "LogCache", {
  9056. get: function () {
  9057. return Tools._LogCache;
  9058. },
  9059. enumerable: true,
  9060. configurable: true
  9061. });
  9062. Tools.ClearLogCache = function () {
  9063. Tools._LogCache = "";
  9064. Tools.errorsCount = 0;
  9065. };
  9066. Object.defineProperty(Tools, "LogLevels", {
  9067. set: function (level) {
  9068. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9069. Tools.Log = Tools._LogEnabled;
  9070. }
  9071. else {
  9072. Tools.Log = Tools._LogDisabled;
  9073. }
  9074. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9075. Tools.Warn = Tools._WarnEnabled;
  9076. }
  9077. else {
  9078. Tools.Warn = Tools._WarnDisabled;
  9079. }
  9080. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9081. Tools.Error = Tools._ErrorEnabled;
  9082. }
  9083. else {
  9084. Tools.Error = Tools._ErrorDisabled;
  9085. }
  9086. },
  9087. enumerable: true,
  9088. configurable: true
  9089. });
  9090. Tools.IsWindowObjectExist = function () {
  9091. return (typeof window) !== "undefined";
  9092. };
  9093. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9094. get: function () {
  9095. return Tools._PerformanceNoneLogLevel;
  9096. },
  9097. enumerable: true,
  9098. configurable: true
  9099. });
  9100. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9101. get: function () {
  9102. return Tools._PerformanceUserMarkLogLevel;
  9103. },
  9104. enumerable: true,
  9105. configurable: true
  9106. });
  9107. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9108. get: function () {
  9109. return Tools._PerformanceConsoleLogLevel;
  9110. },
  9111. enumerable: true,
  9112. configurable: true
  9113. });
  9114. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9115. set: function (level) {
  9116. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9117. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9118. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9119. return;
  9120. }
  9121. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9122. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9123. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9124. return;
  9125. }
  9126. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9127. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9128. },
  9129. enumerable: true,
  9130. configurable: true
  9131. });
  9132. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9133. };
  9134. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9135. };
  9136. Tools._StartUserMark = function (counterName, condition) {
  9137. if (condition === void 0) { condition = true; }
  9138. if (!Tools._performance) {
  9139. if (!Tools.IsWindowObjectExist()) {
  9140. return;
  9141. }
  9142. Tools._performance = window.performance;
  9143. }
  9144. if (!condition || !Tools._performance.mark) {
  9145. return;
  9146. }
  9147. Tools._performance.mark(counterName + "-Begin");
  9148. };
  9149. Tools._EndUserMark = function (counterName, condition) {
  9150. if (condition === void 0) { condition = true; }
  9151. if (!condition || !Tools._performance.mark) {
  9152. return;
  9153. }
  9154. Tools._performance.mark(counterName + "-End");
  9155. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9156. };
  9157. Tools._StartPerformanceConsole = function (counterName, condition) {
  9158. if (condition === void 0) { condition = true; }
  9159. if (!condition) {
  9160. return;
  9161. }
  9162. Tools._StartUserMark(counterName, condition);
  9163. if (console.time) {
  9164. console.time(counterName);
  9165. }
  9166. };
  9167. Tools._EndPerformanceConsole = function (counterName, condition) {
  9168. if (condition === void 0) { condition = true; }
  9169. if (!condition) {
  9170. return;
  9171. }
  9172. Tools._EndUserMark(counterName, condition);
  9173. if (console.time) {
  9174. console.timeEnd(counterName);
  9175. }
  9176. };
  9177. Object.defineProperty(Tools, "Now", {
  9178. get: function () {
  9179. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9180. return window.performance.now();
  9181. }
  9182. return new Date().getTime();
  9183. },
  9184. enumerable: true,
  9185. configurable: true
  9186. });
  9187. /**
  9188. * This method will return the name of the class used to create the instance of the given object.
  9189. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9190. * @param object the object to get the class name from
  9191. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9192. */
  9193. Tools.GetClassName = function (object, isType) {
  9194. if (isType === void 0) { isType = false; }
  9195. var name = null;
  9196. if (!isType && object.getClassName) {
  9197. name = object.getClassName();
  9198. }
  9199. else {
  9200. if (object instanceof Object) {
  9201. var classObj = isType ? object : Object.getPrototypeOf(object);
  9202. name = classObj.constructor["__bjsclassName__"];
  9203. }
  9204. if (!name) {
  9205. name = typeof object;
  9206. }
  9207. }
  9208. return name;
  9209. };
  9210. Tools.First = function (array, predicate) {
  9211. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9212. var el = array_1[_i];
  9213. if (predicate(el)) {
  9214. return el;
  9215. }
  9216. }
  9217. return null;
  9218. };
  9219. /**
  9220. * This method will return the name of the full name of the class, including its owning module (if any).
  9221. * 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).
  9222. * @param object the object to get the class name from
  9223. * @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.
  9224. */
  9225. Tools.getFullClassName = function (object, isType) {
  9226. if (isType === void 0) { isType = false; }
  9227. var className = null;
  9228. var moduleName = null;
  9229. if (!isType && object.getClassName) {
  9230. className = object.getClassName();
  9231. }
  9232. else {
  9233. if (object instanceof Object) {
  9234. var classObj = isType ? object : Object.getPrototypeOf(object);
  9235. className = classObj.constructor["__bjsclassName__"];
  9236. moduleName = classObj.constructor["__bjsmoduleName__"];
  9237. }
  9238. if (!className) {
  9239. className = typeof object;
  9240. }
  9241. }
  9242. if (!className) {
  9243. return null;
  9244. }
  9245. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9246. };
  9247. /**
  9248. * 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.
  9249. * @param array
  9250. */
  9251. Tools.arrayOrStringFeeder = function (array) {
  9252. return function (index) {
  9253. if (index >= array.length) {
  9254. return null;
  9255. }
  9256. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9257. if (val && val.getHashCode) {
  9258. val = val.getHashCode();
  9259. }
  9260. if (typeof val === "string") {
  9261. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9262. }
  9263. return val;
  9264. };
  9265. };
  9266. /**
  9267. * Compute the hashCode of a stream of number
  9268. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9269. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9270. * @return the hash code computed
  9271. */
  9272. Tools.hashCodeFromStream = function (feeder) {
  9273. // Based from here: http://stackoverflow.com/a/7616484/802124
  9274. var hash = 0;
  9275. var index = 0;
  9276. var chr = feeder(index++);
  9277. while (chr != null) {
  9278. hash = ((hash << 5) - hash) + chr;
  9279. hash |= 0; // Convert to 32bit integer
  9280. chr = feeder(index++);
  9281. }
  9282. return hash;
  9283. };
  9284. /**
  9285. * Returns a promise that resolves after the given amount of time.
  9286. * @param delay Number of milliseconds to delay
  9287. * @returns Promise that resolves after the given amount of time
  9288. */
  9289. Tools.DelayAsync = function (delay) {
  9290. return new Promise(function (resolve) {
  9291. setTimeout(function () {
  9292. resolve();
  9293. }, delay);
  9294. });
  9295. };
  9296. Tools.BaseUrl = "";
  9297. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9298. /**
  9299. * Default behaviour for cors in the application.
  9300. * It can be a string if the expected behavior is identical in the entire app.
  9301. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9302. */
  9303. Tools.CorsBehavior = "anonymous";
  9304. Tools.UseFallbackTexture = true;
  9305. /**
  9306. * Use this object to register external classes like custom textures or material
  9307. * to allow the laoders to instantiate them
  9308. */
  9309. Tools.RegisteredExternalClasses = {};
  9310. // Used in case of a texture loading problem
  9311. 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";
  9312. Tools.PreprocessUrl = function (url) {
  9313. return url;
  9314. };
  9315. // Logs
  9316. Tools._NoneLogLevel = 0;
  9317. Tools._MessageLogLevel = 1;
  9318. Tools._WarningLogLevel = 2;
  9319. Tools._ErrorLogLevel = 4;
  9320. Tools._LogCache = "";
  9321. Tools.errorsCount = 0;
  9322. Tools.Log = Tools._LogEnabled;
  9323. Tools.Warn = Tools._WarnEnabled;
  9324. Tools.Error = Tools._ErrorEnabled;
  9325. // Performances
  9326. Tools._PerformanceNoneLogLevel = 0;
  9327. Tools._PerformanceUserMarkLogLevel = 1;
  9328. Tools._PerformanceConsoleLogLevel = 2;
  9329. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9330. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9331. return Tools;
  9332. }());
  9333. BABYLON.Tools = Tools;
  9334. /**
  9335. * This class is used to track a performance counter which is number based.
  9336. * The user has access to many properties which give statistics of different nature
  9337. *
  9338. * The implementer can track two kinds of Performance Counter: time and count
  9339. * 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.
  9340. * 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.
  9341. */
  9342. var PerfCounter = /** @class */ (function () {
  9343. function PerfCounter() {
  9344. this._startMonitoringTime = 0;
  9345. this._min = 0;
  9346. this._max = 0;
  9347. this._average = 0;
  9348. this._lastSecAverage = 0;
  9349. this._current = 0;
  9350. this._totalValueCount = 0;
  9351. this._totalAccumulated = 0;
  9352. this._lastSecAccumulated = 0;
  9353. this._lastSecTime = 0;
  9354. this._lastSecValueCount = 0;
  9355. }
  9356. Object.defineProperty(PerfCounter.prototype, "min", {
  9357. /**
  9358. * Returns the smallest value ever
  9359. */
  9360. get: function () {
  9361. return this._min;
  9362. },
  9363. enumerable: true,
  9364. configurable: true
  9365. });
  9366. Object.defineProperty(PerfCounter.prototype, "max", {
  9367. /**
  9368. * Returns the biggest value ever
  9369. */
  9370. get: function () {
  9371. return this._max;
  9372. },
  9373. enumerable: true,
  9374. configurable: true
  9375. });
  9376. Object.defineProperty(PerfCounter.prototype, "average", {
  9377. /**
  9378. * Returns the average value since the performance counter is running
  9379. */
  9380. get: function () {
  9381. return this._average;
  9382. },
  9383. enumerable: true,
  9384. configurable: true
  9385. });
  9386. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9387. /**
  9388. * Returns the average value of the last second the counter was monitored
  9389. */
  9390. get: function () {
  9391. return this._lastSecAverage;
  9392. },
  9393. enumerable: true,
  9394. configurable: true
  9395. });
  9396. Object.defineProperty(PerfCounter.prototype, "current", {
  9397. /**
  9398. * Returns the current value
  9399. */
  9400. get: function () {
  9401. return this._current;
  9402. },
  9403. enumerable: true,
  9404. configurable: true
  9405. });
  9406. Object.defineProperty(PerfCounter.prototype, "total", {
  9407. get: function () {
  9408. return this._totalAccumulated;
  9409. },
  9410. enumerable: true,
  9411. configurable: true
  9412. });
  9413. Object.defineProperty(PerfCounter.prototype, "count", {
  9414. get: function () {
  9415. return this._totalValueCount;
  9416. },
  9417. enumerable: true,
  9418. configurable: true
  9419. });
  9420. /**
  9421. * Call this method to start monitoring a new frame.
  9422. * 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.
  9423. */
  9424. PerfCounter.prototype.fetchNewFrame = function () {
  9425. this._totalValueCount++;
  9426. this._current = 0;
  9427. this._lastSecValueCount++;
  9428. };
  9429. /**
  9430. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9431. * @param newCount the count value to add to the monitored count
  9432. * @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.
  9433. */
  9434. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9435. if (!PerfCounter.Enabled) {
  9436. return;
  9437. }
  9438. this._current += newCount;
  9439. if (fetchResult) {
  9440. this._fetchResult();
  9441. }
  9442. };
  9443. /**
  9444. * Start monitoring this performance counter
  9445. */
  9446. PerfCounter.prototype.beginMonitoring = function () {
  9447. if (!PerfCounter.Enabled) {
  9448. return;
  9449. }
  9450. this._startMonitoringTime = Tools.Now;
  9451. };
  9452. /**
  9453. * Compute the time lapsed since the previous beginMonitoring() call.
  9454. * @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
  9455. */
  9456. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9457. if (newFrame === void 0) { newFrame = true; }
  9458. if (!PerfCounter.Enabled) {
  9459. return;
  9460. }
  9461. if (newFrame) {
  9462. this.fetchNewFrame();
  9463. }
  9464. var currentTime = Tools.Now;
  9465. this._current = currentTime - this._startMonitoringTime;
  9466. if (newFrame) {
  9467. this._fetchResult();
  9468. }
  9469. };
  9470. PerfCounter.prototype._fetchResult = function () {
  9471. this._totalAccumulated += this._current;
  9472. this._lastSecAccumulated += this._current;
  9473. // Min/Max update
  9474. this._min = Math.min(this._min, this._current);
  9475. this._max = Math.max(this._max, this._current);
  9476. this._average = this._totalAccumulated / this._totalValueCount;
  9477. // Reset last sec?
  9478. var now = Tools.Now;
  9479. if ((now - this._lastSecTime) > 1000) {
  9480. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9481. this._lastSecTime = now;
  9482. this._lastSecAccumulated = 0;
  9483. this._lastSecValueCount = 0;
  9484. }
  9485. };
  9486. PerfCounter.Enabled = true;
  9487. return PerfCounter;
  9488. }());
  9489. BABYLON.PerfCounter = PerfCounter;
  9490. /**
  9491. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9492. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9493. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9494. * @param name The name of the class, case should be preserved
  9495. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9496. */
  9497. function className(name, module) {
  9498. return function (target) {
  9499. target["__bjsclassName__"] = name;
  9500. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9501. };
  9502. }
  9503. BABYLON.className = className;
  9504. /**
  9505. * An implementation of a loop for asynchronous functions.
  9506. */
  9507. var AsyncLoop = /** @class */ (function () {
  9508. /**
  9509. * Constroctor.
  9510. * @param iterations the number of iterations.
  9511. * @param _fn the function to run each iteration
  9512. * @param _successCallback the callback that will be called upon succesful execution
  9513. * @param offset starting offset.
  9514. */
  9515. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9516. if (offset === void 0) { offset = 0; }
  9517. this.iterations = iterations;
  9518. this._fn = _fn;
  9519. this._successCallback = _successCallback;
  9520. this.index = offset - 1;
  9521. this._done = false;
  9522. }
  9523. /**
  9524. * Execute the next iteration. Must be called after the last iteration was finished.
  9525. */
  9526. AsyncLoop.prototype.executeNext = function () {
  9527. if (!this._done) {
  9528. if (this.index + 1 < this.iterations) {
  9529. ++this.index;
  9530. this._fn(this);
  9531. }
  9532. else {
  9533. this.breakLoop();
  9534. }
  9535. }
  9536. };
  9537. /**
  9538. * Break the loop and run the success callback.
  9539. */
  9540. AsyncLoop.prototype.breakLoop = function () {
  9541. this._done = true;
  9542. this._successCallback();
  9543. };
  9544. /**
  9545. * Helper function
  9546. */
  9547. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9548. if (offset === void 0) { offset = 0; }
  9549. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9550. loop.executeNext();
  9551. return loop;
  9552. };
  9553. /**
  9554. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9555. * @param iterations total number of iterations
  9556. * @param syncedIterations number of synchronous iterations in each async iteration.
  9557. * @param fn the function to call each iteration.
  9558. * @param callback a success call back that will be called when iterating stops.
  9559. * @param breakFunction a break condition (optional)
  9560. * @param timeout timeout settings for the setTimeout function. default - 0.
  9561. * @constructor
  9562. */
  9563. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9564. if (timeout === void 0) { timeout = 0; }
  9565. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9566. if (breakFunction && breakFunction())
  9567. loop.breakLoop();
  9568. else {
  9569. setTimeout(function () {
  9570. for (var i = 0; i < syncedIterations; ++i) {
  9571. var iteration = (loop.index * syncedIterations) + i;
  9572. if (iteration >= iterations)
  9573. break;
  9574. fn(iteration);
  9575. if (breakFunction && breakFunction()) {
  9576. loop.breakLoop();
  9577. break;
  9578. }
  9579. }
  9580. loop.executeNext();
  9581. }, timeout);
  9582. }
  9583. }, callback);
  9584. };
  9585. return AsyncLoop;
  9586. }());
  9587. BABYLON.AsyncLoop = AsyncLoop;
  9588. })(BABYLON || (BABYLON = {}));
  9589. //# sourceMappingURL=babylon.tools.js.map
  9590. var BABYLON;
  9591. (function (BABYLON) {
  9592. var PromiseStates;
  9593. (function (PromiseStates) {
  9594. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9595. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9596. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9597. })(PromiseStates || (PromiseStates = {}));
  9598. var FulFillmentAgregator = /** @class */ (function () {
  9599. function FulFillmentAgregator() {
  9600. this.count = 0;
  9601. this.target = 0;
  9602. this.results = [];
  9603. }
  9604. return FulFillmentAgregator;
  9605. }());
  9606. var InternalPromise = /** @class */ (function () {
  9607. function InternalPromise(resolver) {
  9608. var _this = this;
  9609. this._state = PromiseStates.Pending;
  9610. this._children = new Array();
  9611. this._rejectWasConsumed = false;
  9612. if (!resolver) {
  9613. return;
  9614. }
  9615. try {
  9616. resolver(function (value) {
  9617. _this._resolve(value);
  9618. }, function (reason) {
  9619. _this._reject(reason);
  9620. });
  9621. }
  9622. catch (e) {
  9623. this._reject(e);
  9624. }
  9625. }
  9626. InternalPromise.prototype.catch = function (onRejected) {
  9627. return this.then(undefined, onRejected);
  9628. };
  9629. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9630. var _this = this;
  9631. var newPromise = new InternalPromise();
  9632. newPromise._onFulfilled = onFulfilled;
  9633. newPromise._onRejected = onRejected;
  9634. // Composition
  9635. this._children.push(newPromise);
  9636. if (this._state !== PromiseStates.Pending) {
  9637. BABYLON.Tools.SetImmediate(function () {
  9638. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9639. var returnedValue = newPromise._resolve(_this._result);
  9640. if (returnedValue !== undefined && returnedValue !== null) {
  9641. if (returnedValue._state !== undefined) {
  9642. var returnedPromise = returnedValue;
  9643. newPromise._children.push(returnedPromise);
  9644. newPromise = returnedPromise;
  9645. }
  9646. else {
  9647. newPromise._result = returnedValue;
  9648. }
  9649. }
  9650. }
  9651. else {
  9652. newPromise._reject(_this._reason);
  9653. }
  9654. });
  9655. }
  9656. return newPromise;
  9657. };
  9658. InternalPromise.prototype._moveChildren = function (children) {
  9659. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9660. if (this._state === PromiseStates.Fulfilled) {
  9661. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9662. var child = _b[_i];
  9663. child._resolve(this._result);
  9664. }
  9665. }
  9666. else if (this._state === PromiseStates.Rejected) {
  9667. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9668. var child = _d[_c];
  9669. child._reject(this._reason);
  9670. }
  9671. }
  9672. var _a;
  9673. };
  9674. InternalPromise.prototype._resolve = function (value) {
  9675. try {
  9676. this._state = PromiseStates.Fulfilled;
  9677. this._result = value;
  9678. var returnedValue = null;
  9679. if (this._onFulfilled) {
  9680. returnedValue = this._onFulfilled(value);
  9681. }
  9682. if (returnedValue !== undefined && returnedValue !== null) {
  9683. if (returnedValue._state !== undefined) {
  9684. // Transmit children
  9685. var returnedPromise = returnedValue;
  9686. returnedPromise._moveChildren(this._children);
  9687. }
  9688. else {
  9689. value = returnedValue;
  9690. }
  9691. }
  9692. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9693. var child = _a[_i];
  9694. child._resolve(value);
  9695. }
  9696. this._children.length = 0;
  9697. delete this._onFulfilled;
  9698. delete this._onRejected;
  9699. return returnedValue;
  9700. }
  9701. catch (e) {
  9702. this._reject(e, true);
  9703. }
  9704. return null;
  9705. };
  9706. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9707. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9708. this._state = PromiseStates.Rejected;
  9709. this._reason = reason;
  9710. if (this._onRejected && !onLocalThrow) {
  9711. try {
  9712. this._onRejected(reason);
  9713. this._rejectWasConsumed = true;
  9714. }
  9715. catch (e) {
  9716. reason = e;
  9717. }
  9718. }
  9719. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9720. var child = _a[_i];
  9721. if (this._rejectWasConsumed) {
  9722. child._resolve(null);
  9723. }
  9724. else {
  9725. child._reject(reason);
  9726. }
  9727. }
  9728. this._children.length = 0;
  9729. delete this._onFulfilled;
  9730. delete this._onRejected;
  9731. };
  9732. InternalPromise.resolve = function (value) {
  9733. var newPromise = new InternalPromise();
  9734. newPromise._resolve(value);
  9735. return newPromise;
  9736. };
  9737. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9738. promise.then(function (value) {
  9739. agregator.results[index] = value;
  9740. agregator.count++;
  9741. if (agregator.count === agregator.target) {
  9742. agregator.rootPromise._resolve(agregator.results);
  9743. }
  9744. return null;
  9745. }, function (reason) {
  9746. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9747. agregator.rootPromise._reject(reason);
  9748. }
  9749. });
  9750. };
  9751. InternalPromise.all = function (promises) {
  9752. var newPromise = new InternalPromise();
  9753. var agregator = new FulFillmentAgregator();
  9754. agregator.target = promises.length;
  9755. agregator.rootPromise = newPromise;
  9756. if (promises.length) {
  9757. for (var index = 0; index < promises.length; index++) {
  9758. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9759. }
  9760. }
  9761. else {
  9762. newPromise._resolve([]);
  9763. }
  9764. return newPromise;
  9765. };
  9766. InternalPromise.race = function (promises) {
  9767. var newPromise = new InternalPromise();
  9768. if (promises.length) {
  9769. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9770. var promise = promises_1[_i];
  9771. promise.then(function (value) {
  9772. if (newPromise) {
  9773. newPromise._resolve(value);
  9774. newPromise = null;
  9775. }
  9776. return null;
  9777. }, function (reason) {
  9778. if (newPromise) {
  9779. newPromise._reject(reason);
  9780. newPromise = null;
  9781. }
  9782. });
  9783. }
  9784. }
  9785. return newPromise;
  9786. };
  9787. return InternalPromise;
  9788. }());
  9789. /**
  9790. * Helper class that provides a small promise polyfill
  9791. */
  9792. var PromisePolyfill = /** @class */ (function () {
  9793. function PromisePolyfill() {
  9794. }
  9795. /**
  9796. * Static function used to check if the polyfill is required
  9797. * If this is the case then the function will inject the polyfill to window.Promise
  9798. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9799. */
  9800. PromisePolyfill.Apply = function (force) {
  9801. if (force === void 0) { force = false; }
  9802. if (force || typeof Promise === 'undefined') {
  9803. var root = window;
  9804. root.Promise = InternalPromise;
  9805. }
  9806. };
  9807. return PromisePolyfill;
  9808. }());
  9809. BABYLON.PromisePolyfill = PromisePolyfill;
  9810. })(BABYLON || (BABYLON = {}));
  9811. //# sourceMappingURL=babylon.promise.js.map
  9812. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9813. var BABYLON;
  9814. (function (BABYLON) {
  9815. /**
  9816. * Helper class to push actions to a pool of workers.
  9817. */
  9818. var WorkerPool = /** @class */ (function () {
  9819. /**
  9820. * Constructor
  9821. * @param workers Array of workers to use for actions
  9822. */
  9823. function WorkerPool(workers) {
  9824. this._pendingActions = new Array();
  9825. this._workerInfos = workers.map(function (worker) { return ({
  9826. worker: worker,
  9827. active: false
  9828. }); });
  9829. }
  9830. /**
  9831. * Terminates all workers and clears any pending actions.
  9832. */
  9833. WorkerPool.prototype.dispose = function () {
  9834. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9835. var workerInfo = _a[_i];
  9836. workerInfo.worker.terminate();
  9837. }
  9838. delete this._workerInfos;
  9839. delete this._pendingActions;
  9840. };
  9841. /**
  9842. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9843. * pended until a worker has completed its action.
  9844. * @param action The action to perform. Call onComplete when the action is complete.
  9845. */
  9846. WorkerPool.prototype.push = function (action) {
  9847. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9848. var workerInfo = _a[_i];
  9849. if (!workerInfo.active) {
  9850. this._execute(workerInfo, action);
  9851. return;
  9852. }
  9853. }
  9854. this._pendingActions.push(action);
  9855. };
  9856. WorkerPool.prototype._execute = function (workerInfo, action) {
  9857. var _this = this;
  9858. workerInfo.active = true;
  9859. action(workerInfo.worker, function () {
  9860. workerInfo.active = false;
  9861. var nextAction = _this._pendingActions.shift();
  9862. if (nextAction) {
  9863. _this._execute(workerInfo, nextAction);
  9864. }
  9865. });
  9866. };
  9867. return WorkerPool;
  9868. }());
  9869. BABYLON.WorkerPool = WorkerPool;
  9870. })(BABYLON || (BABYLON = {}));
  9871. //# sourceMappingURL=babylon.workerPool.js.map
  9872. var BABYLON;
  9873. (function (BABYLON) {
  9874. var _AlphaState = /** @class */ (function () {
  9875. /**
  9876. * Initializes the state.
  9877. */
  9878. function _AlphaState() {
  9879. this._isAlphaBlendDirty = false;
  9880. this._isBlendFunctionParametersDirty = false;
  9881. this._isBlendEquationParametersDirty = false;
  9882. this._isBlendConstantsDirty = false;
  9883. this._alphaBlend = false;
  9884. this._blendFunctionParameters = new Array(4);
  9885. this._blendEquationParameters = new Array(2);
  9886. this._blendConstants = new Array(4);
  9887. this.reset();
  9888. }
  9889. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9890. get: function () {
  9891. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9892. },
  9893. enumerable: true,
  9894. configurable: true
  9895. });
  9896. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9897. get: function () {
  9898. return this._alphaBlend;
  9899. },
  9900. set: function (value) {
  9901. if (this._alphaBlend === value) {
  9902. return;
  9903. }
  9904. this._alphaBlend = value;
  9905. this._isAlphaBlendDirty = true;
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9911. if (this._blendConstants[0] === r &&
  9912. this._blendConstants[1] === g &&
  9913. this._blendConstants[2] === b &&
  9914. this._blendConstants[3] === a) {
  9915. return;
  9916. }
  9917. this._blendConstants[0] = r;
  9918. this._blendConstants[1] = g;
  9919. this._blendConstants[2] = b;
  9920. this._blendConstants[3] = a;
  9921. this._isBlendConstantsDirty = true;
  9922. };
  9923. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9924. if (this._blendFunctionParameters[0] === value0 &&
  9925. this._blendFunctionParameters[1] === value1 &&
  9926. this._blendFunctionParameters[2] === value2 &&
  9927. this._blendFunctionParameters[3] === value3) {
  9928. return;
  9929. }
  9930. this._blendFunctionParameters[0] = value0;
  9931. this._blendFunctionParameters[1] = value1;
  9932. this._blendFunctionParameters[2] = value2;
  9933. this._blendFunctionParameters[3] = value3;
  9934. this._isBlendFunctionParametersDirty = true;
  9935. };
  9936. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9937. if (this._blendEquationParameters[0] === rgb &&
  9938. this._blendEquationParameters[1] === alpha) {
  9939. return;
  9940. }
  9941. this._blendEquationParameters[0] = rgb;
  9942. this._blendEquationParameters[1] = alpha;
  9943. this._isBlendEquationParametersDirty = true;
  9944. };
  9945. _AlphaState.prototype.reset = function () {
  9946. this._alphaBlend = false;
  9947. this._blendFunctionParameters[0] = null;
  9948. this._blendFunctionParameters[1] = null;
  9949. this._blendFunctionParameters[2] = null;
  9950. this._blendFunctionParameters[3] = null;
  9951. this._blendEquationParameters[0] = null;
  9952. this._blendEquationParameters[1] = null;
  9953. this._blendConstants[0] = null;
  9954. this._blendConstants[1] = null;
  9955. this._blendConstants[2] = null;
  9956. this._blendConstants[3] = null;
  9957. this._isAlphaBlendDirty = true;
  9958. this._isBlendFunctionParametersDirty = false;
  9959. this._isBlendEquationParametersDirty = false;
  9960. this._isBlendConstantsDirty = false;
  9961. };
  9962. _AlphaState.prototype.apply = function (gl) {
  9963. if (!this.isDirty) {
  9964. return;
  9965. }
  9966. // Alpha blend
  9967. if (this._isAlphaBlendDirty) {
  9968. if (this._alphaBlend) {
  9969. gl.enable(gl.BLEND);
  9970. }
  9971. else {
  9972. gl.disable(gl.BLEND);
  9973. }
  9974. this._isAlphaBlendDirty = false;
  9975. }
  9976. // Alpha function
  9977. if (this._isBlendFunctionParametersDirty) {
  9978. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9979. this._isBlendFunctionParametersDirty = false;
  9980. }
  9981. // Alpha equation
  9982. if (this._isBlendEquationParametersDirty) {
  9983. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9984. this._isBlendEquationParametersDirty = false;
  9985. }
  9986. // Constants
  9987. if (this._isBlendConstantsDirty) {
  9988. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9989. this._isBlendConstantsDirty = false;
  9990. }
  9991. };
  9992. return _AlphaState;
  9993. }());
  9994. BABYLON._AlphaState = _AlphaState;
  9995. })(BABYLON || (BABYLON = {}));
  9996. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9997. var BABYLON;
  9998. (function (BABYLON) {
  9999. var _DepthCullingState = /** @class */ (function () {
  10000. /**
  10001. * Initializes the state.
  10002. */
  10003. function _DepthCullingState() {
  10004. this._isDepthTestDirty = false;
  10005. this._isDepthMaskDirty = false;
  10006. this._isDepthFuncDirty = false;
  10007. this._isCullFaceDirty = false;
  10008. this._isCullDirty = false;
  10009. this._isZOffsetDirty = false;
  10010. this._isFrontFaceDirty = false;
  10011. this.reset();
  10012. }
  10013. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10014. get: function () {
  10015. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10016. },
  10017. enumerable: true,
  10018. configurable: true
  10019. });
  10020. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10021. get: function () {
  10022. return this._zOffset;
  10023. },
  10024. set: function (value) {
  10025. if (this._zOffset === value) {
  10026. return;
  10027. }
  10028. this._zOffset = value;
  10029. this._isZOffsetDirty = true;
  10030. },
  10031. enumerable: true,
  10032. configurable: true
  10033. });
  10034. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10035. get: function () {
  10036. return this._cullFace;
  10037. },
  10038. set: function (value) {
  10039. if (this._cullFace === value) {
  10040. return;
  10041. }
  10042. this._cullFace = value;
  10043. this._isCullFaceDirty = true;
  10044. },
  10045. enumerable: true,
  10046. configurable: true
  10047. });
  10048. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10049. get: function () {
  10050. return this._cull;
  10051. },
  10052. set: function (value) {
  10053. if (this._cull === value) {
  10054. return;
  10055. }
  10056. this._cull = value;
  10057. this._isCullDirty = true;
  10058. },
  10059. enumerable: true,
  10060. configurable: true
  10061. });
  10062. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10063. get: function () {
  10064. return this._depthFunc;
  10065. },
  10066. set: function (value) {
  10067. if (this._depthFunc === value) {
  10068. return;
  10069. }
  10070. this._depthFunc = value;
  10071. this._isDepthFuncDirty = true;
  10072. },
  10073. enumerable: true,
  10074. configurable: true
  10075. });
  10076. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10077. get: function () {
  10078. return this._depthMask;
  10079. },
  10080. set: function (value) {
  10081. if (this._depthMask === value) {
  10082. return;
  10083. }
  10084. this._depthMask = value;
  10085. this._isDepthMaskDirty = true;
  10086. },
  10087. enumerable: true,
  10088. configurable: true
  10089. });
  10090. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10091. get: function () {
  10092. return this._depthTest;
  10093. },
  10094. set: function (value) {
  10095. if (this._depthTest === value) {
  10096. return;
  10097. }
  10098. this._depthTest = value;
  10099. this._isDepthTestDirty = true;
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10105. get: function () {
  10106. return this._frontFace;
  10107. },
  10108. set: function (value) {
  10109. if (this._frontFace === value) {
  10110. return;
  10111. }
  10112. this._frontFace = value;
  10113. this._isFrontFaceDirty = true;
  10114. },
  10115. enumerable: true,
  10116. configurable: true
  10117. });
  10118. _DepthCullingState.prototype.reset = function () {
  10119. this._depthMask = true;
  10120. this._depthTest = true;
  10121. this._depthFunc = null;
  10122. this._cullFace = null;
  10123. this._cull = null;
  10124. this._zOffset = 0;
  10125. this._frontFace = null;
  10126. this._isDepthTestDirty = true;
  10127. this._isDepthMaskDirty = true;
  10128. this._isDepthFuncDirty = false;
  10129. this._isCullFaceDirty = false;
  10130. this._isCullDirty = false;
  10131. this._isZOffsetDirty = false;
  10132. this._isFrontFaceDirty = false;
  10133. };
  10134. _DepthCullingState.prototype.apply = function (gl) {
  10135. if (!this.isDirty) {
  10136. return;
  10137. }
  10138. // Cull
  10139. if (this._isCullDirty) {
  10140. if (this.cull) {
  10141. gl.enable(gl.CULL_FACE);
  10142. }
  10143. else {
  10144. gl.disable(gl.CULL_FACE);
  10145. }
  10146. this._isCullDirty = false;
  10147. }
  10148. // Cull face
  10149. if (this._isCullFaceDirty) {
  10150. gl.cullFace(this.cullFace);
  10151. this._isCullFaceDirty = false;
  10152. }
  10153. // Depth mask
  10154. if (this._isDepthMaskDirty) {
  10155. gl.depthMask(this.depthMask);
  10156. this._isDepthMaskDirty = false;
  10157. }
  10158. // Depth test
  10159. if (this._isDepthTestDirty) {
  10160. if (this.depthTest) {
  10161. gl.enable(gl.DEPTH_TEST);
  10162. }
  10163. else {
  10164. gl.disable(gl.DEPTH_TEST);
  10165. }
  10166. this._isDepthTestDirty = false;
  10167. }
  10168. // Depth func
  10169. if (this._isDepthFuncDirty) {
  10170. gl.depthFunc(this.depthFunc);
  10171. this._isDepthFuncDirty = false;
  10172. }
  10173. // zOffset
  10174. if (this._isZOffsetDirty) {
  10175. if (this.zOffset) {
  10176. gl.enable(gl.POLYGON_OFFSET_FILL);
  10177. gl.polygonOffset(this.zOffset, 0);
  10178. }
  10179. else {
  10180. gl.disable(gl.POLYGON_OFFSET_FILL);
  10181. }
  10182. this._isZOffsetDirty = false;
  10183. }
  10184. // Front face
  10185. if (this._isFrontFaceDirty) {
  10186. gl.frontFace(this.frontFace);
  10187. this._isFrontFaceDirty = false;
  10188. }
  10189. };
  10190. return _DepthCullingState;
  10191. }());
  10192. BABYLON._DepthCullingState = _DepthCullingState;
  10193. })(BABYLON || (BABYLON = {}));
  10194. //# sourceMappingURL=babylon.depthCullingState.js.map
  10195. var BABYLON;
  10196. (function (BABYLON) {
  10197. var _StencilState = /** @class */ (function () {
  10198. function _StencilState() {
  10199. this._isStencilTestDirty = false;
  10200. this._isStencilMaskDirty = false;
  10201. this._isStencilFuncDirty = false;
  10202. this._isStencilOpDirty = false;
  10203. this.reset();
  10204. }
  10205. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10206. get: function () {
  10207. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10208. },
  10209. enumerable: true,
  10210. configurable: true
  10211. });
  10212. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10213. get: function () {
  10214. return this._stencilFunc;
  10215. },
  10216. set: function (value) {
  10217. if (this._stencilFunc === value) {
  10218. return;
  10219. }
  10220. this._stencilFunc = value;
  10221. this._isStencilFuncDirty = true;
  10222. },
  10223. enumerable: true,
  10224. configurable: true
  10225. });
  10226. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10227. get: function () {
  10228. return this._stencilFuncRef;
  10229. },
  10230. set: function (value) {
  10231. if (this._stencilFuncRef === value) {
  10232. return;
  10233. }
  10234. this._stencilFuncRef = value;
  10235. this._isStencilFuncDirty = true;
  10236. },
  10237. enumerable: true,
  10238. configurable: true
  10239. });
  10240. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10241. get: function () {
  10242. return this._stencilFuncMask;
  10243. },
  10244. set: function (value) {
  10245. if (this._stencilFuncMask === value) {
  10246. return;
  10247. }
  10248. this._stencilFuncMask = value;
  10249. this._isStencilFuncDirty = true;
  10250. },
  10251. enumerable: true,
  10252. configurable: true
  10253. });
  10254. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10255. get: function () {
  10256. return this._stencilOpStencilFail;
  10257. },
  10258. set: function (value) {
  10259. if (this._stencilOpStencilFail === value) {
  10260. return;
  10261. }
  10262. this._stencilOpStencilFail = value;
  10263. this._isStencilOpDirty = true;
  10264. },
  10265. enumerable: true,
  10266. configurable: true
  10267. });
  10268. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10269. get: function () {
  10270. return this._stencilOpDepthFail;
  10271. },
  10272. set: function (value) {
  10273. if (this._stencilOpDepthFail === value) {
  10274. return;
  10275. }
  10276. this._stencilOpDepthFail = value;
  10277. this._isStencilOpDirty = true;
  10278. },
  10279. enumerable: true,
  10280. configurable: true
  10281. });
  10282. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10283. get: function () {
  10284. return this._stencilOpStencilDepthPass;
  10285. },
  10286. set: function (value) {
  10287. if (this._stencilOpStencilDepthPass === value) {
  10288. return;
  10289. }
  10290. this._stencilOpStencilDepthPass = value;
  10291. this._isStencilOpDirty = true;
  10292. },
  10293. enumerable: true,
  10294. configurable: true
  10295. });
  10296. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10297. get: function () {
  10298. return this._stencilMask;
  10299. },
  10300. set: function (value) {
  10301. if (this._stencilMask === value) {
  10302. return;
  10303. }
  10304. this._stencilMask = value;
  10305. this._isStencilMaskDirty = true;
  10306. },
  10307. enumerable: true,
  10308. configurable: true
  10309. });
  10310. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10311. get: function () {
  10312. return this._stencilTest;
  10313. },
  10314. set: function (value) {
  10315. if (this._stencilTest === value) {
  10316. return;
  10317. }
  10318. this._stencilTest = value;
  10319. this._isStencilTestDirty = true;
  10320. },
  10321. enumerable: true,
  10322. configurable: true
  10323. });
  10324. _StencilState.prototype.reset = function () {
  10325. this._stencilTest = false;
  10326. this._stencilMask = 0xFF;
  10327. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10328. this._stencilFuncRef = 1;
  10329. this._stencilFuncMask = 0xFF;
  10330. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10331. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10332. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10333. this._isStencilTestDirty = true;
  10334. this._isStencilMaskDirty = true;
  10335. this._isStencilFuncDirty = true;
  10336. this._isStencilOpDirty = true;
  10337. };
  10338. _StencilState.prototype.apply = function (gl) {
  10339. if (!this.isDirty) {
  10340. return;
  10341. }
  10342. // Stencil test
  10343. if (this._isStencilTestDirty) {
  10344. if (this.stencilTest) {
  10345. gl.enable(gl.STENCIL_TEST);
  10346. }
  10347. else {
  10348. gl.disable(gl.STENCIL_TEST);
  10349. }
  10350. this._isStencilTestDirty = false;
  10351. }
  10352. // Stencil mask
  10353. if (this._isStencilMaskDirty) {
  10354. gl.stencilMask(this.stencilMask);
  10355. this._isStencilMaskDirty = false;
  10356. }
  10357. // Stencil func
  10358. if (this._isStencilFuncDirty) {
  10359. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10360. this._isStencilFuncDirty = false;
  10361. }
  10362. // Stencil op
  10363. if (this._isStencilOpDirty) {
  10364. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10365. this._isStencilOpDirty = false;
  10366. }
  10367. };
  10368. return _StencilState;
  10369. }());
  10370. BABYLON._StencilState = _StencilState;
  10371. })(BABYLON || (BABYLON = {}));
  10372. //# sourceMappingURL=babylon.stencilState.js.map
  10373. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10374. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10375. s = arguments[i];
  10376. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10377. t[p] = s[p];
  10378. }
  10379. return t;
  10380. };
  10381. var BABYLON;
  10382. (function (BABYLON) {
  10383. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10384. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10385. };
  10386. var compileRawShader = function (gl, source, type) {
  10387. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10388. gl.shaderSource(shader, source);
  10389. gl.compileShader(shader);
  10390. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10391. var log = gl.getShaderInfoLog(shader);
  10392. if (log) {
  10393. throw new Error(log);
  10394. }
  10395. }
  10396. if (!shader) {
  10397. throw new Error("Something went wrong while compile the shader.");
  10398. }
  10399. return shader;
  10400. };
  10401. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10402. var magFilter = gl.NEAREST;
  10403. var minFilter = gl.NEAREST;
  10404. switch (samplingMode) {
  10405. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10406. magFilter = gl.LINEAR;
  10407. if (generateMipMaps) {
  10408. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10409. }
  10410. else {
  10411. minFilter = gl.LINEAR;
  10412. }
  10413. break;
  10414. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10415. magFilter = gl.LINEAR;
  10416. if (generateMipMaps) {
  10417. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10418. }
  10419. else {
  10420. minFilter = gl.LINEAR;
  10421. }
  10422. break;
  10423. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10424. magFilter = gl.NEAREST;
  10425. if (generateMipMaps) {
  10426. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10427. }
  10428. else {
  10429. minFilter = gl.NEAREST;
  10430. }
  10431. break;
  10432. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10433. magFilter = gl.NEAREST;
  10434. if (generateMipMaps) {
  10435. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10436. }
  10437. else {
  10438. minFilter = gl.NEAREST;
  10439. }
  10440. break;
  10441. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10442. magFilter = gl.NEAREST;
  10443. if (generateMipMaps) {
  10444. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10445. }
  10446. else {
  10447. minFilter = gl.LINEAR;
  10448. }
  10449. break;
  10450. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10451. magFilter = gl.NEAREST;
  10452. if (generateMipMaps) {
  10453. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10454. }
  10455. else {
  10456. minFilter = gl.LINEAR;
  10457. }
  10458. break;
  10459. case BABYLON.Texture.NEAREST_LINEAR:
  10460. magFilter = gl.NEAREST;
  10461. minFilter = gl.LINEAR;
  10462. break;
  10463. case BABYLON.Texture.NEAREST_NEAREST:
  10464. magFilter = gl.NEAREST;
  10465. minFilter = gl.NEAREST;
  10466. break;
  10467. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10468. magFilter = gl.LINEAR;
  10469. if (generateMipMaps) {
  10470. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10471. }
  10472. else {
  10473. minFilter = gl.NEAREST;
  10474. }
  10475. break;
  10476. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10477. magFilter = gl.LINEAR;
  10478. if (generateMipMaps) {
  10479. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10480. }
  10481. else {
  10482. minFilter = gl.NEAREST;
  10483. }
  10484. break;
  10485. case BABYLON.Texture.LINEAR_LINEAR:
  10486. magFilter = gl.LINEAR;
  10487. minFilter = gl.LINEAR;
  10488. break;
  10489. case BABYLON.Texture.LINEAR_NEAREST:
  10490. magFilter = gl.LINEAR;
  10491. minFilter = gl.NEAREST;
  10492. break;
  10493. }
  10494. return {
  10495. min: minFilter,
  10496. mag: magFilter
  10497. };
  10498. };
  10499. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10500. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10501. var img;
  10502. var onload = function () {
  10503. loadedImages[index] = img;
  10504. loadedImages._internalCount++;
  10505. if (scene) {
  10506. scene._removePendingData(img);
  10507. }
  10508. if (loadedImages._internalCount === 6) {
  10509. onfinish(loadedImages);
  10510. }
  10511. };
  10512. var onerror = function (message, exception) {
  10513. if (scene) {
  10514. scene._removePendingData(img);
  10515. }
  10516. if (onErrorCallBack) {
  10517. onErrorCallBack(message, exception);
  10518. }
  10519. };
  10520. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10521. if (scene) {
  10522. scene._addPendingData(img);
  10523. }
  10524. };
  10525. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10526. if (onError === void 0) { onError = null; }
  10527. var loadedImages = [];
  10528. loadedImages._internalCount = 0;
  10529. for (var index = 0; index < 6; index++) {
  10530. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10531. }
  10532. };
  10533. var BufferPointer = /** @class */ (function () {
  10534. function BufferPointer() {
  10535. }
  10536. return BufferPointer;
  10537. }());
  10538. var InstancingAttributeInfo = /** @class */ (function () {
  10539. function InstancingAttributeInfo() {
  10540. }
  10541. return InstancingAttributeInfo;
  10542. }());
  10543. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10544. /**
  10545. * Define options used to create a render target texture
  10546. */
  10547. var RenderTargetCreationOptions = /** @class */ (function () {
  10548. function RenderTargetCreationOptions() {
  10549. }
  10550. return RenderTargetCreationOptions;
  10551. }());
  10552. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10553. /**
  10554. * Define options used to create a depth texture
  10555. */
  10556. var DepthTextureCreationOptions = /** @class */ (function () {
  10557. function DepthTextureCreationOptions() {
  10558. }
  10559. return DepthTextureCreationOptions;
  10560. }());
  10561. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10562. /**
  10563. * Regroup several parameters relative to the browser in use
  10564. */
  10565. var EngineCapabilities = /** @class */ (function () {
  10566. function EngineCapabilities() {
  10567. }
  10568. return EngineCapabilities;
  10569. }());
  10570. BABYLON.EngineCapabilities = EngineCapabilities;
  10571. /**
  10572. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10573. */
  10574. var Engine = /** @class */ (function () {
  10575. /**
  10576. * @constructor
  10577. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10578. * @param antialias defines enable antialiasing (default: false)
  10579. * @param options defines further options to be sent to the getContext() function
  10580. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10581. */
  10582. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10583. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10584. var _this = this;
  10585. // Public members
  10586. this.forcePOTTextures = false;
  10587. this.isFullscreen = false;
  10588. this.isPointerLock = false;
  10589. this.cullBackFaces = true;
  10590. this.renderEvenInBackground = true;
  10591. this.preventCacheWipeBetweenFrames = false;
  10592. // To enable/disable IDB support and avoid XHR on .manifest
  10593. this.enableOfflineSupport = false;
  10594. this.scenes = new Array();
  10595. this.postProcesses = new Array();
  10596. // Observables
  10597. /**
  10598. * Observable event triggered each time the rendering canvas is resized
  10599. */
  10600. this.onResizeObservable = new BABYLON.Observable();
  10601. /**
  10602. * Observable event triggered each time the canvas loses focus
  10603. */
  10604. this.onCanvasBlurObservable = new BABYLON.Observable();
  10605. /**
  10606. * Observable event triggered each time the canvas gains focus
  10607. */
  10608. this.onCanvasFocusObservable = new BABYLON.Observable();
  10609. /**
  10610. * Observable event triggered each time the canvas receives pointerout event
  10611. */
  10612. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10613. /**
  10614. * Observable event triggered before each texture is initialized
  10615. */
  10616. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10617. //WebVR
  10618. this._vrDisplay = undefined;
  10619. this._vrSupported = false;
  10620. this._vrExclusivePointerMode = false;
  10621. // Uniform buffers list
  10622. this.disableUniformBuffers = false;
  10623. this._uniformBuffers = new Array();
  10624. // Observables
  10625. /**
  10626. * Observable raised when the engine begins a new frame
  10627. */
  10628. this.onBeginFrameObservable = new BABYLON.Observable();
  10629. /**
  10630. * Observable raised when the engine ends the current frame
  10631. */
  10632. this.onEndFrameObservable = new BABYLON.Observable();
  10633. /**
  10634. * Observable raised when the engine is about to compile a shader
  10635. */
  10636. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10637. /**
  10638. * Observable raised when the engine has jsut compiled a shader
  10639. */
  10640. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10641. this._windowIsBackground = false;
  10642. this._webGLVersion = 1.0;
  10643. this._badOS = false;
  10644. this._badDesktopOS = false;
  10645. /**
  10646. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10647. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10648. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10649. */
  10650. this.disableTextureBindingOptimization = false;
  10651. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10652. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10653. this.onVRRequestPresentStart = new BABYLON.Observable();
  10654. this._colorWrite = true;
  10655. this._drawCalls = new BABYLON.PerfCounter();
  10656. this._textureCollisions = new BABYLON.PerfCounter();
  10657. this._renderingQueueLaunched = false;
  10658. this._activeRenderLoops = new Array();
  10659. // Deterministic lockstepMaxSteps
  10660. this._deterministicLockstep = false;
  10661. this._lockstepMaxSteps = 4;
  10662. // Lost context
  10663. this.onContextLostObservable = new BABYLON.Observable();
  10664. this.onContextRestoredObservable = new BABYLON.Observable();
  10665. this._contextWasLost = false;
  10666. this._doNotHandleContextLost = false;
  10667. // FPS
  10668. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10669. this._fps = 60;
  10670. this._deltaTime = 0;
  10671. /**
  10672. * Turn this value on if you want to pause FPS computation when in background
  10673. */
  10674. this.disablePerformanceMonitorInBackground = false;
  10675. // States
  10676. this._depthCullingState = new BABYLON._DepthCullingState();
  10677. this._stencilState = new BABYLON._StencilState();
  10678. this._alphaState = new BABYLON._AlphaState();
  10679. this._alphaMode = Engine.ALPHA_DISABLE;
  10680. // Cache
  10681. this._internalTexturesCache = new Array();
  10682. this._activeChannel = 0;
  10683. this._currentTextureChannel = -1;
  10684. this._boundTexturesCache = {};
  10685. this._compiledEffects = {};
  10686. this._vertexAttribArraysEnabled = [];
  10687. this._uintIndicesCurrentlySet = false;
  10688. this._currentBoundBuffer = new Array();
  10689. this._currentBufferPointers = new Array();
  10690. this._currentInstanceLocations = new Array();
  10691. this._currentInstanceBuffers = new Array();
  10692. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10693. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10694. this._vaoRecordInProgress = false;
  10695. this._mustWipeVertexAttributes = false;
  10696. this._nextFreeTextureSlots = new Array();
  10697. this._maxSimultaneousTextures = 0;
  10698. this._activeRequests = new Array();
  10699. // Hardware supported Compressed Textures
  10700. this._texturesSupported = new Array();
  10701. this._onVRFullScreenTriggered = function () {
  10702. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10703. //get the old size before we change
  10704. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10705. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10706. //get the width and height, change the render size
  10707. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10708. _this.setHardwareScalingLevel(1);
  10709. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10710. }
  10711. else {
  10712. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10713. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10714. }
  10715. };
  10716. this._boundUniforms = {};
  10717. // Register promises
  10718. BABYLON.PromisePolyfill.Apply();
  10719. var canvas = null;
  10720. Engine.Instances.push(this);
  10721. if (!canvasOrContext) {
  10722. return;
  10723. }
  10724. options = options || {};
  10725. if (canvasOrContext.getContext) {
  10726. canvas = canvasOrContext;
  10727. this._renderingCanvas = canvas;
  10728. if (antialias != null) {
  10729. options.antialias = antialias;
  10730. }
  10731. if (options.deterministicLockstep === undefined) {
  10732. options.deterministicLockstep = false;
  10733. }
  10734. if (options.lockstepMaxSteps === undefined) {
  10735. options.lockstepMaxSteps = 4;
  10736. }
  10737. if (options.preserveDrawingBuffer === undefined) {
  10738. options.preserveDrawingBuffer = false;
  10739. }
  10740. if (options.audioEngine === undefined) {
  10741. options.audioEngine = true;
  10742. }
  10743. if (options.stencil === undefined) {
  10744. options.stencil = true;
  10745. }
  10746. this._deterministicLockstep = options.deterministicLockstep;
  10747. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10748. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10749. // Exceptions
  10750. if (navigator && navigator.userAgent) {
  10751. var ua = navigator.userAgent;
  10752. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10753. var exception = _a[_i];
  10754. var key = exception.key;
  10755. var targets = exception.targets;
  10756. if (ua.indexOf(key) > -1) {
  10757. if (exception.capture && exception.captureConstraint) {
  10758. var capture = exception.capture;
  10759. var constraint = exception.captureConstraint;
  10760. var regex = new RegExp(capture);
  10761. var matches = regex.exec(ua);
  10762. if (matches && matches.length > 0) {
  10763. var capturedValue = parseInt(matches[matches.length - 1]);
  10764. if (capturedValue >= constraint) {
  10765. continue;
  10766. }
  10767. }
  10768. }
  10769. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10770. var target = targets_1[_b];
  10771. switch (target) {
  10772. case "uniformBuffer":
  10773. this.disableUniformBuffers = true;
  10774. break;
  10775. case "textureBindingOptimization":
  10776. this.disableTextureBindingOptimization = true;
  10777. break;
  10778. }
  10779. }
  10780. }
  10781. }
  10782. }
  10783. // GL
  10784. if (!options.disableWebGL2Support) {
  10785. try {
  10786. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10787. if (this._gl) {
  10788. this._webGLVersion = 2.0;
  10789. }
  10790. }
  10791. catch (e) {
  10792. // Do nothing
  10793. }
  10794. }
  10795. if (!this._gl) {
  10796. if (!canvas) {
  10797. throw new Error("The provided canvas is null or undefined.");
  10798. }
  10799. try {
  10800. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10801. }
  10802. catch (e) {
  10803. throw new Error("WebGL not supported");
  10804. }
  10805. }
  10806. if (!this._gl) {
  10807. throw new Error("WebGL not supported");
  10808. }
  10809. this._onCanvasFocus = function () {
  10810. _this.onCanvasFocusObservable.notifyObservers(_this);
  10811. };
  10812. this._onCanvasBlur = function () {
  10813. _this.onCanvasBlurObservable.notifyObservers(_this);
  10814. };
  10815. canvas.addEventListener("focus", this._onCanvasFocus);
  10816. canvas.addEventListener("blur", this._onCanvasBlur);
  10817. this._onBlur = function () {
  10818. if (_this.disablePerformanceMonitorInBackground) {
  10819. _this._performanceMonitor.disable();
  10820. }
  10821. _this._windowIsBackground = true;
  10822. };
  10823. this._onFocus = function () {
  10824. if (_this.disablePerformanceMonitorInBackground) {
  10825. _this._performanceMonitor.enable();
  10826. }
  10827. _this._windowIsBackground = false;
  10828. };
  10829. this._onCanvasPointerOut = function (ev) {
  10830. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10831. };
  10832. window.addEventListener("blur", this._onBlur);
  10833. window.addEventListener("focus", this._onFocus);
  10834. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10835. // Context lost
  10836. if (!this._doNotHandleContextLost) {
  10837. this._onContextLost = function (evt) {
  10838. evt.preventDefault();
  10839. _this._contextWasLost = true;
  10840. BABYLON.Tools.Warn("WebGL context lost.");
  10841. _this.onContextLostObservable.notifyObservers(_this);
  10842. };
  10843. this._onContextRestored = function (evt) {
  10844. // Adding a timeout to avoid race condition at browser level
  10845. setTimeout(function () {
  10846. // Rebuild gl context
  10847. _this._initGLContext();
  10848. // Rebuild effects
  10849. _this._rebuildEffects();
  10850. // Rebuild textures
  10851. _this._rebuildInternalTextures();
  10852. // Rebuild buffers
  10853. _this._rebuildBuffers();
  10854. // Cache
  10855. _this.wipeCaches(true);
  10856. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10857. _this.onContextRestoredObservable.notifyObservers(_this);
  10858. _this._contextWasLost = false;
  10859. }, 0);
  10860. };
  10861. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10862. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10863. }
  10864. }
  10865. else {
  10866. this._gl = canvasOrContext;
  10867. this._renderingCanvas = this._gl.canvas;
  10868. if (this._gl.renderbufferStorageMultisample) {
  10869. this._webGLVersion = 2.0;
  10870. }
  10871. options.stencil = this._gl.getContextAttributes().stencil;
  10872. }
  10873. // Viewport
  10874. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10875. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10876. this.resize();
  10877. this._isStencilEnable = options.stencil ? true : false;
  10878. this._initGLContext();
  10879. if (canvas) {
  10880. // Fullscreen
  10881. this._onFullscreenChange = function () {
  10882. if (document.fullscreen !== undefined) {
  10883. _this.isFullscreen = document.fullscreen;
  10884. }
  10885. else if (document.mozFullScreen !== undefined) {
  10886. _this.isFullscreen = document.mozFullScreen;
  10887. }
  10888. else if (document.webkitIsFullScreen !== undefined) {
  10889. _this.isFullscreen = document.webkitIsFullScreen;
  10890. }
  10891. else if (document.msIsFullScreen !== undefined) {
  10892. _this.isFullscreen = document.msIsFullScreen;
  10893. }
  10894. // Pointer lock
  10895. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10896. canvas.requestPointerLock = canvas.requestPointerLock ||
  10897. canvas.msRequestPointerLock ||
  10898. canvas.mozRequestPointerLock ||
  10899. canvas.webkitRequestPointerLock;
  10900. if (canvas.requestPointerLock) {
  10901. canvas.requestPointerLock();
  10902. }
  10903. }
  10904. };
  10905. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10906. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10907. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10908. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10909. // Pointer lock
  10910. this._onPointerLockChange = function () {
  10911. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10912. document.webkitPointerLockElement === canvas ||
  10913. document.msPointerLockElement === canvas ||
  10914. document.pointerLockElement === canvas);
  10915. };
  10916. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10917. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10918. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10919. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10920. this._onVRDisplayPointerRestricted = function () {
  10921. if (canvas) {
  10922. canvas.requestPointerLock();
  10923. }
  10924. };
  10925. this._onVRDisplayPointerUnrestricted = function () {
  10926. document.exitPointerLock();
  10927. };
  10928. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10929. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10930. }
  10931. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10932. Engine.audioEngine = new BABYLON.AudioEngine();
  10933. }
  10934. // Prepare buffer pointers
  10935. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10936. this._currentBufferPointers[i] = new BufferPointer();
  10937. }
  10938. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10939. // Load WebVR Devices
  10940. if (options.autoEnableWebVR) {
  10941. this.initWebVR();
  10942. }
  10943. // Detect if we are running on a faulty buggy OS.
  10944. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10945. // Detect if we are running on a faulty buggy desktop OS.
  10946. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10947. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10948. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10949. }
  10950. Object.defineProperty(Engine, "LastCreatedEngine", {
  10951. get: function () {
  10952. if (Engine.Instances.length === 0) {
  10953. return null;
  10954. }
  10955. return Engine.Instances[Engine.Instances.length - 1];
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(Engine, "LastCreatedScene", {
  10961. get: function () {
  10962. var lastCreatedEngine = Engine.LastCreatedEngine;
  10963. if (!lastCreatedEngine) {
  10964. return null;
  10965. }
  10966. if (lastCreatedEngine.scenes.length === 0) {
  10967. return null;
  10968. }
  10969. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. /**
  10975. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10976. */
  10977. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10978. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10979. var engine = Engine.Instances[engineIndex];
  10980. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10981. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10982. }
  10983. }
  10984. };
  10985. Object.defineProperty(Engine, "NEVER", {
  10986. get: function () {
  10987. return Engine._NEVER;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(Engine, "ALWAYS", {
  10993. get: function () {
  10994. return Engine._ALWAYS;
  10995. },
  10996. enumerable: true,
  10997. configurable: true
  10998. });
  10999. Object.defineProperty(Engine, "LESS", {
  11000. get: function () {
  11001. return Engine._LESS;
  11002. },
  11003. enumerable: true,
  11004. configurable: true
  11005. });
  11006. Object.defineProperty(Engine, "EQUAL", {
  11007. get: function () {
  11008. return Engine._EQUAL;
  11009. },
  11010. enumerable: true,
  11011. configurable: true
  11012. });
  11013. Object.defineProperty(Engine, "LEQUAL", {
  11014. get: function () {
  11015. return Engine._LEQUAL;
  11016. },
  11017. enumerable: true,
  11018. configurable: true
  11019. });
  11020. Object.defineProperty(Engine, "GREATER", {
  11021. get: function () {
  11022. return Engine._GREATER;
  11023. },
  11024. enumerable: true,
  11025. configurable: true
  11026. });
  11027. Object.defineProperty(Engine, "GEQUAL", {
  11028. get: function () {
  11029. return Engine._GEQUAL;
  11030. },
  11031. enumerable: true,
  11032. configurable: true
  11033. });
  11034. Object.defineProperty(Engine, "NOTEQUAL", {
  11035. get: function () {
  11036. return Engine._NOTEQUAL;
  11037. },
  11038. enumerable: true,
  11039. configurable: true
  11040. });
  11041. Object.defineProperty(Engine, "KEEP", {
  11042. get: function () {
  11043. return Engine._KEEP;
  11044. },
  11045. enumerable: true,
  11046. configurable: true
  11047. });
  11048. Object.defineProperty(Engine, "REPLACE", {
  11049. get: function () {
  11050. return Engine._REPLACE;
  11051. },
  11052. enumerable: true,
  11053. configurable: true
  11054. });
  11055. Object.defineProperty(Engine, "INCR", {
  11056. get: function () {
  11057. return Engine._INCR;
  11058. },
  11059. enumerable: true,
  11060. configurable: true
  11061. });
  11062. Object.defineProperty(Engine, "DECR", {
  11063. get: function () {
  11064. return Engine._DECR;
  11065. },
  11066. enumerable: true,
  11067. configurable: true
  11068. });
  11069. Object.defineProperty(Engine, "INVERT", {
  11070. get: function () {
  11071. return Engine._INVERT;
  11072. },
  11073. enumerable: true,
  11074. configurable: true
  11075. });
  11076. Object.defineProperty(Engine, "INCR_WRAP", {
  11077. get: function () {
  11078. return Engine._INCR_WRAP;
  11079. },
  11080. enumerable: true,
  11081. configurable: true
  11082. });
  11083. Object.defineProperty(Engine, "DECR_WRAP", {
  11084. get: function () {
  11085. return Engine._DECR_WRAP;
  11086. },
  11087. enumerable: true,
  11088. configurable: true
  11089. });
  11090. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11091. get: function () {
  11092. return Engine._ALPHA_DISABLE;
  11093. },
  11094. enumerable: true,
  11095. configurable: true
  11096. });
  11097. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11098. get: function () {
  11099. return Engine._ALPHA_ONEONE;
  11100. },
  11101. enumerable: true,
  11102. configurable: true
  11103. });
  11104. Object.defineProperty(Engine, "ALPHA_ADD", {
  11105. get: function () {
  11106. return Engine._ALPHA_ADD;
  11107. },
  11108. enumerable: true,
  11109. configurable: true
  11110. });
  11111. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11112. get: function () {
  11113. return Engine._ALPHA_COMBINE;
  11114. },
  11115. enumerable: true,
  11116. configurable: true
  11117. });
  11118. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11119. get: function () {
  11120. return Engine._ALPHA_SUBTRACT;
  11121. },
  11122. enumerable: true,
  11123. configurable: true
  11124. });
  11125. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11126. get: function () {
  11127. return Engine._ALPHA_MULTIPLY;
  11128. },
  11129. enumerable: true,
  11130. configurable: true
  11131. });
  11132. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11133. get: function () {
  11134. return Engine._ALPHA_MAXIMIZED;
  11135. },
  11136. enumerable: true,
  11137. configurable: true
  11138. });
  11139. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11140. get: function () {
  11141. return Engine._ALPHA_PREMULTIPLIED;
  11142. },
  11143. enumerable: true,
  11144. configurable: true
  11145. });
  11146. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11147. get: function () {
  11148. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11149. },
  11150. enumerable: true,
  11151. configurable: true
  11152. });
  11153. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11154. get: function () {
  11155. return Engine._ALPHA_INTERPOLATE;
  11156. },
  11157. enumerable: true,
  11158. configurable: true
  11159. });
  11160. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11161. get: function () {
  11162. return Engine._ALPHA_SCREENMODE;
  11163. },
  11164. enumerable: true,
  11165. configurable: true
  11166. });
  11167. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11168. get: function () {
  11169. return Engine._DELAYLOADSTATE_NONE;
  11170. },
  11171. enumerable: true,
  11172. configurable: true
  11173. });
  11174. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11175. get: function () {
  11176. return Engine._DELAYLOADSTATE_LOADED;
  11177. },
  11178. enumerable: true,
  11179. configurable: true
  11180. });
  11181. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11182. get: function () {
  11183. return Engine._DELAYLOADSTATE_LOADING;
  11184. },
  11185. enumerable: true,
  11186. configurable: true
  11187. });
  11188. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11189. get: function () {
  11190. return Engine._DELAYLOADSTATE_NOTLOADED;
  11191. },
  11192. enumerable: true,
  11193. configurable: true
  11194. });
  11195. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11196. get: function () {
  11197. return Engine._TEXTUREFORMAT_ALPHA;
  11198. },
  11199. enumerable: true,
  11200. configurable: true
  11201. });
  11202. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11203. get: function () {
  11204. return Engine._TEXTUREFORMAT_LUMINANCE;
  11205. },
  11206. enumerable: true,
  11207. configurable: true
  11208. });
  11209. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11210. /**
  11211. * R32F
  11212. */
  11213. get: function () {
  11214. return Engine._TEXTUREFORMAT_R32F;
  11215. },
  11216. enumerable: true,
  11217. configurable: true
  11218. });
  11219. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11220. /**
  11221. * RG32F
  11222. */
  11223. get: function () {
  11224. return Engine._TEXTUREFORMAT_RG32F;
  11225. },
  11226. enumerable: true,
  11227. configurable: true
  11228. });
  11229. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11230. /**
  11231. * RGB32F
  11232. */
  11233. get: function () {
  11234. return Engine._TEXTUREFORMAT_RGB32F;
  11235. },
  11236. enumerable: true,
  11237. configurable: true
  11238. });
  11239. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11240. /**
  11241. * RGBA32F
  11242. */
  11243. get: function () {
  11244. return Engine._TEXTUREFORMAT_RGBA32F;
  11245. },
  11246. enumerable: true,
  11247. configurable: true
  11248. });
  11249. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11250. get: function () {
  11251. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11257. get: function () {
  11258. return Engine._TEXTUREFORMAT_RGB;
  11259. },
  11260. enumerable: true,
  11261. configurable: true
  11262. });
  11263. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11264. get: function () {
  11265. return Engine._TEXTUREFORMAT_RGBA;
  11266. },
  11267. enumerable: true,
  11268. configurable: true
  11269. });
  11270. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11271. get: function () {
  11272. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11273. },
  11274. enumerable: true,
  11275. configurable: true
  11276. });
  11277. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11278. get: function () {
  11279. return Engine._TEXTURETYPE_FLOAT;
  11280. },
  11281. enumerable: true,
  11282. configurable: true
  11283. });
  11284. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11285. get: function () {
  11286. return Engine._TEXTURETYPE_HALF_FLOAT;
  11287. },
  11288. enumerable: true,
  11289. configurable: true
  11290. });
  11291. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11292. get: function () {
  11293. return Engine._SCALEMODE_FLOOR;
  11294. },
  11295. enumerable: true,
  11296. configurable: true
  11297. });
  11298. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11299. get: function () {
  11300. return Engine._SCALEMODE_NEAREST;
  11301. },
  11302. enumerable: true,
  11303. configurable: true
  11304. });
  11305. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11306. get: function () {
  11307. return Engine._SCALEMODE_CEILING;
  11308. },
  11309. enumerable: true,
  11310. configurable: true
  11311. });
  11312. Object.defineProperty(Engine, "Version", {
  11313. get: function () {
  11314. return "3.2.0-alphaC";
  11315. },
  11316. enumerable: true,
  11317. configurable: true
  11318. });
  11319. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11320. get: function () {
  11321. return this._vrExclusivePointerMode;
  11322. },
  11323. enumerable: true,
  11324. configurable: true
  11325. });
  11326. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11327. get: function () {
  11328. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11329. },
  11330. enumerable: true,
  11331. configurable: true
  11332. });
  11333. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11334. get: function () {
  11335. return this._webGLVersion < 2 || this.forcePOTTextures;
  11336. },
  11337. enumerable: true,
  11338. configurable: true
  11339. });
  11340. Object.defineProperty(Engine.prototype, "badOS", {
  11341. get: function () {
  11342. return this._badOS;
  11343. },
  11344. enumerable: true,
  11345. configurable: true
  11346. });
  11347. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11348. get: function () {
  11349. return this._badDesktopOS;
  11350. },
  11351. enumerable: true,
  11352. configurable: true
  11353. });
  11354. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11355. get: function () {
  11356. return this._performanceMonitor;
  11357. },
  11358. enumerable: true,
  11359. configurable: true
  11360. });
  11361. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11362. get: function () {
  11363. return this._texturesSupported;
  11364. },
  11365. enumerable: true,
  11366. configurable: true
  11367. });
  11368. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11369. get: function () {
  11370. return this._textureFormatInUse;
  11371. },
  11372. enumerable: true,
  11373. configurable: true
  11374. });
  11375. Object.defineProperty(Engine.prototype, "currentViewport", {
  11376. get: function () {
  11377. return this._cachedViewport;
  11378. },
  11379. enumerable: true,
  11380. configurable: true
  11381. });
  11382. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11383. // Empty texture
  11384. get: function () {
  11385. if (!this._emptyTexture) {
  11386. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11387. }
  11388. return this._emptyTexture;
  11389. },
  11390. enumerable: true,
  11391. configurable: true
  11392. });
  11393. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11394. get: function () {
  11395. if (!this._emptyTexture3D) {
  11396. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11397. }
  11398. return this._emptyTexture3D;
  11399. },
  11400. enumerable: true,
  11401. configurable: true
  11402. });
  11403. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11404. get: function () {
  11405. if (!this._emptyCubeTexture) {
  11406. var faceData = new Uint8Array(4);
  11407. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11408. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11409. }
  11410. return this._emptyCubeTexture;
  11411. },
  11412. enumerable: true,
  11413. configurable: true
  11414. });
  11415. Engine.prototype._rebuildInternalTextures = function () {
  11416. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11417. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11418. var internalTexture = currentState_1[_i];
  11419. internalTexture._rebuild();
  11420. }
  11421. };
  11422. Engine.prototype._rebuildEffects = function () {
  11423. for (var key in this._compiledEffects) {
  11424. var effect = this._compiledEffects[key];
  11425. effect._prepareEffect();
  11426. }
  11427. BABYLON.Effect.ResetCache();
  11428. };
  11429. Engine.prototype._rebuildBuffers = function () {
  11430. // Index / Vertex
  11431. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11432. var scene = _a[_i];
  11433. scene.resetCachedMaterial();
  11434. scene._rebuildGeometries();
  11435. scene._rebuildTextures();
  11436. }
  11437. // Uniforms
  11438. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11439. var uniformBuffer = _c[_b];
  11440. uniformBuffer._rebuild();
  11441. }
  11442. };
  11443. Engine.prototype._initGLContext = function () {
  11444. // Caps
  11445. this._caps = new EngineCapabilities();
  11446. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11447. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11448. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11449. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11450. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11451. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11452. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11453. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11454. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11455. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11456. // Infos
  11457. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11458. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11459. if (rendererInfo != null) {
  11460. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11461. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11462. }
  11463. if (!this._glVendor) {
  11464. this._glVendor = "Unknown vendor";
  11465. }
  11466. if (!this._glRenderer) {
  11467. this._glRenderer = "Unknown renderer";
  11468. }
  11469. // Constants
  11470. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11471. if (this._gl.RGBA16F !== 0x881A) {
  11472. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11473. }
  11474. if (this._gl.RGBA32F !== 0x8814) {
  11475. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11476. }
  11477. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11478. this._gl.DEPTH24_STENCIL8 = 35056;
  11479. }
  11480. // Extensions
  11481. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11482. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11483. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11484. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11485. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11486. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11487. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11488. 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');
  11489. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11490. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11491. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11492. this._caps.highPrecisionShaderSupported = true;
  11493. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11494. if (this._caps.timerQuery) {
  11495. if (this._webGLVersion === 1) {
  11496. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11497. }
  11498. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11499. }
  11500. // Checks if some of the format renders first to allow the use of webgl inspector.
  11501. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11502. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11503. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11504. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11505. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11506. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11507. if (this._webGLVersion > 1) {
  11508. this._gl.HALF_FLOAT_OES = 0x140B;
  11509. }
  11510. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11511. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11512. // Draw buffers
  11513. if (this._webGLVersion > 1) {
  11514. this._caps.drawBuffersExtension = true;
  11515. }
  11516. else {
  11517. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11518. if (drawBuffersExtension !== null) {
  11519. this._caps.drawBuffersExtension = true;
  11520. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11521. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11522. for (var i = 0; i < 16; i++) {
  11523. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11524. }
  11525. }
  11526. else {
  11527. this._caps.drawBuffersExtension = false;
  11528. }
  11529. }
  11530. // Depth Texture
  11531. if (this._webGLVersion > 1) {
  11532. this._caps.depthTextureExtension = true;
  11533. }
  11534. else {
  11535. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11536. if (depthTextureExtension != null) {
  11537. this._caps.depthTextureExtension = true;
  11538. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11539. }
  11540. }
  11541. // Vertex array object
  11542. if (this._webGLVersion > 1) {
  11543. this._caps.vertexArrayObject = true;
  11544. }
  11545. else {
  11546. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11547. if (vertexArrayObjectExtension != null) {
  11548. this._caps.vertexArrayObject = true;
  11549. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11550. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11551. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11552. }
  11553. else {
  11554. this._caps.vertexArrayObject = false;
  11555. }
  11556. }
  11557. // Instances count
  11558. if (this._webGLVersion > 1) {
  11559. this._caps.instancedArrays = true;
  11560. }
  11561. else {
  11562. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11563. if (instanceExtension != null) {
  11564. this._caps.instancedArrays = true;
  11565. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11566. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11567. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11568. }
  11569. else {
  11570. this._caps.instancedArrays = false;
  11571. }
  11572. }
  11573. // Intelligently add supported compressed formats in order to check for.
  11574. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11575. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11576. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11577. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11578. if (this._caps.astc)
  11579. this.texturesSupported.push('-astc.ktx');
  11580. if (this._caps.s3tc)
  11581. this.texturesSupported.push('-dxt.ktx');
  11582. if (this._caps.pvrtc)
  11583. this.texturesSupported.push('-pvrtc.ktx');
  11584. if (this._caps.etc2)
  11585. this.texturesSupported.push('-etc2.ktx');
  11586. if (this._caps.etc1)
  11587. this.texturesSupported.push('-etc1.ktx');
  11588. if (this._gl.getShaderPrecisionFormat) {
  11589. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11590. if (highp) {
  11591. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11592. }
  11593. }
  11594. // Depth buffer
  11595. this.setDepthBuffer(true);
  11596. this.setDepthFunctionToLessOrEqual();
  11597. this.setDepthWrite(true);
  11598. // Texture maps
  11599. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11600. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11601. this._nextFreeTextureSlots.push(slot);
  11602. }
  11603. };
  11604. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11605. get: function () {
  11606. return this._webGLVersion;
  11607. },
  11608. enumerable: true,
  11609. configurable: true
  11610. });
  11611. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11612. /**
  11613. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11614. */
  11615. get: function () {
  11616. return this._isStencilEnable;
  11617. },
  11618. enumerable: true,
  11619. configurable: true
  11620. });
  11621. Engine.prototype._prepareWorkingCanvas = function () {
  11622. if (this._workingCanvas) {
  11623. return;
  11624. }
  11625. this._workingCanvas = document.createElement("canvas");
  11626. var context = this._workingCanvas.getContext("2d");
  11627. if (context) {
  11628. this._workingContext = context;
  11629. }
  11630. };
  11631. Engine.prototype.resetTextureCache = function () {
  11632. for (var key in this._boundTexturesCache) {
  11633. var boundTexture = this._boundTexturesCache[key];
  11634. if (boundTexture) {
  11635. this._removeDesignatedSlot(boundTexture);
  11636. }
  11637. this._boundTexturesCache[key] = null;
  11638. }
  11639. if (!this.disableTextureBindingOptimization) {
  11640. this._nextFreeTextureSlots = [];
  11641. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11642. this._nextFreeTextureSlots.push(slot);
  11643. }
  11644. }
  11645. this._currentTextureChannel = -1;
  11646. };
  11647. Engine.prototype.isDeterministicLockStep = function () {
  11648. return this._deterministicLockstep;
  11649. };
  11650. Engine.prototype.getLockstepMaxSteps = function () {
  11651. return this._lockstepMaxSteps;
  11652. };
  11653. Engine.prototype.getGlInfo = function () {
  11654. return {
  11655. vendor: this._glVendor,
  11656. renderer: this._glRenderer,
  11657. version: this._glVersion
  11658. };
  11659. };
  11660. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11661. if (useScreen === void 0) { useScreen = false; }
  11662. var viewport = camera.viewport;
  11663. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11664. };
  11665. Engine.prototype.getRenderWidth = function (useScreen) {
  11666. if (useScreen === void 0) { useScreen = false; }
  11667. if (!useScreen && this._currentRenderTarget) {
  11668. return this._currentRenderTarget.width;
  11669. }
  11670. return this._gl.drawingBufferWidth;
  11671. };
  11672. Engine.prototype.getRenderHeight = function (useScreen) {
  11673. if (useScreen === void 0) { useScreen = false; }
  11674. if (!useScreen && this._currentRenderTarget) {
  11675. return this._currentRenderTarget.height;
  11676. }
  11677. return this._gl.drawingBufferHeight;
  11678. };
  11679. Engine.prototype.getRenderingCanvas = function () {
  11680. return this._renderingCanvas;
  11681. };
  11682. Engine.prototype.getRenderingCanvasClientRect = function () {
  11683. if (!this._renderingCanvas) {
  11684. return null;
  11685. }
  11686. return this._renderingCanvas.getBoundingClientRect();
  11687. };
  11688. Engine.prototype.setHardwareScalingLevel = function (level) {
  11689. this._hardwareScalingLevel = level;
  11690. this.resize();
  11691. };
  11692. Engine.prototype.getHardwareScalingLevel = function () {
  11693. return this._hardwareScalingLevel;
  11694. };
  11695. Engine.prototype.getLoadedTexturesCache = function () {
  11696. return this._internalTexturesCache;
  11697. };
  11698. Engine.prototype.getCaps = function () {
  11699. return this._caps;
  11700. };
  11701. Object.defineProperty(Engine.prototype, "drawCalls", {
  11702. /** The number of draw calls submitted last frame */
  11703. get: function () {
  11704. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11705. return 0;
  11706. },
  11707. enumerable: true,
  11708. configurable: true
  11709. });
  11710. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11711. get: function () {
  11712. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11713. return null;
  11714. },
  11715. enumerable: true,
  11716. configurable: true
  11717. });
  11718. Engine.prototype.getDepthFunction = function () {
  11719. return this._depthCullingState.depthFunc;
  11720. };
  11721. Engine.prototype.setDepthFunction = function (depthFunc) {
  11722. this._depthCullingState.depthFunc = depthFunc;
  11723. };
  11724. Engine.prototype.setDepthFunctionToGreater = function () {
  11725. this._depthCullingState.depthFunc = this._gl.GREATER;
  11726. };
  11727. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11728. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11729. };
  11730. Engine.prototype.setDepthFunctionToLess = function () {
  11731. this._depthCullingState.depthFunc = this._gl.LESS;
  11732. };
  11733. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11734. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11735. };
  11736. Engine.prototype.getStencilBuffer = function () {
  11737. return this._stencilState.stencilTest;
  11738. };
  11739. Engine.prototype.setStencilBuffer = function (enable) {
  11740. this._stencilState.stencilTest = enable;
  11741. };
  11742. Engine.prototype.getStencilMask = function () {
  11743. return this._stencilState.stencilMask;
  11744. };
  11745. Engine.prototype.setStencilMask = function (mask) {
  11746. this._stencilState.stencilMask = mask;
  11747. };
  11748. Engine.prototype.getStencilFunction = function () {
  11749. return this._stencilState.stencilFunc;
  11750. };
  11751. Engine.prototype.getStencilFunctionReference = function () {
  11752. return this._stencilState.stencilFuncRef;
  11753. };
  11754. Engine.prototype.getStencilFunctionMask = function () {
  11755. return this._stencilState.stencilFuncMask;
  11756. };
  11757. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11758. this._stencilState.stencilFunc = stencilFunc;
  11759. };
  11760. Engine.prototype.setStencilFunctionReference = function (reference) {
  11761. this._stencilState.stencilFuncRef = reference;
  11762. };
  11763. Engine.prototype.setStencilFunctionMask = function (mask) {
  11764. this._stencilState.stencilFuncMask = mask;
  11765. };
  11766. Engine.prototype.getStencilOperationFail = function () {
  11767. return this._stencilState.stencilOpStencilFail;
  11768. };
  11769. Engine.prototype.getStencilOperationDepthFail = function () {
  11770. return this._stencilState.stencilOpDepthFail;
  11771. };
  11772. Engine.prototype.getStencilOperationPass = function () {
  11773. return this._stencilState.stencilOpStencilDepthPass;
  11774. };
  11775. Engine.prototype.setStencilOperationFail = function (operation) {
  11776. this._stencilState.stencilOpStencilFail = operation;
  11777. };
  11778. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11779. this._stencilState.stencilOpDepthFail = operation;
  11780. };
  11781. Engine.prototype.setStencilOperationPass = function (operation) {
  11782. this._stencilState.stencilOpStencilDepthPass = operation;
  11783. };
  11784. Engine.prototype.setDitheringState = function (value) {
  11785. if (value) {
  11786. this._gl.enable(this._gl.DITHER);
  11787. }
  11788. else {
  11789. this._gl.disable(this._gl.DITHER);
  11790. }
  11791. };
  11792. Engine.prototype.setRasterizerState = function (value) {
  11793. if (value) {
  11794. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11795. }
  11796. else {
  11797. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11798. }
  11799. };
  11800. /**
  11801. * stop executing a render loop function and remove it from the execution array
  11802. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11803. */
  11804. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11805. if (!renderFunction) {
  11806. this._activeRenderLoops = [];
  11807. return;
  11808. }
  11809. var index = this._activeRenderLoops.indexOf(renderFunction);
  11810. if (index >= 0) {
  11811. this._activeRenderLoops.splice(index, 1);
  11812. }
  11813. };
  11814. Engine.prototype._renderLoop = function () {
  11815. if (!this._contextWasLost) {
  11816. var shouldRender = true;
  11817. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11818. shouldRender = false;
  11819. }
  11820. if (shouldRender) {
  11821. // Start new frame
  11822. this.beginFrame();
  11823. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11824. var renderFunction = this._activeRenderLoops[index];
  11825. renderFunction();
  11826. }
  11827. // Present
  11828. this.endFrame();
  11829. }
  11830. }
  11831. if (this._activeRenderLoops.length > 0) {
  11832. // Register new frame
  11833. var requester = null;
  11834. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11835. requester = this._vrDisplay;
  11836. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11837. }
  11838. else {
  11839. this._renderingQueueLaunched = false;
  11840. }
  11841. };
  11842. /**
  11843. * Register and execute a render loop. The engine can have more than one render function.
  11844. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11845. * @example
  11846. * engine.runRenderLoop(function () {
  11847. * scene.render()
  11848. * })
  11849. */
  11850. Engine.prototype.runRenderLoop = function (renderFunction) {
  11851. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11852. return;
  11853. }
  11854. this._activeRenderLoops.push(renderFunction);
  11855. if (!this._renderingQueueLaunched) {
  11856. this._renderingQueueLaunched = true;
  11857. this._bindedRenderFunction = this._renderLoop.bind(this);
  11858. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11859. }
  11860. };
  11861. /**
  11862. * Toggle full screen mode.
  11863. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11864. * @param {any} options - an options object to be sent to the requestFullscreen function
  11865. */
  11866. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11867. if (this.isFullscreen) {
  11868. BABYLON.Tools.ExitFullscreen();
  11869. }
  11870. else {
  11871. this._pointerLockRequested = requestPointerLock;
  11872. if (this._renderingCanvas) {
  11873. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11874. }
  11875. }
  11876. };
  11877. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11878. if (stencil === void 0) { stencil = false; }
  11879. this.applyStates();
  11880. var mode = 0;
  11881. if (backBuffer && color) {
  11882. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11883. mode |= this._gl.COLOR_BUFFER_BIT;
  11884. }
  11885. if (depth) {
  11886. this._gl.clearDepth(1.0);
  11887. mode |= this._gl.DEPTH_BUFFER_BIT;
  11888. }
  11889. if (stencil) {
  11890. this._gl.clearStencil(0);
  11891. mode |= this._gl.STENCIL_BUFFER_BIT;
  11892. }
  11893. this._gl.clear(mode);
  11894. };
  11895. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11896. var gl = this._gl;
  11897. // Save state
  11898. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11899. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11900. // Change state
  11901. gl.enable(gl.SCISSOR_TEST);
  11902. gl.scissor(x, y, width, height);
  11903. // Clear
  11904. this.clear(clearColor, true, true, true);
  11905. // Restore state
  11906. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11907. if (curScissor === true) {
  11908. gl.enable(gl.SCISSOR_TEST);
  11909. }
  11910. else {
  11911. gl.disable(gl.SCISSOR_TEST);
  11912. }
  11913. };
  11914. /**
  11915. * Set the WebGL's viewport
  11916. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11917. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11918. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11919. */
  11920. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11921. var width = requiredWidth || this.getRenderWidth();
  11922. var height = requiredHeight || this.getRenderHeight();
  11923. var x = viewport.x || 0;
  11924. var y = viewport.y || 0;
  11925. this._cachedViewport = viewport;
  11926. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11927. };
  11928. /**
  11929. * Directly set the WebGL Viewport
  11930. * The x, y, width & height are directly passed to the WebGL call
  11931. * @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.
  11932. */
  11933. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11934. var currentViewport = this._cachedViewport;
  11935. this._cachedViewport = null;
  11936. this._gl.viewport(x, y, width, height);
  11937. return currentViewport;
  11938. };
  11939. Engine.prototype.beginFrame = function () {
  11940. this.onBeginFrameObservable.notifyObservers(this);
  11941. this._measureFps();
  11942. };
  11943. Engine.prototype.endFrame = function () {
  11944. //force a flush in case we are using a bad OS.
  11945. if (this._badOS) {
  11946. this.flushFramebuffer();
  11947. }
  11948. //submit frame to the vr device, if enabled
  11949. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11950. // TODO: We should only submit the frame if we read frameData successfully.
  11951. this._vrDisplay.submitFrame();
  11952. }
  11953. this.onEndFrameObservable.notifyObservers(this);
  11954. };
  11955. /**
  11956. * resize the view according to the canvas' size.
  11957. * @example
  11958. * window.addEventListener("resize", function () {
  11959. * engine.resize();
  11960. * });
  11961. */
  11962. Engine.prototype.resize = function () {
  11963. // We're not resizing the size of the canvas while in VR mode & presenting
  11964. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11965. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11966. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11967. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11968. }
  11969. };
  11970. /**
  11971. * force a specific size of the canvas
  11972. * @param {number} width - the new canvas' width
  11973. * @param {number} height - the new canvas' height
  11974. */
  11975. Engine.prototype.setSize = function (width, height) {
  11976. if (!this._renderingCanvas) {
  11977. return;
  11978. }
  11979. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11980. return;
  11981. }
  11982. this._renderingCanvas.width = width;
  11983. this._renderingCanvas.height = height;
  11984. for (var index = 0; index < this.scenes.length; index++) {
  11985. var scene = this.scenes[index];
  11986. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11987. var cam = scene.cameras[camIndex];
  11988. cam._currentRenderId = 0;
  11989. }
  11990. }
  11991. if (this.onResizeObservable.hasObservers) {
  11992. this.onResizeObservable.notifyObservers(this);
  11993. }
  11994. };
  11995. // WebVR functions
  11996. Engine.prototype.isVRDevicePresent = function () {
  11997. return !!this._vrDisplay;
  11998. };
  11999. Engine.prototype.getVRDevice = function () {
  12000. return this._vrDisplay;
  12001. };
  12002. /**
  12003. * Initializes a webVR display and starts listening to display change events.
  12004. * The onVRDisplayChangedObservable will be notified upon these changes.
  12005. * @returns The onVRDisplayChangedObservable.
  12006. */
  12007. Engine.prototype.initWebVR = function () {
  12008. this.initWebVRAsync();
  12009. return this.onVRDisplayChangedObservable;
  12010. };
  12011. /**
  12012. * Initializes a webVR display and starts listening to display change events.
  12013. * The onVRDisplayChangedObservable will be notified upon these changes.
  12014. * @returns A promise containing a VRDisplay and if vr is supported.
  12015. */
  12016. Engine.prototype.initWebVRAsync = function () {
  12017. var _this = this;
  12018. var notifyObservers = function () {
  12019. var eventArgs = {
  12020. vrDisplay: _this._vrDisplay,
  12021. vrSupported: _this._vrSupported
  12022. };
  12023. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12024. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12025. };
  12026. if (!this._onVrDisplayConnect) {
  12027. this._onVrDisplayConnect = function (event) {
  12028. _this._vrDisplay = event.display;
  12029. notifyObservers();
  12030. };
  12031. this._onVrDisplayDisconnect = function () {
  12032. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12033. _this._vrDisplay = undefined;
  12034. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12035. notifyObservers();
  12036. };
  12037. this._onVrDisplayPresentChange = function () {
  12038. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12039. };
  12040. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12041. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12042. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12043. }
  12044. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12045. this._webVRInitPromise.then(notifyObservers);
  12046. return this._webVRInitPromise;
  12047. };
  12048. Engine.prototype.enableVR = function () {
  12049. var _this = this;
  12050. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12051. var onResolved = function () {
  12052. _this.onVRRequestPresentComplete.notifyObservers(true);
  12053. _this._onVRFullScreenTriggered();
  12054. };
  12055. var onRejected = function () {
  12056. _this.onVRRequestPresentComplete.notifyObservers(false);
  12057. };
  12058. this.onVRRequestPresentStart.notifyObservers(this);
  12059. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12060. }
  12061. };
  12062. Engine.prototype.disableVR = function () {
  12063. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12064. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12065. }
  12066. };
  12067. Engine.prototype._getVRDisplaysAsync = function () {
  12068. var _this = this;
  12069. return new Promise(function (res, rej) {
  12070. if (navigator.getVRDisplays) {
  12071. navigator.getVRDisplays().then(function (devices) {
  12072. _this._vrSupported = true;
  12073. // note that devices may actually be an empty array. This is fine;
  12074. // we expect this._vrDisplay to be undefined in this case.
  12075. _this._vrDisplay = devices[0];
  12076. res({
  12077. vrDisplay: _this._vrDisplay,
  12078. vrSupported: _this._vrSupported
  12079. });
  12080. });
  12081. }
  12082. else {
  12083. _this._vrDisplay = undefined;
  12084. _this._vrSupported = false;
  12085. res({
  12086. vrDisplay: _this._vrDisplay,
  12087. vrSupported: _this._vrSupported
  12088. });
  12089. }
  12090. });
  12091. };
  12092. /**
  12093. * Binds the frame buffer to the specified texture.
  12094. * @param texture The texture to render to or null for the default canvas
  12095. * @param faceIndex The face of the texture to render to in case of cube texture
  12096. * @param requiredWidth The width of the target to render to
  12097. * @param requiredHeight The height of the target to render to
  12098. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12099. * @param depthStencilTexture The depth stencil texture to use to render
  12100. */
  12101. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12102. if (this._currentRenderTarget) {
  12103. this.unBindFramebuffer(this._currentRenderTarget);
  12104. }
  12105. this._currentRenderTarget = texture;
  12106. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12107. var gl = this._gl;
  12108. if (texture.isCube) {
  12109. if (faceIndex === undefined) {
  12110. faceIndex = 0;
  12111. }
  12112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12113. if (depthStencilTexture) {
  12114. if (depthStencilTexture._generateStencilBuffer) {
  12115. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12116. }
  12117. else {
  12118. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12119. }
  12120. }
  12121. }
  12122. if (this._cachedViewport && !forceFullscreenViewport) {
  12123. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12124. }
  12125. else {
  12126. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12127. }
  12128. this.wipeCaches();
  12129. };
  12130. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12131. if (this._currentFramebuffer !== framebuffer) {
  12132. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12133. this._currentFramebuffer = framebuffer;
  12134. }
  12135. };
  12136. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12137. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12138. this._currentRenderTarget = null;
  12139. // If MSAA, we need to bitblt back to main texture
  12140. var gl = this._gl;
  12141. if (texture._MSAAFramebuffer) {
  12142. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12143. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12144. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12145. }
  12146. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12147. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12148. gl.generateMipmap(gl.TEXTURE_2D);
  12149. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12150. }
  12151. if (onBeforeUnbind) {
  12152. if (texture._MSAAFramebuffer) {
  12153. // Bind the correct framebuffer
  12154. this.bindUnboundFramebuffer(texture._framebuffer);
  12155. }
  12156. onBeforeUnbind();
  12157. }
  12158. this.bindUnboundFramebuffer(null);
  12159. };
  12160. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12161. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12162. this._currentRenderTarget = null;
  12163. // If MSAA, we need to bitblt back to main texture
  12164. var gl = this._gl;
  12165. if (textures[0]._MSAAFramebuffer) {
  12166. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12167. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12168. var attachments = textures[0]._attachments;
  12169. if (!attachments) {
  12170. attachments = new Array(textures.length);
  12171. textures[0]._attachments = attachments;
  12172. }
  12173. for (var i = 0; i < textures.length; i++) {
  12174. var texture = textures[i];
  12175. for (var j = 0; j < attachments.length; j++) {
  12176. attachments[j] = gl.NONE;
  12177. }
  12178. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12179. gl.readBuffer(attachments[i]);
  12180. gl.drawBuffers(attachments);
  12181. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12182. }
  12183. for (var i = 0; i < attachments.length; i++) {
  12184. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12185. }
  12186. gl.drawBuffers(attachments);
  12187. }
  12188. for (var i = 0; i < textures.length; i++) {
  12189. var texture = textures[i];
  12190. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12191. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12192. gl.generateMipmap(gl.TEXTURE_2D);
  12193. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12194. }
  12195. }
  12196. if (onBeforeUnbind) {
  12197. if (textures[0]._MSAAFramebuffer) {
  12198. // Bind the correct framebuffer
  12199. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12200. }
  12201. onBeforeUnbind();
  12202. }
  12203. this.bindUnboundFramebuffer(null);
  12204. };
  12205. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12206. if (texture.generateMipMaps) {
  12207. var gl = this._gl;
  12208. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12209. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12210. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12211. }
  12212. };
  12213. Engine.prototype.flushFramebuffer = function () {
  12214. this._gl.flush();
  12215. };
  12216. Engine.prototype.restoreDefaultFramebuffer = function () {
  12217. if (this._currentRenderTarget) {
  12218. this.unBindFramebuffer(this._currentRenderTarget);
  12219. }
  12220. else {
  12221. this.bindUnboundFramebuffer(null);
  12222. }
  12223. if (this._cachedViewport) {
  12224. this.setViewport(this._cachedViewport);
  12225. }
  12226. this.wipeCaches();
  12227. };
  12228. // UBOs
  12229. Engine.prototype.createUniformBuffer = function (elements) {
  12230. var ubo = this._gl.createBuffer();
  12231. if (!ubo) {
  12232. throw new Error("Unable to create uniform buffer");
  12233. }
  12234. this.bindUniformBuffer(ubo);
  12235. if (elements instanceof Float32Array) {
  12236. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12237. }
  12238. else {
  12239. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12240. }
  12241. this.bindUniformBuffer(null);
  12242. ubo.references = 1;
  12243. return ubo;
  12244. };
  12245. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12246. var ubo = this._gl.createBuffer();
  12247. if (!ubo) {
  12248. throw new Error("Unable to create dynamic uniform buffer");
  12249. }
  12250. this.bindUniformBuffer(ubo);
  12251. if (elements instanceof Float32Array) {
  12252. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12253. }
  12254. else {
  12255. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12256. }
  12257. this.bindUniformBuffer(null);
  12258. ubo.references = 1;
  12259. return ubo;
  12260. };
  12261. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12262. this.bindUniformBuffer(uniformBuffer);
  12263. if (offset === undefined) {
  12264. offset = 0;
  12265. }
  12266. if (count === undefined) {
  12267. if (elements instanceof Float32Array) {
  12268. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12269. }
  12270. else {
  12271. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12272. }
  12273. }
  12274. else {
  12275. if (elements instanceof Float32Array) {
  12276. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12277. }
  12278. else {
  12279. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12280. }
  12281. }
  12282. this.bindUniformBuffer(null);
  12283. };
  12284. // VBOs
  12285. Engine.prototype._resetVertexBufferBinding = function () {
  12286. this.bindArrayBuffer(null);
  12287. this._cachedVertexBuffers = null;
  12288. };
  12289. Engine.prototype.createVertexBuffer = function (vertices) {
  12290. var vbo = this._gl.createBuffer();
  12291. if (!vbo) {
  12292. throw new Error("Unable to create vertex buffer");
  12293. }
  12294. this.bindArrayBuffer(vbo);
  12295. if (vertices instanceof Float32Array) {
  12296. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12297. }
  12298. else {
  12299. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12300. }
  12301. this._resetVertexBufferBinding();
  12302. vbo.references = 1;
  12303. return vbo;
  12304. };
  12305. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12306. var vbo = this._gl.createBuffer();
  12307. if (!vbo) {
  12308. throw new Error("Unable to create dynamic vertex buffer");
  12309. }
  12310. this.bindArrayBuffer(vbo);
  12311. if (vertices instanceof Float32Array) {
  12312. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12313. }
  12314. else {
  12315. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12316. }
  12317. this._resetVertexBufferBinding();
  12318. vbo.references = 1;
  12319. return vbo;
  12320. };
  12321. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12322. if (offset === void 0) { offset = 0; }
  12323. // Force cache update
  12324. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12325. this.bindIndexBuffer(indexBuffer);
  12326. var arrayBuffer;
  12327. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12328. arrayBuffer = indices;
  12329. }
  12330. else {
  12331. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12332. }
  12333. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12334. this._resetIndexBufferBinding();
  12335. };
  12336. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12337. this.bindArrayBuffer(vertexBuffer);
  12338. if (offset === undefined) {
  12339. offset = 0;
  12340. }
  12341. if (count === undefined) {
  12342. if (vertices instanceof Float32Array) {
  12343. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12344. }
  12345. else {
  12346. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12347. }
  12348. }
  12349. else {
  12350. if (vertices instanceof Float32Array) {
  12351. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12352. }
  12353. else {
  12354. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12355. }
  12356. }
  12357. this._resetVertexBufferBinding();
  12358. };
  12359. Engine.prototype._resetIndexBufferBinding = function () {
  12360. this.bindIndexBuffer(null);
  12361. this._cachedIndexBuffer = null;
  12362. };
  12363. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12364. var vbo = this._gl.createBuffer();
  12365. if (!vbo) {
  12366. throw new Error("Unable to create index buffer");
  12367. }
  12368. this.bindIndexBuffer(vbo);
  12369. // Check for 32 bits indices
  12370. var arrayBuffer;
  12371. var need32Bits = false;
  12372. if (indices instanceof Uint16Array) {
  12373. arrayBuffer = indices;
  12374. }
  12375. else {
  12376. //check 32 bit support
  12377. if (this._caps.uintIndices) {
  12378. if (indices instanceof Uint32Array) {
  12379. arrayBuffer = indices;
  12380. need32Bits = true;
  12381. }
  12382. else {
  12383. //number[] or Int32Array, check if 32 bit is necessary
  12384. for (var index = 0; index < indices.length; index++) {
  12385. if (indices[index] > 65535) {
  12386. need32Bits = true;
  12387. break;
  12388. }
  12389. }
  12390. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12391. }
  12392. }
  12393. else {
  12394. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12395. arrayBuffer = new Uint16Array(indices);
  12396. }
  12397. }
  12398. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12399. this._resetIndexBufferBinding();
  12400. vbo.references = 1;
  12401. vbo.is32Bits = need32Bits;
  12402. return vbo;
  12403. };
  12404. Engine.prototype.bindArrayBuffer = function (buffer) {
  12405. if (!this._vaoRecordInProgress) {
  12406. this._unbindVertexArrayObject();
  12407. }
  12408. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12409. };
  12410. Engine.prototype.bindUniformBuffer = function (buffer) {
  12411. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12412. };
  12413. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12414. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12415. };
  12416. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12417. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12418. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12419. };
  12420. ;
  12421. Engine.prototype.bindIndexBuffer = function (buffer) {
  12422. if (!this._vaoRecordInProgress) {
  12423. this._unbindVertexArrayObject();
  12424. }
  12425. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12426. };
  12427. Engine.prototype.bindBuffer = function (buffer, target) {
  12428. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12429. this._gl.bindBuffer(target, buffer);
  12430. this._currentBoundBuffer[target] = buffer;
  12431. }
  12432. };
  12433. Engine.prototype.updateArrayBuffer = function (data) {
  12434. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12435. };
  12436. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12437. var pointer = this._currentBufferPointers[indx];
  12438. var changed = false;
  12439. if (!pointer.active) {
  12440. changed = true;
  12441. pointer.active = true;
  12442. pointer.index = indx;
  12443. pointer.size = size;
  12444. pointer.type = type;
  12445. pointer.normalized = normalized;
  12446. pointer.stride = stride;
  12447. pointer.offset = offset;
  12448. pointer.buffer = buffer;
  12449. }
  12450. else {
  12451. if (pointer.buffer !== buffer) {
  12452. pointer.buffer = buffer;
  12453. changed = true;
  12454. }
  12455. if (pointer.size !== size) {
  12456. pointer.size = size;
  12457. changed = true;
  12458. }
  12459. if (pointer.type !== type) {
  12460. pointer.type = type;
  12461. changed = true;
  12462. }
  12463. if (pointer.normalized !== normalized) {
  12464. pointer.normalized = normalized;
  12465. changed = true;
  12466. }
  12467. if (pointer.stride !== stride) {
  12468. pointer.stride = stride;
  12469. changed = true;
  12470. }
  12471. if (pointer.offset !== offset) {
  12472. pointer.offset = offset;
  12473. changed = true;
  12474. }
  12475. }
  12476. if (changed || this._vaoRecordInProgress) {
  12477. this.bindArrayBuffer(buffer);
  12478. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12479. }
  12480. };
  12481. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12482. if (indexBuffer == null) {
  12483. return;
  12484. }
  12485. if (this._cachedIndexBuffer !== indexBuffer) {
  12486. this._cachedIndexBuffer = indexBuffer;
  12487. this.bindIndexBuffer(indexBuffer);
  12488. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12489. }
  12490. };
  12491. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12492. var attributes = effect.getAttributesNames();
  12493. if (!this._vaoRecordInProgress) {
  12494. this._unbindVertexArrayObject();
  12495. }
  12496. this.unbindAllAttributes();
  12497. for (var index = 0; index < attributes.length; index++) {
  12498. var order = effect.getAttributeLocation(index);
  12499. if (order >= 0) {
  12500. var vertexBuffer = vertexBuffers[attributes[index]];
  12501. if (!vertexBuffer) {
  12502. continue;
  12503. }
  12504. this._gl.enableVertexAttribArray(order);
  12505. if (!this._vaoRecordInProgress) {
  12506. this._vertexAttribArraysEnabled[order] = true;
  12507. }
  12508. var buffer = vertexBuffer.getBuffer();
  12509. if (buffer) {
  12510. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12511. if (vertexBuffer.getIsInstanced()) {
  12512. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12513. if (!this._vaoRecordInProgress) {
  12514. this._currentInstanceLocations.push(order);
  12515. this._currentInstanceBuffers.push(buffer);
  12516. }
  12517. }
  12518. }
  12519. }
  12520. }
  12521. };
  12522. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12523. var vao = this._gl.createVertexArray();
  12524. this._vaoRecordInProgress = true;
  12525. this._gl.bindVertexArray(vao);
  12526. this._mustWipeVertexAttributes = true;
  12527. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12528. this.bindIndexBuffer(indexBuffer);
  12529. this._vaoRecordInProgress = false;
  12530. this._gl.bindVertexArray(null);
  12531. return vao;
  12532. };
  12533. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12534. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12535. this._cachedVertexArrayObject = vertexArrayObject;
  12536. this._gl.bindVertexArray(vertexArrayObject);
  12537. this._cachedVertexBuffers = null;
  12538. this._cachedIndexBuffer = null;
  12539. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12540. this._mustWipeVertexAttributes = true;
  12541. }
  12542. };
  12543. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12544. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12545. this._cachedVertexBuffers = vertexBuffer;
  12546. this._cachedEffectForVertexBuffers = effect;
  12547. var attributesCount = effect.getAttributesCount();
  12548. this._unbindVertexArrayObject();
  12549. this.unbindAllAttributes();
  12550. var offset = 0;
  12551. for (var index = 0; index < attributesCount; index++) {
  12552. if (index < vertexDeclaration.length) {
  12553. var order = effect.getAttributeLocation(index);
  12554. if (order >= 0) {
  12555. this._gl.enableVertexAttribArray(order);
  12556. this._vertexAttribArraysEnabled[order] = true;
  12557. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12558. }
  12559. offset += vertexDeclaration[index] * 4;
  12560. }
  12561. }
  12562. }
  12563. this._bindIndexBufferWithCache(indexBuffer);
  12564. };
  12565. Engine.prototype._unbindVertexArrayObject = function () {
  12566. if (!this._cachedVertexArrayObject) {
  12567. return;
  12568. }
  12569. this._cachedVertexArrayObject = null;
  12570. this._gl.bindVertexArray(null);
  12571. };
  12572. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12573. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12574. this._cachedVertexBuffers = vertexBuffers;
  12575. this._cachedEffectForVertexBuffers = effect;
  12576. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12577. }
  12578. this._bindIndexBufferWithCache(indexBuffer);
  12579. };
  12580. Engine.prototype.unbindInstanceAttributes = function () {
  12581. var boundBuffer;
  12582. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12583. var instancesBuffer = this._currentInstanceBuffers[i];
  12584. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12585. boundBuffer = instancesBuffer;
  12586. this.bindArrayBuffer(instancesBuffer);
  12587. }
  12588. var offsetLocation = this._currentInstanceLocations[i];
  12589. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12590. }
  12591. this._currentInstanceBuffers.length = 0;
  12592. this._currentInstanceLocations.length = 0;
  12593. };
  12594. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12595. this._gl.deleteVertexArray(vao);
  12596. };
  12597. Engine.prototype._releaseBuffer = function (buffer) {
  12598. buffer.references--;
  12599. if (buffer.references === 0) {
  12600. this._gl.deleteBuffer(buffer);
  12601. return true;
  12602. }
  12603. return false;
  12604. };
  12605. Engine.prototype.createInstancesBuffer = function (capacity) {
  12606. var buffer = this._gl.createBuffer();
  12607. if (!buffer) {
  12608. throw new Error("Unable to create instance buffer");
  12609. }
  12610. buffer.capacity = capacity;
  12611. this.bindArrayBuffer(buffer);
  12612. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12613. return buffer;
  12614. };
  12615. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12616. this._gl.deleteBuffer(buffer);
  12617. };
  12618. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12619. this.bindArrayBuffer(instancesBuffer);
  12620. if (data) {
  12621. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12622. }
  12623. if (offsetLocations[0].index !== undefined) {
  12624. var stride = 0;
  12625. for (var i = 0; i < offsetLocations.length; i++) {
  12626. var ai = offsetLocations[i];
  12627. stride += ai.attributeSize * 4;
  12628. }
  12629. for (var i = 0; i < offsetLocations.length; i++) {
  12630. var ai = offsetLocations[i];
  12631. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12632. this._gl.enableVertexAttribArray(ai.index);
  12633. this._vertexAttribArraysEnabled[ai.index] = true;
  12634. }
  12635. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12636. this._gl.vertexAttribDivisor(ai.index, 1);
  12637. this._currentInstanceLocations.push(ai.index);
  12638. this._currentInstanceBuffers.push(instancesBuffer);
  12639. }
  12640. }
  12641. else {
  12642. for (var index = 0; index < 4; index++) {
  12643. var offsetLocation = offsetLocations[index];
  12644. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12645. this._gl.enableVertexAttribArray(offsetLocation);
  12646. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12647. }
  12648. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12649. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12650. this._currentInstanceLocations.push(offsetLocation);
  12651. this._currentInstanceBuffers.push(instancesBuffer);
  12652. }
  12653. }
  12654. };
  12655. Engine.prototype.applyStates = function () {
  12656. this._depthCullingState.apply(this._gl);
  12657. this._stencilState.apply(this._gl);
  12658. this._alphaState.apply(this._gl);
  12659. };
  12660. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12661. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12662. };
  12663. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12664. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12665. };
  12666. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12667. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12668. };
  12669. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12670. // Apply states
  12671. this.applyStates();
  12672. this._drawCalls.addCount(1, false);
  12673. // Render
  12674. var drawMode = this._drawMode(fillMode);
  12675. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12676. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12677. if (instancesCount) {
  12678. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12679. }
  12680. else {
  12681. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12682. }
  12683. };
  12684. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12685. // Apply states
  12686. this.applyStates();
  12687. this._drawCalls.addCount(1, false);
  12688. var drawMode = this._drawMode(fillMode);
  12689. if (instancesCount) {
  12690. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12691. }
  12692. else {
  12693. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12694. }
  12695. };
  12696. Engine.prototype._drawMode = function (fillMode) {
  12697. switch (fillMode) {
  12698. // Triangle views
  12699. case BABYLON.Material.TriangleFillMode:
  12700. return this._gl.TRIANGLES;
  12701. case BABYLON.Material.PointFillMode:
  12702. return this._gl.POINTS;
  12703. case BABYLON.Material.WireFrameFillMode:
  12704. return this._gl.LINES;
  12705. // Draw modes
  12706. case BABYLON.Material.PointListDrawMode:
  12707. return this._gl.POINTS;
  12708. case BABYLON.Material.LineListDrawMode:
  12709. return this._gl.LINES;
  12710. case BABYLON.Material.LineLoopDrawMode:
  12711. return this._gl.LINE_LOOP;
  12712. case BABYLON.Material.LineStripDrawMode:
  12713. return this._gl.LINE_STRIP;
  12714. case BABYLON.Material.TriangleStripDrawMode:
  12715. return this._gl.TRIANGLE_STRIP;
  12716. case BABYLON.Material.TriangleFanDrawMode:
  12717. return this._gl.TRIANGLE_FAN;
  12718. default:
  12719. return this._gl.TRIANGLES;
  12720. }
  12721. };
  12722. // Shaders
  12723. Engine.prototype._releaseEffect = function (effect) {
  12724. if (this._compiledEffects[effect._key]) {
  12725. delete this._compiledEffects[effect._key];
  12726. this._deleteProgram(effect.getProgram());
  12727. }
  12728. };
  12729. Engine.prototype._deleteProgram = function (program) {
  12730. if (program) {
  12731. program.__SPECTOR_rebuildProgram = null;
  12732. if (program.transformFeedback) {
  12733. this.deleteTransformFeedback(program.transformFeedback);
  12734. program.transformFeedback = null;
  12735. }
  12736. this._gl.deleteProgram(program);
  12737. }
  12738. };
  12739. /**
  12740. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12741. * @param samplers An array of string used to represent textures
  12742. */
  12743. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12744. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12745. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12746. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12747. if (this._compiledEffects[name]) {
  12748. var compiledEffect = this._compiledEffects[name];
  12749. if (onCompiled && compiledEffect.isReady()) {
  12750. onCompiled(compiledEffect);
  12751. }
  12752. return compiledEffect;
  12753. }
  12754. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12755. effect._key = name;
  12756. this._compiledEffects[name] = effect;
  12757. return effect;
  12758. };
  12759. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12760. if (uniformsNames === void 0) { uniformsNames = []; }
  12761. if (samplers === void 0) { samplers = []; }
  12762. if (defines === void 0) { defines = ""; }
  12763. return this.createEffect({
  12764. vertex: "particles",
  12765. fragmentElement: fragmentName
  12766. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12767. };
  12768. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12769. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12770. context = context || this._gl;
  12771. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12772. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12773. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12774. };
  12775. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12776. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12777. context = context || this._gl;
  12778. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12779. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12780. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12781. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12782. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12783. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12784. return program;
  12785. };
  12786. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12787. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12788. var shaderProgram = context.createProgram();
  12789. if (!shaderProgram) {
  12790. throw new Error("Unable to create program");
  12791. }
  12792. context.attachShader(shaderProgram, vertexShader);
  12793. context.attachShader(shaderProgram, fragmentShader);
  12794. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12795. var transformFeedback = this.createTransformFeedback();
  12796. this.bindTransformFeedback(transformFeedback);
  12797. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12798. shaderProgram.transformFeedback = transformFeedback;
  12799. }
  12800. context.linkProgram(shaderProgram);
  12801. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12802. this.bindTransformFeedback(null);
  12803. }
  12804. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12805. if (!linked) {
  12806. context.validateProgram(shaderProgram);
  12807. var error = context.getProgramInfoLog(shaderProgram);
  12808. if (error) {
  12809. throw new Error(error);
  12810. }
  12811. }
  12812. context.deleteShader(vertexShader);
  12813. context.deleteShader(fragmentShader);
  12814. return shaderProgram;
  12815. };
  12816. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12817. var results = new Array();
  12818. for (var index = 0; index < uniformsNames.length; index++) {
  12819. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12820. }
  12821. return results;
  12822. };
  12823. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12824. var results = [];
  12825. for (var index = 0; index < attributesNames.length; index++) {
  12826. try {
  12827. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12828. }
  12829. catch (e) {
  12830. results.push(-1);
  12831. }
  12832. }
  12833. return results;
  12834. };
  12835. Engine.prototype.enableEffect = function (effect) {
  12836. if (!effect) {
  12837. return;
  12838. }
  12839. // Use program
  12840. this.bindSamplers(effect);
  12841. this._currentEffect = effect;
  12842. if (effect.onBind) {
  12843. effect.onBind(effect);
  12844. }
  12845. effect.onBindObservable.notifyObservers(effect);
  12846. };
  12847. Engine.prototype.setIntArray = function (uniform, array) {
  12848. if (!uniform)
  12849. return;
  12850. this._gl.uniform1iv(uniform, array);
  12851. };
  12852. Engine.prototype.setIntArray2 = function (uniform, array) {
  12853. if (!uniform || array.length % 2 !== 0)
  12854. return;
  12855. this._gl.uniform2iv(uniform, array);
  12856. };
  12857. Engine.prototype.setIntArray3 = function (uniform, array) {
  12858. if (!uniform || array.length % 3 !== 0)
  12859. return;
  12860. this._gl.uniform3iv(uniform, array);
  12861. };
  12862. Engine.prototype.setIntArray4 = function (uniform, array) {
  12863. if (!uniform || array.length % 4 !== 0)
  12864. return;
  12865. this._gl.uniform4iv(uniform, array);
  12866. };
  12867. Engine.prototype.setFloatArray = function (uniform, array) {
  12868. if (!uniform)
  12869. return;
  12870. this._gl.uniform1fv(uniform, array);
  12871. };
  12872. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12873. if (!uniform || array.length % 2 !== 0)
  12874. return;
  12875. this._gl.uniform2fv(uniform, array);
  12876. };
  12877. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12878. if (!uniform || array.length % 3 !== 0)
  12879. return;
  12880. this._gl.uniform3fv(uniform, array);
  12881. };
  12882. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12883. if (!uniform || array.length % 4 !== 0)
  12884. return;
  12885. this._gl.uniform4fv(uniform, array);
  12886. };
  12887. Engine.prototype.setArray = function (uniform, array) {
  12888. if (!uniform)
  12889. return;
  12890. this._gl.uniform1fv(uniform, array);
  12891. };
  12892. Engine.prototype.setArray2 = function (uniform, array) {
  12893. if (!uniform || array.length % 2 !== 0)
  12894. return;
  12895. this._gl.uniform2fv(uniform, array);
  12896. };
  12897. Engine.prototype.setArray3 = function (uniform, array) {
  12898. if (!uniform || array.length % 3 !== 0)
  12899. return;
  12900. this._gl.uniform3fv(uniform, array);
  12901. };
  12902. Engine.prototype.setArray4 = function (uniform, array) {
  12903. if (!uniform || array.length % 4 !== 0)
  12904. return;
  12905. this._gl.uniform4fv(uniform, array);
  12906. };
  12907. Engine.prototype.setMatrices = function (uniform, matrices) {
  12908. if (!uniform)
  12909. return;
  12910. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12911. };
  12912. Engine.prototype.setMatrix = function (uniform, matrix) {
  12913. if (!uniform)
  12914. return;
  12915. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12916. };
  12917. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12918. if (!uniform)
  12919. return;
  12920. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12921. };
  12922. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12923. if (!uniform)
  12924. return;
  12925. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12926. };
  12927. Engine.prototype.setInt = function (uniform, value) {
  12928. if (!uniform)
  12929. return;
  12930. this._gl.uniform1i(uniform, value);
  12931. };
  12932. Engine.prototype.setFloat = function (uniform, value) {
  12933. if (!uniform)
  12934. return;
  12935. this._gl.uniform1f(uniform, value);
  12936. };
  12937. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12938. if (!uniform)
  12939. return;
  12940. this._gl.uniform2f(uniform, x, y);
  12941. };
  12942. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12943. if (!uniform)
  12944. return;
  12945. this._gl.uniform3f(uniform, x, y, z);
  12946. };
  12947. Engine.prototype.setBool = function (uniform, bool) {
  12948. if (!uniform)
  12949. return;
  12950. this._gl.uniform1i(uniform, bool);
  12951. };
  12952. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12953. if (!uniform)
  12954. return;
  12955. this._gl.uniform4f(uniform, x, y, z, w);
  12956. };
  12957. Engine.prototype.setColor3 = function (uniform, color3) {
  12958. if (!uniform)
  12959. return;
  12960. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12961. };
  12962. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12963. if (!uniform)
  12964. return;
  12965. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12966. };
  12967. /**
  12968. * Sets a Color4 on a uniform variable
  12969. * @param uniform defines the uniform location
  12970. * @param color4 defines the value to be set
  12971. */
  12972. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12973. if (!uniform)
  12974. return;
  12975. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12976. };
  12977. // States
  12978. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12979. if (zOffset === void 0) { zOffset = 0; }
  12980. if (reverseSide === void 0) { reverseSide = false; }
  12981. // Culling
  12982. if (this._depthCullingState.cull !== culling || force) {
  12983. this._depthCullingState.cull = culling;
  12984. }
  12985. // Cull face
  12986. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12987. if (this._depthCullingState.cullFace !== cullFace || force) {
  12988. this._depthCullingState.cullFace = cullFace;
  12989. }
  12990. // Z offset
  12991. this.setZOffset(zOffset);
  12992. // Front face
  12993. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12994. if (this._depthCullingState.frontFace !== frontFace || force) {
  12995. this._depthCullingState.frontFace = frontFace;
  12996. }
  12997. };
  12998. Engine.prototype.setZOffset = function (value) {
  12999. this._depthCullingState.zOffset = value;
  13000. };
  13001. Engine.prototype.getZOffset = function () {
  13002. return this._depthCullingState.zOffset;
  13003. };
  13004. Engine.prototype.setDepthBuffer = function (enable) {
  13005. this._depthCullingState.depthTest = enable;
  13006. };
  13007. Engine.prototype.getDepthWrite = function () {
  13008. return this._depthCullingState.depthMask;
  13009. };
  13010. Engine.prototype.setDepthWrite = function (enable) {
  13011. this._depthCullingState.depthMask = enable;
  13012. };
  13013. Engine.prototype.setColorWrite = function (enable) {
  13014. this._gl.colorMask(enable, enable, enable, enable);
  13015. this._colorWrite = enable;
  13016. };
  13017. Engine.prototype.getColorWrite = function () {
  13018. return this._colorWrite;
  13019. };
  13020. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13021. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13022. };
  13023. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13024. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13025. if (this._alphaMode === mode) {
  13026. return;
  13027. }
  13028. switch (mode) {
  13029. case Engine.ALPHA_DISABLE:
  13030. this._alphaState.alphaBlend = false;
  13031. break;
  13032. case Engine.ALPHA_PREMULTIPLIED:
  13033. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13034. this._alphaState.alphaBlend = true;
  13035. break;
  13036. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13037. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13038. this._alphaState.alphaBlend = true;
  13039. break;
  13040. case Engine.ALPHA_COMBINE:
  13041. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13042. this._alphaState.alphaBlend = true;
  13043. break;
  13044. case Engine.ALPHA_ONEONE:
  13045. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13046. this._alphaState.alphaBlend = true;
  13047. break;
  13048. case Engine.ALPHA_ADD:
  13049. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13050. this._alphaState.alphaBlend = true;
  13051. break;
  13052. case Engine.ALPHA_SUBTRACT:
  13053. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13054. this._alphaState.alphaBlend = true;
  13055. break;
  13056. case Engine.ALPHA_MULTIPLY:
  13057. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13058. this._alphaState.alphaBlend = true;
  13059. break;
  13060. case Engine.ALPHA_MAXIMIZED:
  13061. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13062. this._alphaState.alphaBlend = true;
  13063. break;
  13064. case Engine.ALPHA_INTERPOLATE:
  13065. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13066. this._alphaState.alphaBlend = true;
  13067. break;
  13068. case Engine.ALPHA_SCREENMODE:
  13069. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13070. this._alphaState.alphaBlend = true;
  13071. break;
  13072. }
  13073. if (!noDepthWriteChange) {
  13074. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13075. }
  13076. this._alphaMode = mode;
  13077. };
  13078. Engine.prototype.getAlphaMode = function () {
  13079. return this._alphaMode;
  13080. };
  13081. // Textures
  13082. Engine.prototype.wipeCaches = function (bruteForce) {
  13083. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13084. return;
  13085. }
  13086. this._currentEffect = null;
  13087. // 6/8/2017: deltakosh: Should not be required anymore.
  13088. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13089. if (bruteForce) {
  13090. this.resetTextureCache();
  13091. this._currentProgram = null;
  13092. this._stencilState.reset();
  13093. this._depthCullingState.reset();
  13094. this.setDepthFunctionToLessOrEqual();
  13095. this._alphaState.reset();
  13096. }
  13097. this._resetVertexBufferBinding();
  13098. this._cachedIndexBuffer = null;
  13099. this._cachedEffectForVertexBuffers = null;
  13100. this._unbindVertexArrayObject();
  13101. this.bindIndexBuffer(null);
  13102. };
  13103. /**
  13104. * Set the compressed texture format to use, based on the formats you have, and the formats
  13105. * supported by the hardware / browser.
  13106. *
  13107. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13108. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13109. * to API arguments needed to compressed textures. This puts the burden on the container
  13110. * generator to house the arcane code for determining these for current & future formats.
  13111. *
  13112. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13113. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13114. *
  13115. * Note: The result of this call is not taken into account when a texture is base64.
  13116. *
  13117. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13118. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13119. *
  13120. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13121. * @returns The extension selected.
  13122. */
  13123. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13124. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13125. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13126. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13127. return this._textureFormatInUse = this._texturesSupported[i];
  13128. }
  13129. }
  13130. }
  13131. // actively set format to nothing, to allow this to be called more than once
  13132. // and possibly fail the 2nd time
  13133. this._textureFormatInUse = null;
  13134. return null;
  13135. };
  13136. Engine.prototype._createTexture = function () {
  13137. var texture = this._gl.createTexture();
  13138. if (!texture) {
  13139. throw new Error("Unable to create texture");
  13140. }
  13141. return texture;
  13142. };
  13143. /**
  13144. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13145. * @param {string} urlArg- This contains one of the following:
  13146. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13147. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13148. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13149. *
  13150. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13151. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13152. * @param {Scene} scene- Needed for loading to the correct scene.
  13153. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13154. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13155. * @param {callback} onError- Optional callback to be called upon failure.
  13156. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13157. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13158. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13159. *
  13160. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13161. */
  13162. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13163. var _this = this;
  13164. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13165. if (onLoad === void 0) { onLoad = null; }
  13166. if (onError === void 0) { onError = null; }
  13167. if (buffer === void 0) { buffer = null; }
  13168. if (fallBack === void 0) { fallBack = null; }
  13169. if (format === void 0) { format = null; }
  13170. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13171. var fromData = url.substr(0, 5) === "data:";
  13172. var fromBlob = url.substr(0, 5) === "blob:";
  13173. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13174. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13175. // establish the file extension, if possible
  13176. var lastDot = url.lastIndexOf('.');
  13177. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13178. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13179. var isTGA = (extension.indexOf(".tga") === 0);
  13180. // determine if a ktx file should be substituted
  13181. var isKTX = false;
  13182. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13183. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13184. isKTX = true;
  13185. }
  13186. if (scene) {
  13187. scene._addPendingData(texture);
  13188. }
  13189. texture.url = url;
  13190. texture.generateMipMaps = !noMipmap;
  13191. texture.samplingMode = samplingMode;
  13192. texture.invertY = invertY;
  13193. if (!this._doNotHandleContextLost) {
  13194. // Keep a link to the buffer only if we plan to handle context lost
  13195. texture._buffer = buffer;
  13196. }
  13197. var onLoadObserver = null;
  13198. if (onLoad && !fallBack) {
  13199. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13200. }
  13201. if (!fallBack)
  13202. this._internalTexturesCache.push(texture);
  13203. var onerror = function (message, exception) {
  13204. if (scene) {
  13205. scene._removePendingData(texture);
  13206. }
  13207. if (onLoadObserver) {
  13208. texture.onLoadedObservable.remove(onLoadObserver);
  13209. }
  13210. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13211. if (isKTX) {
  13212. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13213. }
  13214. else if (BABYLON.Tools.UseFallbackTexture) {
  13215. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13216. }
  13217. if (onError) {
  13218. onError(message || "Unknown error", exception);
  13219. }
  13220. };
  13221. var callback = null;
  13222. // processing for non-image formats
  13223. if (isKTX || isTGA || isDDS) {
  13224. if (isKTX) {
  13225. callback = function (data) {
  13226. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13227. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13228. ktx.uploadLevels(_this._gl, !noMipmap);
  13229. return false;
  13230. }, samplingMode);
  13231. };
  13232. }
  13233. else if (isTGA) {
  13234. callback = function (arrayBuffer) {
  13235. var data = new Uint8Array(arrayBuffer);
  13236. var header = BABYLON.TGATools.GetTGAHeader(data);
  13237. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13238. BABYLON.TGATools.UploadContent(_this._gl, data);
  13239. return false;
  13240. }, samplingMode);
  13241. };
  13242. }
  13243. else if (isDDS) {
  13244. callback = function (data) {
  13245. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13246. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13247. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13248. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13249. return false;
  13250. }, samplingMode);
  13251. };
  13252. }
  13253. if (!buffer) {
  13254. this._loadFile(url, function (data) {
  13255. if (callback) {
  13256. callback(data);
  13257. }
  13258. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13259. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13260. });
  13261. }
  13262. else {
  13263. if (callback) {
  13264. callback(buffer);
  13265. }
  13266. }
  13267. // image format processing
  13268. }
  13269. else {
  13270. var onload = function (img) {
  13271. if (fromBlob && !_this._doNotHandleContextLost) {
  13272. // We need to store the image if we need to rebuild the texture
  13273. // in case of a webgl context lost
  13274. texture._buffer = img;
  13275. }
  13276. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13277. var gl = _this._gl;
  13278. var isPot = (img.width === potWidth && img.height === potHeight);
  13279. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13280. if (isPot) {
  13281. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13282. return false;
  13283. }
  13284. // Using shaders to rescale because canvas.drawImage is lossy
  13285. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13286. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13287. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13288. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13289. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13291. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13292. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13293. _this._releaseTexture(source);
  13294. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13295. continuationCallback();
  13296. });
  13297. return true;
  13298. }, samplingMode);
  13299. };
  13300. if (!fromData || isBase64)
  13301. if (buffer instanceof HTMLImageElement) {
  13302. onload(buffer);
  13303. }
  13304. else {
  13305. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13306. }
  13307. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13308. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13309. else
  13310. onload(buffer);
  13311. }
  13312. return texture;
  13313. };
  13314. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13315. var _this = this;
  13316. var rtt = this.createRenderTargetTexture({
  13317. width: destination.width,
  13318. height: destination.height,
  13319. }, {
  13320. generateMipMaps: false,
  13321. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13322. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13323. generateDepthBuffer: false,
  13324. generateStencilBuffer: false
  13325. });
  13326. if (!this._rescalePostProcess) {
  13327. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13328. }
  13329. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13330. _this._rescalePostProcess.onApply = function (effect) {
  13331. effect._bindTexture("textureSampler", source);
  13332. };
  13333. var hostingScene = scene;
  13334. if (!hostingScene) {
  13335. hostingScene = _this.scenes[_this.scenes.length - 1];
  13336. }
  13337. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13338. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13339. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13340. _this.unBindFramebuffer(rtt);
  13341. _this._releaseTexture(rtt);
  13342. if (onComplete) {
  13343. onComplete();
  13344. }
  13345. });
  13346. };
  13347. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13348. if (compression === void 0) { compression = null; }
  13349. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13350. if (!texture) {
  13351. return;
  13352. }
  13353. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13354. var internalFormat = this._getInternalFormat(format);
  13355. var textureType = this._getWebGLTextureType(type);
  13356. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13357. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13358. if (!this._doNotHandleContextLost) {
  13359. texture._bufferView = data;
  13360. texture.format = format;
  13361. texture.type = type;
  13362. texture.invertY = invertY;
  13363. texture._compression = compression;
  13364. }
  13365. if (texture.width % 4 !== 0) {
  13366. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13367. }
  13368. if (compression && data) {
  13369. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13370. }
  13371. else {
  13372. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13373. }
  13374. if (texture.generateMipMaps) {
  13375. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13376. }
  13377. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13378. // this.resetTextureCache();
  13379. texture.isReady = true;
  13380. };
  13381. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13382. if (compression === void 0) { compression = null; }
  13383. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13384. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13385. texture.baseWidth = width;
  13386. texture.baseHeight = height;
  13387. texture.width = width;
  13388. texture.height = height;
  13389. texture.format = format;
  13390. texture.generateMipMaps = generateMipMaps;
  13391. texture.samplingMode = samplingMode;
  13392. texture.invertY = invertY;
  13393. texture._compression = compression;
  13394. texture.type = type;
  13395. if (!this._doNotHandleContextLost) {
  13396. texture._bufferView = data;
  13397. }
  13398. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13399. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13400. // Filters
  13401. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13402. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13403. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13404. if (generateMipMaps) {
  13405. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13406. }
  13407. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13408. this._internalTexturesCache.push(texture);
  13409. return texture;
  13410. };
  13411. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13412. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13413. texture.baseWidth = width;
  13414. texture.baseHeight = height;
  13415. if (generateMipMaps) {
  13416. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13417. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13418. }
  13419. // this.resetTextureCache();
  13420. texture.width = width;
  13421. texture.height = height;
  13422. texture.isReady = false;
  13423. texture.generateMipMaps = generateMipMaps;
  13424. texture.samplingMode = samplingMode;
  13425. this.updateTextureSamplingMode(samplingMode, texture);
  13426. this._internalTexturesCache.push(texture);
  13427. return texture;
  13428. };
  13429. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13430. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13431. if (texture.isCube) {
  13432. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13433. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13434. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13435. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13436. }
  13437. else if (texture.is3D) {
  13438. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13439. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13440. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13441. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13442. }
  13443. else {
  13444. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13445. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13446. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13447. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13448. }
  13449. texture.samplingMode = samplingMode;
  13450. };
  13451. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13452. if (premulAlpha === void 0) { premulAlpha = false; }
  13453. if (!texture) {
  13454. return;
  13455. }
  13456. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13457. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13458. if (premulAlpha) {
  13459. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13460. }
  13461. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13462. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13463. if (texture.generateMipMaps) {
  13464. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13465. }
  13466. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13467. if (premulAlpha) {
  13468. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13469. }
  13470. texture.isReady = true;
  13471. };
  13472. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13473. if (!texture || texture._isDisabled) {
  13474. return;
  13475. }
  13476. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13477. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13478. try {
  13479. // Testing video texture support
  13480. if (this._videoTextureSupported === undefined) {
  13481. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13482. if (this._gl.getError() !== 0) {
  13483. this._videoTextureSupported = false;
  13484. }
  13485. else {
  13486. this._videoTextureSupported = true;
  13487. }
  13488. }
  13489. // Copy video through the current working canvas if video texture is not supported
  13490. if (!this._videoTextureSupported) {
  13491. if (!texture._workingCanvas) {
  13492. texture._workingCanvas = document.createElement("canvas");
  13493. var context = texture._workingCanvas.getContext("2d");
  13494. if (!context) {
  13495. throw new Error("Unable to get 2d context");
  13496. }
  13497. texture._workingContext = context;
  13498. texture._workingCanvas.width = texture.width;
  13499. texture._workingCanvas.height = texture.height;
  13500. }
  13501. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13502. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13503. }
  13504. else {
  13505. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13506. }
  13507. if (texture.generateMipMaps) {
  13508. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13509. }
  13510. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13511. // this.resetTextureCache();
  13512. texture.isReady = true;
  13513. }
  13514. catch (ex) {
  13515. // Something unexpected
  13516. // Let's disable the texture
  13517. texture._isDisabled = true;
  13518. }
  13519. };
  13520. /**
  13521. * Updates a depth texture Comparison Mode and Function.
  13522. * If the comparison Function is equal to 0, the mode will be set to none.
  13523. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13524. * @param texture The texture to set the comparison function for
  13525. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13526. */
  13527. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13528. if (this.webGLVersion === 1) {
  13529. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13530. return;
  13531. }
  13532. var gl = this._gl;
  13533. if (texture.isCube) {
  13534. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13535. if (comparisonFunction === 0) {
  13536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13538. }
  13539. else {
  13540. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13541. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13542. }
  13543. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13544. }
  13545. else {
  13546. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13547. if (comparisonFunction === 0) {
  13548. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13549. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13550. }
  13551. else {
  13552. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13553. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13554. }
  13555. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13556. }
  13557. texture._comparisonFunction = comparisonFunction;
  13558. };
  13559. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13560. var width = size.width || size;
  13561. var height = size.height || size;
  13562. internalTexture.baseWidth = width;
  13563. internalTexture.baseHeight = height;
  13564. internalTexture.width = width;
  13565. internalTexture.height = height;
  13566. internalTexture.isReady = true;
  13567. internalTexture.samples = 1;
  13568. internalTexture.generateMipMaps = false;
  13569. internalTexture._generateDepthBuffer = true;
  13570. internalTexture._generateStencilBuffer = generateStencil;
  13571. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13572. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13573. internalTexture._comparisonFunction = comparisonFunction;
  13574. var gl = this._gl;
  13575. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13576. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13577. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13578. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13579. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13580. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13581. if (comparisonFunction === 0) {
  13582. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13583. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13584. }
  13585. else {
  13586. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13587. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13588. }
  13589. };
  13590. /**
  13591. * Creates a depth stencil texture.
  13592. * This is only available in WebGL 2 or with the depth texture extension available.
  13593. * @param size The size of face edge in the texture.
  13594. * @param options The options defining the texture.
  13595. * @returns The texture
  13596. */
  13597. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13598. if (options.isCube) {
  13599. var width = size.width || size;
  13600. return this._createDepthStencilCubeTexture(width, options);
  13601. }
  13602. else {
  13603. return this._createDepthStencilTexture(size, options);
  13604. }
  13605. };
  13606. /**
  13607. * Creates a depth stencil texture.
  13608. * This is only available in WebGL 2 or with the depth texture extension available.
  13609. * @param size The size of face edge in the texture.
  13610. * @param options The options defining the texture.
  13611. * @returns The texture
  13612. */
  13613. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13614. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13615. if (!this._caps.depthTextureExtension) {
  13616. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13617. return internalTexture;
  13618. }
  13619. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13620. var gl = this._gl;
  13621. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13622. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13623. if (this.webGLVersion > 1) {
  13624. if (internalOptions.generateStencil) {
  13625. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13626. }
  13627. else {
  13628. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13629. }
  13630. }
  13631. else {
  13632. if (internalOptions.generateStencil) {
  13633. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13634. }
  13635. else {
  13636. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13637. }
  13638. }
  13639. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13640. return internalTexture;
  13641. };
  13642. /**
  13643. * Creates a depth stencil cube texture.
  13644. * This is only available in WebGL 2.
  13645. * @param size The size of face edge in the cube texture.
  13646. * @param options The options defining the cube texture.
  13647. * @returns The cube texture
  13648. */
  13649. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13650. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13651. internalTexture.isCube = true;
  13652. if (this.webGLVersion === 1) {
  13653. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13654. return internalTexture;
  13655. }
  13656. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13657. var gl = this._gl;
  13658. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13659. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13660. // Create the depth/stencil buffer
  13661. for (var face = 0; face < 6; face++) {
  13662. if (internalOptions.generateStencil) {
  13663. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13664. }
  13665. else {
  13666. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13667. }
  13668. }
  13669. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13670. return internalTexture;
  13671. };
  13672. /**
  13673. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13674. * @param renderTarget The render target to set the frame buffer for
  13675. */
  13676. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13677. // Create the framebuffer
  13678. var internalTexture = renderTarget.getInternalTexture();
  13679. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13680. return;
  13681. }
  13682. var gl = this._gl;
  13683. var depthStencilTexture = renderTarget.depthStencilTexture;
  13684. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13685. if (depthStencilTexture.isCube) {
  13686. if (depthStencilTexture._generateStencilBuffer) {
  13687. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13688. }
  13689. else {
  13690. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13691. }
  13692. }
  13693. else {
  13694. if (depthStencilTexture._generateStencilBuffer) {
  13695. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13696. }
  13697. else {
  13698. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13699. }
  13700. }
  13701. this.bindUnboundFramebuffer(null);
  13702. };
  13703. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13704. var fullOptions = new RenderTargetCreationOptions();
  13705. if (options !== undefined && typeof options === "object") {
  13706. fullOptions.generateMipMaps = options.generateMipMaps;
  13707. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13708. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13709. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13710. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13711. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13712. }
  13713. else {
  13714. fullOptions.generateMipMaps = options;
  13715. fullOptions.generateDepthBuffer = true;
  13716. fullOptions.generateStencilBuffer = false;
  13717. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13718. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13719. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13720. }
  13721. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13722. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13723. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13724. }
  13725. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13726. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13727. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13728. }
  13729. var gl = this._gl;
  13730. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13731. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13732. var width = size.width || size;
  13733. var height = size.height || size;
  13734. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13735. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13736. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13737. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13738. }
  13739. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13740. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13741. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13742. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13743. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13744. // Create the framebuffer
  13745. var framebuffer = gl.createFramebuffer();
  13746. this.bindUnboundFramebuffer(framebuffer);
  13747. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13748. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13749. if (fullOptions.generateMipMaps) {
  13750. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13751. }
  13752. // Unbind
  13753. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13754. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13755. this.bindUnboundFramebuffer(null);
  13756. texture._framebuffer = framebuffer;
  13757. texture.baseWidth = width;
  13758. texture.baseHeight = height;
  13759. texture.width = width;
  13760. texture.height = height;
  13761. texture.isReady = true;
  13762. texture.samples = 1;
  13763. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13764. texture.samplingMode = fullOptions.samplingMode;
  13765. texture.type = fullOptions.type;
  13766. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13767. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13768. // this.resetTextureCache();
  13769. this._internalTexturesCache.push(texture);
  13770. return texture;
  13771. };
  13772. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13773. var generateMipMaps = false;
  13774. var generateDepthBuffer = true;
  13775. var generateStencilBuffer = false;
  13776. var generateDepthTexture = false;
  13777. var textureCount = 1;
  13778. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13779. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13780. var types = [], samplingModes = [];
  13781. if (options !== undefined) {
  13782. generateMipMaps = options.generateMipMaps;
  13783. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13784. generateStencilBuffer = options.generateStencilBuffer;
  13785. generateDepthTexture = options.generateDepthTexture;
  13786. textureCount = options.textureCount || 1;
  13787. if (options.types) {
  13788. types = options.types;
  13789. }
  13790. if (options.samplingModes) {
  13791. samplingModes = options.samplingModes;
  13792. }
  13793. }
  13794. var gl = this._gl;
  13795. // Create the framebuffer
  13796. var framebuffer = gl.createFramebuffer();
  13797. this.bindUnboundFramebuffer(framebuffer);
  13798. var width = size.width || size;
  13799. var height = size.height || size;
  13800. var textures = [];
  13801. var attachments = [];
  13802. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13803. for (var i = 0; i < textureCount; i++) {
  13804. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13805. var type = types[i] || defaultType;
  13806. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13807. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13808. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13809. }
  13810. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13811. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13812. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13813. }
  13814. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13815. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13816. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13817. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13818. }
  13819. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13820. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13821. textures.push(texture);
  13822. attachments.push(attachment);
  13823. gl.activeTexture(gl["TEXTURE" + i]);
  13824. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13825. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13826. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13827. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13828. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13829. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13830. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13831. if (generateMipMaps) {
  13832. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13833. }
  13834. // Unbind
  13835. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13836. texture._framebuffer = framebuffer;
  13837. texture._depthStencilBuffer = depthStencilBuffer;
  13838. texture.baseWidth = width;
  13839. texture.baseHeight = height;
  13840. texture.width = width;
  13841. texture.height = height;
  13842. texture.isReady = true;
  13843. texture.samples = 1;
  13844. texture.generateMipMaps = generateMipMaps;
  13845. texture.samplingMode = samplingMode;
  13846. texture.type = type;
  13847. texture._generateDepthBuffer = generateDepthBuffer;
  13848. texture._generateStencilBuffer = generateStencilBuffer;
  13849. texture._attachments = attachments;
  13850. this._internalTexturesCache.push(texture);
  13851. }
  13852. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13853. // Depth texture
  13854. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13855. gl.activeTexture(gl.TEXTURE0);
  13856. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13858. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13859. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13860. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13861. 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);
  13862. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13863. depthTexture._framebuffer = framebuffer;
  13864. depthTexture.baseWidth = width;
  13865. depthTexture.baseHeight = height;
  13866. depthTexture.width = width;
  13867. depthTexture.height = height;
  13868. depthTexture.isReady = true;
  13869. depthTexture.samples = 1;
  13870. depthTexture.generateMipMaps = generateMipMaps;
  13871. depthTexture.samplingMode = gl.NEAREST;
  13872. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13873. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13874. textures.push(depthTexture);
  13875. this._internalTexturesCache.push(depthTexture);
  13876. }
  13877. gl.drawBuffers(attachments);
  13878. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13879. this.bindUnboundFramebuffer(null);
  13880. this.resetTextureCache();
  13881. return textures;
  13882. };
  13883. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13884. if (samples === void 0) { samples = 1; }
  13885. var depthStencilBuffer = null;
  13886. var gl = this._gl;
  13887. // Create the depth/stencil buffer
  13888. if (generateStencilBuffer) {
  13889. depthStencilBuffer = gl.createRenderbuffer();
  13890. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13891. if (samples > 1) {
  13892. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13893. }
  13894. else {
  13895. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13896. }
  13897. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13898. }
  13899. else if (generateDepthBuffer) {
  13900. depthStencilBuffer = gl.createRenderbuffer();
  13901. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13902. if (samples > 1) {
  13903. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13904. }
  13905. else {
  13906. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13907. }
  13908. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13909. }
  13910. return depthStencilBuffer;
  13911. };
  13912. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13913. if (this.webGLVersion < 2 || !texture) {
  13914. return 1;
  13915. }
  13916. if (texture.samples === samples) {
  13917. return samples;
  13918. }
  13919. var gl = this._gl;
  13920. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13921. // Dispose previous render buffers
  13922. if (texture._depthStencilBuffer) {
  13923. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13924. texture._depthStencilBuffer = null;
  13925. }
  13926. if (texture._MSAAFramebuffer) {
  13927. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13928. texture._MSAAFramebuffer = null;
  13929. }
  13930. if (texture._MSAARenderBuffer) {
  13931. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13932. texture._MSAARenderBuffer = null;
  13933. }
  13934. if (samples > 1) {
  13935. var framebuffer = gl.createFramebuffer();
  13936. if (!framebuffer) {
  13937. throw new Error("Unable to create multi sampled framebuffer");
  13938. }
  13939. texture._MSAAFramebuffer = framebuffer;
  13940. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13941. var colorRenderbuffer = gl.createRenderbuffer();
  13942. if (!colorRenderbuffer) {
  13943. throw new Error("Unable to create multi sampled framebuffer");
  13944. }
  13945. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13946. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13947. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13948. texture._MSAARenderBuffer = colorRenderbuffer;
  13949. }
  13950. else {
  13951. this.bindUnboundFramebuffer(texture._framebuffer);
  13952. }
  13953. texture.samples = samples;
  13954. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13955. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13956. this.bindUnboundFramebuffer(null);
  13957. return samples;
  13958. };
  13959. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13960. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13961. return 1;
  13962. }
  13963. if (textures[0].samples === samples) {
  13964. return samples;
  13965. }
  13966. var gl = this._gl;
  13967. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13968. // Dispose previous render buffers
  13969. if (textures[0]._depthStencilBuffer) {
  13970. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13971. textures[0]._depthStencilBuffer = null;
  13972. }
  13973. if (textures[0]._MSAAFramebuffer) {
  13974. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13975. textures[0]._MSAAFramebuffer = null;
  13976. }
  13977. for (var i = 0; i < textures.length; i++) {
  13978. if (textures[i]._MSAARenderBuffer) {
  13979. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13980. textures[i]._MSAARenderBuffer = null;
  13981. }
  13982. }
  13983. if (samples > 1) {
  13984. var framebuffer = gl.createFramebuffer();
  13985. if (!framebuffer) {
  13986. throw new Error("Unable to create multi sampled framebuffer");
  13987. }
  13988. this.bindUnboundFramebuffer(framebuffer);
  13989. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13990. var attachments = [];
  13991. for (var i = 0; i < textures.length; i++) {
  13992. var texture = textures[i];
  13993. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13994. var colorRenderbuffer = gl.createRenderbuffer();
  13995. if (!colorRenderbuffer) {
  13996. throw new Error("Unable to create multi sampled framebuffer");
  13997. }
  13998. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13999. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14000. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  14001. texture._MSAAFramebuffer = framebuffer;
  14002. texture._MSAARenderBuffer = colorRenderbuffer;
  14003. texture.samples = samples;
  14004. texture._depthStencilBuffer = depthStencilBuffer;
  14005. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14006. attachments.push(attachment);
  14007. }
  14008. gl.drawBuffers(attachments);
  14009. }
  14010. else {
  14011. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  14012. }
  14013. this.bindUnboundFramebuffer(null);
  14014. return samples;
  14015. };
  14016. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  14017. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  14018. };
  14019. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  14020. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  14021. };
  14022. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  14023. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  14024. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  14025. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14026. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14027. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14028. }
  14029. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14030. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14031. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14032. }
  14033. var gl = this._gl;
  14034. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14035. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14036. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  14037. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14038. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14039. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  14040. }
  14041. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14043. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14044. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14045. for (var face = 0; face < 6; face++) {
  14046. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14047. }
  14048. // Create the framebuffer
  14049. var framebuffer = gl.createFramebuffer();
  14050. this.bindUnboundFramebuffer(framebuffer);
  14051. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14052. // MipMaps
  14053. if (fullOptions.generateMipMaps) {
  14054. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14055. }
  14056. // Unbind
  14057. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14058. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14059. this.bindUnboundFramebuffer(null);
  14060. texture._framebuffer = framebuffer;
  14061. texture.width = size;
  14062. texture.height = size;
  14063. texture.isReady = true;
  14064. texture.isCube = true;
  14065. texture.samples = 1;
  14066. texture.generateMipMaps = fullOptions.generateMipMaps;
  14067. texture.samplingMode = fullOptions.samplingMode;
  14068. texture.type = fullOptions.type;
  14069. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14070. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14071. this._internalTexturesCache.push(texture);
  14072. return texture;
  14073. };
  14074. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14075. var _this = this;
  14076. if (onLoad === void 0) { onLoad = null; }
  14077. if (onError === void 0) { onError = null; }
  14078. if (forcedExtension === void 0) { forcedExtension = null; }
  14079. var callback = function (loadData) {
  14080. if (!loadData) {
  14081. if (onLoad) {
  14082. onLoad(null);
  14083. }
  14084. return;
  14085. }
  14086. var texture = loadData.texture;
  14087. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14088. texture._lodGenerationScale = scale;
  14089. texture._lodGenerationOffset = offset;
  14090. if (_this._caps.textureLOD) {
  14091. // Do not add extra process if texture lod is supported.
  14092. if (onLoad) {
  14093. onLoad(texture);
  14094. }
  14095. return;
  14096. }
  14097. var mipSlices = 3;
  14098. var gl = _this._gl;
  14099. var width = loadData.width;
  14100. if (!width) {
  14101. return;
  14102. }
  14103. var textures = [];
  14104. for (var i = 0; i < mipSlices; i++) {
  14105. //compute LOD from even spacing in smoothness (matching shader calculation)
  14106. var smoothness = i / (mipSlices - 1);
  14107. var roughness = 1 - smoothness;
  14108. var minLODIndex = offset; // roughness = 0
  14109. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14110. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14111. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14112. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14113. glTextureFromLod.isCube = true;
  14114. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14116. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14117. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14118. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14119. if (loadData.isDDS) {
  14120. var info = loadData.info;
  14121. var data = loadData.data;
  14122. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14123. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14124. }
  14125. else {
  14126. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14127. }
  14128. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14129. // Wrap in a base texture for easy binding.
  14130. var lodTexture = new BABYLON.BaseTexture(scene);
  14131. lodTexture.isCube = true;
  14132. lodTexture._texture = glTextureFromLod;
  14133. glTextureFromLod.isReady = true;
  14134. textures.push(lodTexture);
  14135. }
  14136. texture._lodTextureHigh = textures[2];
  14137. texture._lodTextureMid = textures[1];
  14138. texture._lodTextureLow = textures[0];
  14139. if (onLoad) {
  14140. onLoad(texture);
  14141. }
  14142. };
  14143. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14144. };
  14145. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14146. var _this = this;
  14147. if (onLoad === void 0) { onLoad = null; }
  14148. if (onError === void 0) { onError = null; }
  14149. if (forcedExtension === void 0) { forcedExtension = null; }
  14150. var gl = this._gl;
  14151. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14152. texture.isCube = true;
  14153. texture.url = rootUrl;
  14154. texture.generateMipMaps = !noMipmap;
  14155. if (!this._doNotHandleContextLost) {
  14156. texture._extension = forcedExtension;
  14157. texture._files = files;
  14158. }
  14159. var isKTX = false;
  14160. var isDDS = false;
  14161. var lastDot = rootUrl.lastIndexOf('.');
  14162. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14163. if (this._textureFormatInUse) {
  14164. extension = this._textureFormatInUse;
  14165. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14166. isKTX = true;
  14167. }
  14168. else {
  14169. isDDS = (extension === ".dds");
  14170. }
  14171. var onerror = function (request, exception) {
  14172. if (onError && request) {
  14173. onError(request.status + " " + request.statusText, exception);
  14174. }
  14175. };
  14176. if (isKTX) {
  14177. this._loadFile(rootUrl, function (data) {
  14178. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14179. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14180. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14181. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14182. ktx.uploadLevels(_this._gl, !noMipmap);
  14183. _this.setCubeMapTextureParams(gl, loadMipmap);
  14184. texture.width = ktx.pixelWidth;
  14185. texture.height = ktx.pixelHeight;
  14186. texture.isReady = true;
  14187. }, undefined, undefined, true, onerror);
  14188. }
  14189. else if (isDDS) {
  14190. if (files && files.length === 6) {
  14191. this._cascadeLoadFiles(scene, function (imgs) {
  14192. var info;
  14193. var loadMipmap = false;
  14194. var width = 0;
  14195. for (var index = 0; index < imgs.length; index++) {
  14196. var data = imgs[index];
  14197. info = BABYLON.DDSTools.GetDDSInfo(data);
  14198. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14199. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14200. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14201. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14202. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14203. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14204. }
  14205. texture.width = info.width;
  14206. texture.height = info.height;
  14207. texture.type = info.textureType;
  14208. width = info.width;
  14209. }
  14210. _this.setCubeMapTextureParams(gl, loadMipmap);
  14211. texture.isReady = true;
  14212. if (onLoad) {
  14213. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14214. }
  14215. }, files, onError);
  14216. }
  14217. else {
  14218. this._loadFile(rootUrl, function (data) {
  14219. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14220. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14221. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14222. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14223. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14224. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14225. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14226. }
  14227. _this.setCubeMapTextureParams(gl, loadMipmap);
  14228. texture.width = info.width;
  14229. texture.height = info.height;
  14230. texture.isReady = true;
  14231. texture.type = info.textureType;
  14232. if (onLoad) {
  14233. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14234. }
  14235. }, undefined, undefined, true, onerror);
  14236. }
  14237. }
  14238. else {
  14239. if (!files) {
  14240. throw new Error("Cannot load cubemap because files were not defined");
  14241. }
  14242. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14243. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14244. var height = width;
  14245. _this._prepareWorkingCanvas();
  14246. if (!_this._workingCanvas || !_this._workingContext) {
  14247. return;
  14248. }
  14249. _this._workingCanvas.width = width;
  14250. _this._workingCanvas.height = height;
  14251. var faces = [
  14252. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14253. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14254. ];
  14255. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14256. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14257. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14258. for (var index = 0; index < faces.length; index++) {
  14259. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14260. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14261. }
  14262. if (!noMipmap) {
  14263. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14264. }
  14265. _this.setCubeMapTextureParams(gl, !noMipmap);
  14266. texture.width = width;
  14267. texture.height = height;
  14268. texture.isReady = true;
  14269. if (format) {
  14270. texture.format = format;
  14271. }
  14272. texture.onLoadedObservable.notifyObservers(texture);
  14273. texture.onLoadedObservable.clear();
  14274. if (onLoad) {
  14275. onLoad();
  14276. }
  14277. }, files, onError);
  14278. }
  14279. this._internalTexturesCache.push(texture);
  14280. return texture;
  14281. };
  14282. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14283. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14284. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14285. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14286. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14287. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14288. // this.resetTextureCache();
  14289. };
  14290. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14291. if (compression === void 0) { compression = null; }
  14292. if (level === void 0) { level = 0; }
  14293. texture._bufferViewArray = data;
  14294. texture.format = format;
  14295. texture.type = type;
  14296. texture.invertY = invertY;
  14297. texture._compression = compression;
  14298. var gl = this._gl;
  14299. var textureType = this._getWebGLTextureType(type);
  14300. var internalFormat = this._getInternalFormat(format);
  14301. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14302. var needConversion = false;
  14303. if (internalFormat === gl.RGB) {
  14304. internalFormat = gl.RGBA;
  14305. needConversion = true;
  14306. }
  14307. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14308. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14309. if (texture.width % 4 !== 0) {
  14310. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14311. }
  14312. // Data are known to be in +X +Y +Z -X -Y -Z
  14313. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14314. var faceData = data[faceIndex];
  14315. if (compression) {
  14316. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14317. }
  14318. else {
  14319. if (needConversion) {
  14320. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14321. }
  14322. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14323. }
  14324. }
  14325. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14326. if (isPot && texture.generateMipMaps && level === 0) {
  14327. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14328. }
  14329. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14330. // this.resetTextureCache();
  14331. texture.isReady = true;
  14332. };
  14333. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14334. if (compression === void 0) { compression = null; }
  14335. var gl = this._gl;
  14336. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14337. texture.isCube = true;
  14338. texture.generateMipMaps = generateMipMaps;
  14339. texture.format = format;
  14340. texture.type = type;
  14341. if (!this._doNotHandleContextLost) {
  14342. texture._bufferViewArray = data;
  14343. }
  14344. var textureType = this._getWebGLTextureType(type);
  14345. var internalFormat = this._getInternalFormat(format);
  14346. if (internalFormat === gl.RGB) {
  14347. internalFormat = gl.RGBA;
  14348. }
  14349. var width = size;
  14350. var height = width;
  14351. texture.width = width;
  14352. texture.height = height;
  14353. // Double check on POT to generate Mips.
  14354. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14355. if (!isPot) {
  14356. generateMipMaps = false;
  14357. }
  14358. // Upload data if needed. The texture won't be ready until then.
  14359. if (data) {
  14360. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14361. }
  14362. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14363. // Filters
  14364. if (data && generateMipMaps) {
  14365. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14366. }
  14367. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14368. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14369. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14370. }
  14371. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14373. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14374. }
  14375. else {
  14376. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14377. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14378. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14379. }
  14380. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14382. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14383. return texture;
  14384. };
  14385. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14386. var _this = this;
  14387. if (onLoad === void 0) { onLoad = null; }
  14388. if (onError === void 0) { onError = null; }
  14389. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14390. if (invertY === void 0) { invertY = false; }
  14391. var gl = this._gl;
  14392. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14393. scene._addPendingData(texture);
  14394. texture.url = url;
  14395. this._internalTexturesCache.push(texture);
  14396. var onerror = function (request, exception) {
  14397. scene._removePendingData(texture);
  14398. if (onError && request) {
  14399. onError(request.status + " " + request.statusText, exception);
  14400. }
  14401. };
  14402. var internalCallback = function (data) {
  14403. var width = texture.width;
  14404. var faceDataArrays = callback(data);
  14405. if (!faceDataArrays) {
  14406. return;
  14407. }
  14408. if (mipmmapGenerator) {
  14409. var textureType = _this._getWebGLTextureType(type);
  14410. var internalFormat = _this._getInternalFormat(format);
  14411. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14412. var needConversion = false;
  14413. if (internalFormat === gl.RGB) {
  14414. internalFormat = gl.RGBA;
  14415. needConversion = true;
  14416. }
  14417. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14418. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14419. var mipData = mipmmapGenerator(faceDataArrays);
  14420. for (var level = 0; level < mipData.length; level++) {
  14421. var mipSize = width >> level;
  14422. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14423. var mipFaceData = mipData[level][faceIndex];
  14424. if (needConversion) {
  14425. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14426. }
  14427. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14428. }
  14429. }
  14430. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14431. }
  14432. else {
  14433. texture.generateMipMaps = !noMipmap;
  14434. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14435. }
  14436. texture.isReady = true;
  14437. // this.resetTextureCache();
  14438. scene._removePendingData(texture);
  14439. if (onLoad) {
  14440. onLoad();
  14441. }
  14442. };
  14443. this._loadFile(url, function (data) {
  14444. internalCallback(data);
  14445. }, undefined, scene.database, true, onerror);
  14446. return texture;
  14447. };
  14448. ;
  14449. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14450. if (compression === void 0) { compression = null; }
  14451. var internalFormat = this._getInternalFormat(format);
  14452. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14453. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14454. if (!this._doNotHandleContextLost) {
  14455. texture._bufferView = data;
  14456. texture.format = format;
  14457. texture.invertY = invertY;
  14458. texture._compression = compression;
  14459. }
  14460. if (texture.width % 4 !== 0) {
  14461. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14462. }
  14463. if (compression && data) {
  14464. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14465. }
  14466. else {
  14467. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14468. }
  14469. if (texture.generateMipMaps) {
  14470. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14471. }
  14472. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14473. // this.resetTextureCache();
  14474. texture.isReady = true;
  14475. };
  14476. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14477. if (compression === void 0) { compression = null; }
  14478. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14479. texture.baseWidth = width;
  14480. texture.baseHeight = height;
  14481. texture.baseDepth = depth;
  14482. texture.width = width;
  14483. texture.height = height;
  14484. texture.depth = depth;
  14485. texture.format = format;
  14486. texture.generateMipMaps = generateMipMaps;
  14487. texture.samplingMode = samplingMode;
  14488. texture.is3D = true;
  14489. if (!this._doNotHandleContextLost) {
  14490. texture._bufferView = data;
  14491. }
  14492. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14493. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14494. // Filters
  14495. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14496. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14497. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14498. if (generateMipMaps) {
  14499. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14500. }
  14501. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14502. this._internalTexturesCache.push(texture);
  14503. return texture;
  14504. };
  14505. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14506. var gl = this._gl;
  14507. if (!gl) {
  14508. return;
  14509. }
  14510. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14511. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14512. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14513. if (!noMipmap && !isCompressed) {
  14514. gl.generateMipmap(gl.TEXTURE_2D);
  14515. }
  14516. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14517. // this.resetTextureCache();
  14518. if (scene) {
  14519. scene._removePendingData(texture);
  14520. }
  14521. texture.onLoadedObservable.notifyObservers(texture);
  14522. texture.onLoadedObservable.clear();
  14523. };
  14524. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14525. var _this = this;
  14526. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14527. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14528. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14529. var gl = this._gl;
  14530. if (!gl) {
  14531. return;
  14532. }
  14533. if (!texture._webGLTexture) {
  14534. // this.resetTextureCache();
  14535. if (scene) {
  14536. scene._removePendingData(texture);
  14537. }
  14538. return;
  14539. }
  14540. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14541. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14542. texture.baseWidth = width;
  14543. texture.baseHeight = height;
  14544. texture.width = potWidth;
  14545. texture.height = potHeight;
  14546. texture.isReady = true;
  14547. if (processFunction(potWidth, potHeight, function () {
  14548. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14549. })) {
  14550. // Returning as texture needs extra async steps
  14551. return;
  14552. }
  14553. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14554. };
  14555. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14556. // Create new RGBA data container.
  14557. var rgbaData;
  14558. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14559. rgbaData = new Float32Array(width * height * 4);
  14560. }
  14561. else {
  14562. rgbaData = new Uint32Array(width * height * 4);
  14563. }
  14564. // Convert each pixel.
  14565. for (var x = 0; x < width; x++) {
  14566. for (var y = 0; y < height; y++) {
  14567. var index = (y * width + x) * 3;
  14568. var newIndex = (y * width + x) * 4;
  14569. // Map Old Value to new value.
  14570. rgbaData[newIndex + 0] = rgbData[index + 0];
  14571. rgbaData[newIndex + 1] = rgbData[index + 1];
  14572. rgbaData[newIndex + 2] = rgbData[index + 2];
  14573. // Add fully opaque alpha channel.
  14574. rgbaData[newIndex + 3] = 1;
  14575. }
  14576. }
  14577. return rgbaData;
  14578. };
  14579. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14580. var gl = this._gl;
  14581. if (texture._framebuffer) {
  14582. gl.deleteFramebuffer(texture._framebuffer);
  14583. texture._framebuffer = null;
  14584. }
  14585. if (texture._depthStencilBuffer) {
  14586. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14587. texture._depthStencilBuffer = null;
  14588. }
  14589. if (texture._MSAAFramebuffer) {
  14590. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14591. texture._MSAAFramebuffer = null;
  14592. }
  14593. if (texture._MSAARenderBuffer) {
  14594. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14595. texture._MSAARenderBuffer = null;
  14596. }
  14597. };
  14598. Engine.prototype._releaseTexture = function (texture) {
  14599. var gl = this._gl;
  14600. this._releaseFramebufferObjects(texture);
  14601. gl.deleteTexture(texture._webGLTexture);
  14602. // Unbind channels
  14603. this.unbindAllTextures();
  14604. var index = this._internalTexturesCache.indexOf(texture);
  14605. if (index !== -1) {
  14606. this._internalTexturesCache.splice(index, 1);
  14607. }
  14608. // Integrated fixed lod samplers.
  14609. if (texture._lodTextureHigh) {
  14610. texture._lodTextureHigh.dispose();
  14611. }
  14612. if (texture._lodTextureMid) {
  14613. texture._lodTextureMid.dispose();
  14614. }
  14615. if (texture._lodTextureLow) {
  14616. texture._lodTextureLow.dispose();
  14617. }
  14618. };
  14619. Engine.prototype.setProgram = function (program) {
  14620. if (this._currentProgram !== program) {
  14621. this._gl.useProgram(program);
  14622. this._currentProgram = program;
  14623. }
  14624. };
  14625. Engine.prototype.bindSamplers = function (effect) {
  14626. this.setProgram(effect.getProgram());
  14627. var samplers = effect.getSamplers();
  14628. for (var index = 0; index < samplers.length; index++) {
  14629. var uniform = effect.getUniform(samplers[index]);
  14630. if (uniform) {
  14631. this._boundUniforms[index] = uniform;
  14632. }
  14633. }
  14634. this._currentEffect = null;
  14635. };
  14636. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14637. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14638. return;
  14639. }
  14640. // Remove
  14641. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14642. // Bind last to it
  14643. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14644. // Bind to dummy
  14645. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14646. };
  14647. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14648. if (!internalTexture) {
  14649. return -1;
  14650. }
  14651. internalTexture._initialSlot = channel;
  14652. if (this.disableTextureBindingOptimization) {
  14653. if (channel !== internalTexture._designatedSlot) {
  14654. this._textureCollisions.addCount(1, false);
  14655. }
  14656. }
  14657. else {
  14658. if (channel !== internalTexture._designatedSlot) {
  14659. if (internalTexture._designatedSlot > -1) {
  14660. return internalTexture._designatedSlot;
  14661. }
  14662. else {
  14663. // No slot for this texture, let's pick a new one (if we find a free slot)
  14664. if (this._nextFreeTextureSlots.length) {
  14665. return this._nextFreeTextureSlots[0];
  14666. }
  14667. // We need to recycle the oldest bound texture, sorry.
  14668. this._textureCollisions.addCount(1, false);
  14669. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14670. }
  14671. }
  14672. }
  14673. return channel;
  14674. };
  14675. Engine.prototype._linkTrackers = function (previous, next) {
  14676. previous.next = next;
  14677. next.previous = previous;
  14678. };
  14679. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14680. var currentSlot = internalTexture._designatedSlot;
  14681. if (currentSlot === -1) {
  14682. return -1;
  14683. }
  14684. internalTexture._designatedSlot = -1;
  14685. if (this.disableTextureBindingOptimization) {
  14686. return -1;
  14687. }
  14688. // Remove from bound list
  14689. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14690. // Free the slot
  14691. this._boundTexturesCache[currentSlot] = null;
  14692. this._nextFreeTextureSlots.push(currentSlot);
  14693. return currentSlot;
  14694. };
  14695. Engine.prototype._activateCurrentTexture = function () {
  14696. if (this._currentTextureChannel !== this._activeChannel) {
  14697. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14698. this._currentTextureChannel = this._activeChannel;
  14699. }
  14700. };
  14701. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14702. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14703. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14704. this._activeChannel = texture._designatedSlot;
  14705. }
  14706. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14707. var isTextureForRendering = texture && texture._initialSlot > -1;
  14708. if (currentTextureBound !== texture) {
  14709. if (currentTextureBound) {
  14710. this._removeDesignatedSlot(currentTextureBound);
  14711. }
  14712. this._activateCurrentTexture();
  14713. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14714. this._boundTexturesCache[this._activeChannel] = texture;
  14715. if (texture) {
  14716. if (!this.disableTextureBindingOptimization) {
  14717. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14718. if (slotIndex > -1) {
  14719. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14720. }
  14721. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14722. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14723. }
  14724. texture._designatedSlot = this._activeChannel;
  14725. }
  14726. }
  14727. else if (forTextureDataUpdate) {
  14728. this._activateCurrentTexture();
  14729. }
  14730. if (isTextureForRendering && !forTextureDataUpdate) {
  14731. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14732. }
  14733. };
  14734. Engine.prototype._bindTexture = function (channel, texture) {
  14735. if (channel < 0) {
  14736. return;
  14737. }
  14738. if (texture) {
  14739. channel = this._getCorrectTextureChannel(channel, texture);
  14740. }
  14741. this._activeChannel = channel;
  14742. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14743. };
  14744. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14745. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14746. };
  14747. Engine.prototype.unbindAllTextures = function () {
  14748. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14749. this._activeChannel = channel;
  14750. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14751. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14752. if (this.webGLVersion > 1) {
  14753. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14754. }
  14755. }
  14756. };
  14757. /**
  14758. * Sets a texture to the according uniform.
  14759. * @param channel The texture channel
  14760. * @param uniform The uniform to set
  14761. * @param texture The texture to apply
  14762. */
  14763. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14764. if (channel < 0) {
  14765. return;
  14766. }
  14767. if (uniform) {
  14768. this._boundUniforms[channel] = uniform;
  14769. }
  14770. this._setTexture(channel, texture);
  14771. };
  14772. /**
  14773. * Sets a depth stencil texture from a render target to the according uniform.
  14774. * @param channel The texture channel
  14775. * @param uniform The uniform to set
  14776. * @param texture The render target texture containing the depth stencil texture to apply
  14777. */
  14778. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14779. if (channel < 0) {
  14780. return;
  14781. }
  14782. if (uniform) {
  14783. this._boundUniforms[channel] = uniform;
  14784. }
  14785. if (!texture || !texture.depthStencilTexture) {
  14786. this._setTexture(channel, null);
  14787. }
  14788. else {
  14789. this._setTexture(channel, texture, false, true);
  14790. }
  14791. };
  14792. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14793. var uniform = this._boundUniforms[sourceSlot];
  14794. if (uniform._currentState === destination) {
  14795. return;
  14796. }
  14797. this._gl.uniform1i(uniform, destination);
  14798. uniform._currentState = destination;
  14799. };
  14800. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14801. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14802. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14803. // Not ready?
  14804. if (!texture) {
  14805. if (this._boundTexturesCache[channel] != null) {
  14806. this._activeChannel = channel;
  14807. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14808. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14809. if (this.webGLVersion > 1) {
  14810. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14811. }
  14812. }
  14813. return false;
  14814. }
  14815. // Video
  14816. if (texture.video) {
  14817. this._activeChannel = channel;
  14818. texture.update();
  14819. }
  14820. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14821. texture.delayLoad();
  14822. return false;
  14823. }
  14824. var internalTexture;
  14825. if (depthStencilTexture) {
  14826. internalTexture = texture.depthStencilTexture;
  14827. }
  14828. else if (texture.isReady()) {
  14829. internalTexture = texture.getInternalTexture();
  14830. }
  14831. else if (texture.isCube) {
  14832. internalTexture = this.emptyCubeTexture;
  14833. }
  14834. else if (texture.is3D) {
  14835. internalTexture = this.emptyTexture3D;
  14836. }
  14837. else {
  14838. internalTexture = this.emptyTexture;
  14839. }
  14840. if (!isPartOfTextureArray) {
  14841. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14842. }
  14843. if (this._boundTexturesCache[channel] === internalTexture) {
  14844. this._moveBoundTextureOnTop(internalTexture);
  14845. if (!isPartOfTextureArray) {
  14846. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14847. }
  14848. return false;
  14849. }
  14850. this._activeChannel = channel;
  14851. if (internalTexture && internalTexture.is3D) {
  14852. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14853. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14854. internalTexture._cachedWrapU = texture.wrapU;
  14855. switch (texture.wrapU) {
  14856. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14857. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14858. break;
  14859. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14860. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14861. break;
  14862. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14863. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14864. break;
  14865. }
  14866. }
  14867. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14868. internalTexture._cachedWrapV = texture.wrapV;
  14869. switch (texture.wrapV) {
  14870. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14871. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14872. break;
  14873. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14874. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14875. break;
  14876. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14877. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14878. break;
  14879. }
  14880. }
  14881. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14882. internalTexture._cachedWrapR = texture.wrapR;
  14883. switch (texture.wrapR) {
  14884. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14885. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14886. break;
  14887. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14888. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14889. break;
  14890. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14891. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14892. break;
  14893. }
  14894. }
  14895. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14896. }
  14897. else if (internalTexture && internalTexture.isCube) {
  14898. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14899. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14900. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14901. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14902. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14903. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14904. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14905. }
  14906. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14907. }
  14908. else {
  14909. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14910. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14911. internalTexture._cachedWrapU = texture.wrapU;
  14912. switch (texture.wrapU) {
  14913. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14914. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14915. break;
  14916. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14917. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14918. break;
  14919. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14920. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14921. break;
  14922. }
  14923. }
  14924. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14925. internalTexture._cachedWrapV = texture.wrapV;
  14926. switch (texture.wrapV) {
  14927. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14928. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14929. break;
  14930. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14931. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14932. break;
  14933. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14934. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14935. break;
  14936. }
  14937. }
  14938. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14939. }
  14940. return true;
  14941. };
  14942. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14943. if (channel < 0 || !uniform) {
  14944. return;
  14945. }
  14946. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14947. this._textureUnits = new Int32Array(textures.length);
  14948. }
  14949. for (var i = 0; i < textures.length; i++) {
  14950. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14951. }
  14952. this._gl.uniform1iv(uniform, this._textureUnits);
  14953. for (var index = 0; index < textures.length; index++) {
  14954. this._setTexture(this._textureUnits[index], textures[index], true);
  14955. }
  14956. };
  14957. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14958. var internalTexture = texture.getInternalTexture();
  14959. if (!internalTexture) {
  14960. return;
  14961. }
  14962. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14963. var value = texture.anisotropicFilteringLevel;
  14964. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14965. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14966. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14967. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14968. }
  14969. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14970. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14971. internalTexture._cachedAnisotropicFilteringLevel = value;
  14972. }
  14973. };
  14974. Engine.prototype.readPixels = function (x, y, width, height) {
  14975. var data = new Uint8Array(height * width * 4);
  14976. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14977. return data;
  14978. };
  14979. /**
  14980. * Add an externaly attached data from its key.
  14981. * This method call will fail and return false, if such key already exists.
  14982. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14983. * @param key the unique key that identifies the data
  14984. * @param data the data object to associate to the key for this Engine instance
  14985. * @return true if no such key were already present and the data was added successfully, false otherwise
  14986. */
  14987. Engine.prototype.addExternalData = function (key, data) {
  14988. if (!this._externalData) {
  14989. this._externalData = new BABYLON.StringDictionary();
  14990. }
  14991. return this._externalData.add(key, data);
  14992. };
  14993. /**
  14994. * Get an externaly attached data from its key
  14995. * @param key the unique key that identifies the data
  14996. * @return the associated data, if present (can be null), or undefined if not present
  14997. */
  14998. Engine.prototype.getExternalData = function (key) {
  14999. if (!this._externalData) {
  15000. this._externalData = new BABYLON.StringDictionary();
  15001. }
  15002. return this._externalData.get(key);
  15003. };
  15004. /**
  15005. * Get an externaly attached data from its key, create it using a factory if it's not already present
  15006. * @param key the unique key that identifies the data
  15007. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  15008. * @return the associated data, can be null if the factory returned null.
  15009. */
  15010. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  15011. if (!this._externalData) {
  15012. this._externalData = new BABYLON.StringDictionary();
  15013. }
  15014. return this._externalData.getOrAddWithFactory(key, factory);
  15015. };
  15016. /**
  15017. * Remove an externaly attached data from the Engine instance
  15018. * @param key the unique key that identifies the data
  15019. * @return true if the data was successfully removed, false if it doesn't exist
  15020. */
  15021. Engine.prototype.removeExternalData = function (key) {
  15022. if (!this._externalData) {
  15023. this._externalData = new BABYLON.StringDictionary();
  15024. }
  15025. return this._externalData.remove(key);
  15026. };
  15027. Engine.prototype.unbindAllAttributes = function () {
  15028. if (this._mustWipeVertexAttributes) {
  15029. this._mustWipeVertexAttributes = false;
  15030. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  15031. this._gl.disableVertexAttribArray(i);
  15032. this._vertexAttribArraysEnabled[i] = false;
  15033. this._currentBufferPointers[i].active = false;
  15034. }
  15035. return;
  15036. }
  15037. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  15038. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  15039. continue;
  15040. }
  15041. this._gl.disableVertexAttribArray(i);
  15042. this._vertexAttribArraysEnabled[i] = false;
  15043. this._currentBufferPointers[i].active = false;
  15044. }
  15045. };
  15046. Engine.prototype.releaseEffects = function () {
  15047. for (var name in this._compiledEffects) {
  15048. this._deleteProgram(this._compiledEffects[name]._program);
  15049. }
  15050. this._compiledEffects = {};
  15051. };
  15052. // Dispose
  15053. Engine.prototype.dispose = function () {
  15054. this.hideLoadingUI();
  15055. this.stopRenderLoop();
  15056. // Release postProcesses
  15057. while (this.postProcesses.length) {
  15058. this.postProcesses[0].dispose();
  15059. }
  15060. // Empty texture
  15061. if (this._emptyTexture) {
  15062. this._releaseTexture(this._emptyTexture);
  15063. this._emptyTexture = null;
  15064. }
  15065. if (this._emptyCubeTexture) {
  15066. this._releaseTexture(this._emptyCubeTexture);
  15067. this._emptyCubeTexture = null;
  15068. }
  15069. // Rescale PP
  15070. if (this._rescalePostProcess) {
  15071. this._rescalePostProcess.dispose();
  15072. }
  15073. // Release scenes
  15074. while (this.scenes.length) {
  15075. this.scenes[0].dispose();
  15076. }
  15077. // Release audio engine
  15078. if (Engine.audioEngine) {
  15079. Engine.audioEngine.dispose();
  15080. }
  15081. // Release effects
  15082. this.releaseEffects();
  15083. // Unbind
  15084. this.unbindAllAttributes();
  15085. if (this._dummyFramebuffer) {
  15086. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15087. }
  15088. //WebVR
  15089. this.disableVR();
  15090. // Events
  15091. if (BABYLON.Tools.IsWindowObjectExist()) {
  15092. window.removeEventListener("blur", this._onBlur);
  15093. window.removeEventListener("focus", this._onFocus);
  15094. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15095. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15096. if (this._renderingCanvas) {
  15097. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15098. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15099. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15100. if (!this._doNotHandleContextLost) {
  15101. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15102. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15103. }
  15104. }
  15105. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15106. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15107. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15108. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15109. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15110. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15111. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15112. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15113. if (this._onVrDisplayConnect) {
  15114. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15115. if (this._onVrDisplayDisconnect) {
  15116. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15117. }
  15118. if (this._onVrDisplayPresentChange) {
  15119. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15120. }
  15121. this._onVrDisplayConnect = null;
  15122. this._onVrDisplayDisconnect = null;
  15123. }
  15124. }
  15125. // Remove from Instances
  15126. var index = Engine.Instances.indexOf(this);
  15127. if (index >= 0) {
  15128. Engine.Instances.splice(index, 1);
  15129. }
  15130. this._workingCanvas = null;
  15131. this._workingContext = null;
  15132. this._currentBufferPointers = [];
  15133. this._renderingCanvas = null;
  15134. this._currentProgram = null;
  15135. this._bindedRenderFunction = null;
  15136. this.onResizeObservable.clear();
  15137. this.onCanvasBlurObservable.clear();
  15138. this.onCanvasFocusObservable.clear();
  15139. this.onCanvasPointerOutObservable.clear();
  15140. this.onBeginFrameObservable.clear();
  15141. this.onEndFrameObservable.clear();
  15142. BABYLON.Effect.ResetCache();
  15143. // Abort active requests
  15144. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15145. var request = _a[_i];
  15146. request.abort();
  15147. }
  15148. };
  15149. // Loading screen
  15150. Engine.prototype.displayLoadingUI = function () {
  15151. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15152. return;
  15153. }
  15154. var loadingScreen = this.loadingScreen;
  15155. if (loadingScreen) {
  15156. loadingScreen.displayLoadingUI();
  15157. }
  15158. };
  15159. Engine.prototype.hideLoadingUI = function () {
  15160. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15161. return;
  15162. }
  15163. var loadingScreen = this.loadingScreen;
  15164. if (loadingScreen) {
  15165. loadingScreen.hideLoadingUI();
  15166. }
  15167. };
  15168. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15169. get: function () {
  15170. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15171. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15172. return this._loadingScreen;
  15173. },
  15174. set: function (loadingScreen) {
  15175. this._loadingScreen = loadingScreen;
  15176. },
  15177. enumerable: true,
  15178. configurable: true
  15179. });
  15180. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15181. set: function (text) {
  15182. this.loadingScreen.loadingUIText = text;
  15183. },
  15184. enumerable: true,
  15185. configurable: true
  15186. });
  15187. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15188. set: function (color) {
  15189. this.loadingScreen.loadingUIBackgroundColor = color;
  15190. },
  15191. enumerable: true,
  15192. configurable: true
  15193. });
  15194. Engine.prototype.attachContextLostEvent = function (callback) {
  15195. if (this._renderingCanvas) {
  15196. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15197. }
  15198. };
  15199. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15200. if (this._renderingCanvas) {
  15201. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15202. }
  15203. };
  15204. Engine.prototype.getVertexShaderSource = function (program) {
  15205. var shaders = this._gl.getAttachedShaders(program);
  15206. if (!shaders) {
  15207. return null;
  15208. }
  15209. return this._gl.getShaderSource(shaders[0]);
  15210. };
  15211. Engine.prototype.getFragmentShaderSource = function (program) {
  15212. var shaders = this._gl.getAttachedShaders(program);
  15213. if (!shaders) {
  15214. return null;
  15215. }
  15216. return this._gl.getShaderSource(shaders[1]);
  15217. };
  15218. Engine.prototype.getError = function () {
  15219. return this._gl.getError();
  15220. };
  15221. // FPS
  15222. Engine.prototype.getFps = function () {
  15223. return this._fps;
  15224. };
  15225. Engine.prototype.getDeltaTime = function () {
  15226. return this._deltaTime;
  15227. };
  15228. Engine.prototype._measureFps = function () {
  15229. this._performanceMonitor.sampleFrame();
  15230. this._fps = this._performanceMonitor.averageFPS;
  15231. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15232. };
  15233. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15234. if (faceIndex === void 0) { faceIndex = -1; }
  15235. var gl = this._gl;
  15236. if (!this._dummyFramebuffer) {
  15237. var dummy = gl.createFramebuffer();
  15238. if (!dummy) {
  15239. throw new Error("Unable to create dummy framebuffer");
  15240. }
  15241. this._dummyFramebuffer = dummy;
  15242. }
  15243. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15244. if (faceIndex > -1) {
  15245. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15246. }
  15247. else {
  15248. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15249. }
  15250. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15251. var buffer;
  15252. switch (readType) {
  15253. case gl.UNSIGNED_BYTE:
  15254. buffer = new Uint8Array(4 * width * height);
  15255. readType = gl.UNSIGNED_BYTE;
  15256. break;
  15257. default:
  15258. buffer = new Float32Array(4 * width * height);
  15259. readType = gl.FLOAT;
  15260. break;
  15261. }
  15262. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15263. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15264. return buffer;
  15265. };
  15266. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15267. if (this._webGLVersion > 1) {
  15268. return this._caps.colorBufferFloat;
  15269. }
  15270. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15271. };
  15272. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15273. if (this._webGLVersion > 1) {
  15274. return this._caps.colorBufferFloat;
  15275. }
  15276. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15277. };
  15278. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15279. Engine.prototype._canRenderToFramebuffer = function (type) {
  15280. var gl = this._gl;
  15281. //clear existing errors
  15282. while (gl.getError() !== gl.NO_ERROR) { }
  15283. var successful = true;
  15284. var texture = gl.createTexture();
  15285. gl.bindTexture(gl.TEXTURE_2D, texture);
  15286. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15287. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15288. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15289. var fb = gl.createFramebuffer();
  15290. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15291. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15292. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15293. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15294. successful = successful && (gl.getError() === gl.NO_ERROR);
  15295. //try render by clearing frame buffer's color buffer
  15296. if (successful) {
  15297. gl.clear(gl.COLOR_BUFFER_BIT);
  15298. successful = successful && (gl.getError() === gl.NO_ERROR);
  15299. }
  15300. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15301. if (successful) {
  15302. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15303. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15304. var readFormat = gl.RGBA;
  15305. var readType = gl.UNSIGNED_BYTE;
  15306. var buffer = new Uint8Array(4);
  15307. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15308. successful = successful && (gl.getError() === gl.NO_ERROR);
  15309. }
  15310. //clean up
  15311. gl.deleteTexture(texture);
  15312. gl.deleteFramebuffer(fb);
  15313. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15314. //clear accumulated errors
  15315. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15316. return successful;
  15317. };
  15318. Engine.prototype._getWebGLTextureType = function (type) {
  15319. if (type === Engine.TEXTURETYPE_FLOAT) {
  15320. return this._gl.FLOAT;
  15321. }
  15322. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15323. // Add Half Float Constant.
  15324. return this._gl.HALF_FLOAT_OES;
  15325. }
  15326. return this._gl.UNSIGNED_BYTE;
  15327. };
  15328. ;
  15329. Engine.prototype._getInternalFormat = function (format) {
  15330. var internalFormat = this._gl.RGBA;
  15331. switch (format) {
  15332. case Engine.TEXTUREFORMAT_ALPHA:
  15333. internalFormat = this._gl.ALPHA;
  15334. break;
  15335. case Engine.TEXTUREFORMAT_LUMINANCE:
  15336. internalFormat = this._gl.LUMINANCE;
  15337. break;
  15338. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15339. internalFormat = this._gl.LUMINANCE_ALPHA;
  15340. break;
  15341. case Engine.TEXTUREFORMAT_RGB:
  15342. case Engine.TEXTUREFORMAT_RGB32F:
  15343. internalFormat = this._gl.RGB;
  15344. break;
  15345. case Engine.TEXTUREFORMAT_RGBA:
  15346. case Engine.TEXTUREFORMAT_RGBA32F:
  15347. internalFormat = this._gl.RGBA;
  15348. break;
  15349. case Engine.TEXTUREFORMAT_R32F:
  15350. internalFormat = this._gl.RED;
  15351. break;
  15352. case Engine.TEXTUREFORMAT_RG32F:
  15353. internalFormat = this._gl.RG;
  15354. break;
  15355. }
  15356. return internalFormat;
  15357. };
  15358. /** @ignore */
  15359. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15360. if (this._webGLVersion === 1) {
  15361. if (format) {
  15362. switch (format) {
  15363. case Engine.TEXTUREFORMAT_LUMINANCE:
  15364. return this._gl.LUMINANCE;
  15365. }
  15366. }
  15367. return this._gl.RGBA;
  15368. }
  15369. if (type === Engine.TEXTURETYPE_FLOAT) {
  15370. if (format) {
  15371. switch (format) {
  15372. case Engine.TEXTUREFORMAT_R32F:
  15373. return this._gl.R32F;
  15374. case Engine.TEXTUREFORMAT_RG32F:
  15375. return this._gl.RG32F;
  15376. case Engine.TEXTUREFORMAT_RGB32F:
  15377. return this._gl.RGB32F;
  15378. }
  15379. }
  15380. return this._gl.RGBA32F;
  15381. }
  15382. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15383. return this._gl.RGBA16F;
  15384. }
  15385. if (format) {
  15386. switch (format) {
  15387. case Engine.TEXTUREFORMAT_LUMINANCE:
  15388. return this._gl.LUMINANCE;
  15389. }
  15390. }
  15391. return this._gl.RGBA;
  15392. };
  15393. ;
  15394. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15395. if (type === Engine.TEXTURETYPE_FLOAT) {
  15396. return this._gl.RGBA32F;
  15397. }
  15398. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15399. return this._gl.RGBA16F;
  15400. }
  15401. return this._gl.RGBA8;
  15402. };
  15403. ;
  15404. Engine.prototype.createQuery = function () {
  15405. return this._gl.createQuery();
  15406. };
  15407. Engine.prototype.deleteQuery = function (query) {
  15408. this._gl.deleteQuery(query);
  15409. return this;
  15410. };
  15411. Engine.prototype.isQueryResultAvailable = function (query) {
  15412. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15413. };
  15414. Engine.prototype.getQueryResult = function (query) {
  15415. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15416. };
  15417. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15418. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15419. this._gl.beginQuery(glAlgorithm, query);
  15420. return this;
  15421. };
  15422. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15423. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15424. this._gl.endQuery(glAlgorithm);
  15425. return this;
  15426. };
  15427. /* Time queries */
  15428. Engine.prototype._createTimeQuery = function () {
  15429. var timerQuery = this._caps.timerQuery;
  15430. if (timerQuery.createQueryEXT) {
  15431. return timerQuery.createQueryEXT();
  15432. }
  15433. return this.createQuery();
  15434. };
  15435. Engine.prototype._deleteTimeQuery = function (query) {
  15436. var timerQuery = this._caps.timerQuery;
  15437. if (timerQuery.deleteQueryEXT) {
  15438. timerQuery.deleteQueryEXT(query);
  15439. return;
  15440. }
  15441. this.deleteQuery(query);
  15442. };
  15443. Engine.prototype._getTimeQueryResult = function (query) {
  15444. var timerQuery = this._caps.timerQuery;
  15445. if (timerQuery.getQueryObjectEXT) {
  15446. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15447. }
  15448. return this.getQueryResult(query);
  15449. };
  15450. Engine.prototype._getTimeQueryAvailability = function (query) {
  15451. var timerQuery = this._caps.timerQuery;
  15452. if (timerQuery.getQueryObjectEXT) {
  15453. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15454. }
  15455. return this.isQueryResultAvailable(query);
  15456. };
  15457. Engine.prototype.startTimeQuery = function () {
  15458. var timerQuery = this._caps.timerQuery;
  15459. if (!timerQuery) {
  15460. return null;
  15461. }
  15462. var token = new BABYLON._TimeToken();
  15463. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15464. if (this._caps.canUseTimestampForTimerQuery) {
  15465. token._startTimeQuery = this._createTimeQuery();
  15466. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15467. }
  15468. else {
  15469. if (this._currentNonTimestampToken) {
  15470. return this._currentNonTimestampToken;
  15471. }
  15472. token._timeElapsedQuery = this._createTimeQuery();
  15473. if (timerQuery.beginQueryEXT) {
  15474. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15475. }
  15476. else {
  15477. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15478. }
  15479. this._currentNonTimestampToken = token;
  15480. }
  15481. return token;
  15482. };
  15483. Engine.prototype.endTimeQuery = function (token) {
  15484. var timerQuery = this._caps.timerQuery;
  15485. if (!timerQuery || !token) {
  15486. return -1;
  15487. }
  15488. if (this._caps.canUseTimestampForTimerQuery) {
  15489. if (!token._startTimeQuery) {
  15490. return -1;
  15491. }
  15492. if (!token._endTimeQuery) {
  15493. token._endTimeQuery = this._createTimeQuery();
  15494. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15495. }
  15496. }
  15497. else if (!token._timeElapsedQueryEnded) {
  15498. if (!token._timeElapsedQuery) {
  15499. return -1;
  15500. }
  15501. if (timerQuery.endQueryEXT) {
  15502. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15503. }
  15504. else {
  15505. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15506. }
  15507. token._timeElapsedQueryEnded = true;
  15508. }
  15509. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15510. var available = false;
  15511. if (token._endTimeQuery) {
  15512. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15513. }
  15514. else if (token._timeElapsedQuery) {
  15515. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15516. }
  15517. if (available && !disjoint) {
  15518. var result = 0;
  15519. if (this._caps.canUseTimestampForTimerQuery) {
  15520. if (!token._startTimeQuery || !token._endTimeQuery) {
  15521. return -1;
  15522. }
  15523. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15524. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15525. result = timeEnd - timeStart;
  15526. this._deleteTimeQuery(token._startTimeQuery);
  15527. this._deleteTimeQuery(token._endTimeQuery);
  15528. token._startTimeQuery = null;
  15529. token._endTimeQuery = null;
  15530. }
  15531. else {
  15532. if (!token._timeElapsedQuery) {
  15533. return -1;
  15534. }
  15535. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15536. this._deleteTimeQuery(token._timeElapsedQuery);
  15537. token._timeElapsedQuery = null;
  15538. token._timeElapsedQueryEnded = false;
  15539. this._currentNonTimestampToken = null;
  15540. }
  15541. return result;
  15542. }
  15543. return -1;
  15544. };
  15545. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15546. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15547. };
  15548. // Transform feedback
  15549. Engine.prototype.createTransformFeedback = function () {
  15550. return this._gl.createTransformFeedback();
  15551. };
  15552. Engine.prototype.deleteTransformFeedback = function (value) {
  15553. this._gl.deleteTransformFeedback(value);
  15554. };
  15555. Engine.prototype.bindTransformFeedback = function (value) {
  15556. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15557. };
  15558. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15559. if (usePoints === void 0) { usePoints = true; }
  15560. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15561. };
  15562. Engine.prototype.endTransformFeedback = function () {
  15563. this._gl.endTransformFeedback();
  15564. };
  15565. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15566. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15567. };
  15568. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15569. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15570. };
  15571. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15572. var _this = this;
  15573. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15574. this._activeRequests.push(request);
  15575. request.onCompleteObservable.add(function (request) {
  15576. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15577. });
  15578. return request;
  15579. };
  15580. /** @ignore */
  15581. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15582. var _this = this;
  15583. return new Promise(function (resolve, reject) {
  15584. _this._loadFile(url, function (data) {
  15585. resolve(data);
  15586. }, undefined, database, useArrayBuffer, function (request, exception) {
  15587. reject(exception);
  15588. });
  15589. });
  15590. };
  15591. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15592. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15593. var onload = function (data) {
  15594. loadedFiles[index] = data;
  15595. loadedFiles._internalCount++;
  15596. if (loadedFiles._internalCount === 6) {
  15597. onfinish(loadedFiles);
  15598. }
  15599. };
  15600. var onerror = function (request, exception) {
  15601. if (onErrorCallBack && request) {
  15602. onErrorCallBack(request.status + " " + request.statusText, exception);
  15603. }
  15604. };
  15605. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15606. };
  15607. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15608. if (onError === void 0) { onError = null; }
  15609. var loadedFiles = [];
  15610. loadedFiles._internalCount = 0;
  15611. for (var index = 0; index < 6; index++) {
  15612. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15613. }
  15614. };
  15615. // Statics
  15616. Engine.isSupported = function () {
  15617. try {
  15618. var tempcanvas = document.createElement("canvas");
  15619. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15620. return gl != null && !!window.WebGLRenderingContext;
  15621. }
  15622. catch (e) {
  15623. return false;
  15624. }
  15625. };
  15626. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15627. Engine.ExceptionList = [
  15628. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15629. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15630. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15631. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15632. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15633. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15634. ];
  15635. Engine.Instances = new Array();
  15636. // Const statics
  15637. Engine._ALPHA_DISABLE = 0;
  15638. Engine._ALPHA_ADD = 1;
  15639. Engine._ALPHA_COMBINE = 2;
  15640. Engine._ALPHA_SUBTRACT = 3;
  15641. Engine._ALPHA_MULTIPLY = 4;
  15642. Engine._ALPHA_MAXIMIZED = 5;
  15643. Engine._ALPHA_ONEONE = 6;
  15644. Engine._ALPHA_PREMULTIPLIED = 7;
  15645. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15646. Engine._ALPHA_INTERPOLATE = 9;
  15647. Engine._ALPHA_SCREENMODE = 10;
  15648. Engine._DELAYLOADSTATE_NONE = 0;
  15649. Engine._DELAYLOADSTATE_LOADED = 1;
  15650. Engine._DELAYLOADSTATE_LOADING = 2;
  15651. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15652. Engine._TEXTUREFORMAT_ALPHA = 0;
  15653. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15654. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15655. Engine._TEXTUREFORMAT_RGB = 4;
  15656. Engine._TEXTUREFORMAT_RGBA = 5;
  15657. Engine._TEXTUREFORMAT_R32F = 6;
  15658. Engine._TEXTUREFORMAT_RG32F = 7;
  15659. Engine._TEXTUREFORMAT_RGB32F = 8;
  15660. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15661. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15662. Engine._TEXTURETYPE_FLOAT = 1;
  15663. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15664. // Depht or Stencil test Constants.
  15665. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15666. 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.
  15667. 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.
  15668. 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.
  15669. 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.
  15670. 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.
  15671. 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.
  15672. 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.
  15673. // Stencil Actions Constants.
  15674. Engine._KEEP = 0x1E00;
  15675. Engine._REPLACE = 0x1E01;
  15676. Engine._INCR = 0x1E02;
  15677. Engine._DECR = 0x1E03;
  15678. Engine._INVERT = 0x150A;
  15679. Engine._INCR_WRAP = 0x8507;
  15680. Engine._DECR_WRAP = 0x8508;
  15681. // Texture rescaling mode
  15682. Engine._SCALEMODE_FLOOR = 1;
  15683. Engine._SCALEMODE_NEAREST = 2;
  15684. Engine._SCALEMODE_CEILING = 3;
  15685. // Updatable statics so stick with vars here
  15686. Engine.CollisionsEpsilon = 0.001;
  15687. Engine.CodeRepository = "src/";
  15688. Engine.ShadersRepository = "src/Shaders/";
  15689. return Engine;
  15690. }());
  15691. BABYLON.Engine = Engine;
  15692. })(BABYLON || (BABYLON = {}));
  15693. //# sourceMappingURL=babylon.engine.js.map
  15694. var BABYLON;
  15695. (function (BABYLON) {
  15696. /**
  15697. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15698. */
  15699. var Node = /** @class */ (function () {
  15700. /**
  15701. * Creates a new Node
  15702. * @param {string} name - the name and id to be given to this node
  15703. * @param {BABYLON.Scene} the scene this node will be added to
  15704. */
  15705. function Node(name, scene) {
  15706. if (scene === void 0) { scene = null; }
  15707. /**
  15708. * Gets or sets a string used to store user defined state for the node
  15709. */
  15710. this.state = "";
  15711. /**
  15712. * Gets or sets an object used to store user defined information for the node
  15713. */
  15714. this.metadata = null;
  15715. /**
  15716. * Gets or sets a boolean used to define if the node must be serialized
  15717. */
  15718. this.doNotSerialize = false;
  15719. /** @ignore */
  15720. this._isDisposed = false;
  15721. /**
  15722. * Gets a list of {BABYLON.Animation} associated with the node
  15723. */
  15724. this.animations = new Array();
  15725. this._ranges = {};
  15726. this._isEnabled = true;
  15727. this._isReady = true;
  15728. /** @ignore */
  15729. this._currentRenderId = -1;
  15730. this._parentRenderId = -1;
  15731. this._animationPropertiesOverride = null;
  15732. /**
  15733. * An event triggered when the mesh is disposed
  15734. * @type {BABYLON.Observable}
  15735. */
  15736. this.onDisposeObservable = new BABYLON.Observable();
  15737. // Behaviors
  15738. this._behaviors = new Array();
  15739. this.name = name;
  15740. this.id = name;
  15741. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15742. this.uniqueId = this._scene.getUniqueId();
  15743. this._initCache();
  15744. }
  15745. /**
  15746. * Gets a boolean indicating if the node has been disposed
  15747. * @returns true if the node was disposed
  15748. */
  15749. Node.prototype.isDisposed = function () {
  15750. return this._isDisposed;
  15751. };
  15752. Object.defineProperty(Node.prototype, "parent", {
  15753. get: function () {
  15754. return this._parentNode;
  15755. },
  15756. /**
  15757. * Gets or sets the parent of the node
  15758. */
  15759. set: function (parent) {
  15760. if (this._parentNode === parent) {
  15761. return;
  15762. }
  15763. // Remove self from list of children of parent
  15764. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15765. var index = this._parentNode._children.indexOf(this);
  15766. if (index !== -1) {
  15767. this._parentNode._children.splice(index, 1);
  15768. }
  15769. }
  15770. // Store new parent
  15771. this._parentNode = parent;
  15772. // Add as child to new parent
  15773. if (this._parentNode) {
  15774. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15775. this._parentNode._children = new Array();
  15776. }
  15777. this._parentNode._children.push(this);
  15778. }
  15779. },
  15780. enumerable: true,
  15781. configurable: true
  15782. });
  15783. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15784. /**
  15785. * Gets or sets the animation properties override
  15786. */
  15787. get: function () {
  15788. return this._animationPropertiesOverride;
  15789. },
  15790. set: function (value) {
  15791. this._animationPropertiesOverride = value;
  15792. },
  15793. enumerable: true,
  15794. configurable: true
  15795. });
  15796. /**
  15797. * Gets a string idenfifying the name of the class
  15798. * @returns "Node" string
  15799. */
  15800. Node.prototype.getClassName = function () {
  15801. return "Node";
  15802. };
  15803. Object.defineProperty(Node.prototype, "onDispose", {
  15804. /**
  15805. * Sets a callback that will be raised when the node will be disposed
  15806. */
  15807. set: function (callback) {
  15808. if (this._onDisposeObserver) {
  15809. this.onDisposeObservable.remove(this._onDisposeObserver);
  15810. }
  15811. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15812. },
  15813. enumerable: true,
  15814. configurable: true
  15815. });
  15816. /**
  15817. * Gets the scene of the node
  15818. * @returns a {BABYLON.Scene}
  15819. */
  15820. Node.prototype.getScene = function () {
  15821. return this._scene;
  15822. };
  15823. /**
  15824. * Gets the engine of the node
  15825. * @returns a {BABYLON.Engine}
  15826. */
  15827. Node.prototype.getEngine = function () {
  15828. return this._scene.getEngine();
  15829. };
  15830. /**
  15831. * Attach a behavior to the node
  15832. * @see http://doc.babylonjs.com/features/behaviour
  15833. * @param behavior defines the behavior to attach
  15834. * @returns the current Node
  15835. */
  15836. Node.prototype.addBehavior = function (behavior) {
  15837. var _this = this;
  15838. var index = this._behaviors.indexOf(behavior);
  15839. if (index !== -1) {
  15840. return this;
  15841. }
  15842. behavior.init();
  15843. if (this._scene.isLoading) {
  15844. // We defer the attach when the scene will be loaded
  15845. var observer = this._scene.onDataLoadedObservable.add(function () {
  15846. behavior.attach(_this);
  15847. setTimeout(function () {
  15848. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15849. _this._scene.onDataLoadedObservable.remove(observer);
  15850. }, 0);
  15851. });
  15852. }
  15853. else {
  15854. behavior.attach(this);
  15855. }
  15856. this._behaviors.push(behavior);
  15857. return this;
  15858. };
  15859. /**
  15860. * Remove an attached behavior
  15861. * @see http://doc.babylonjs.com/features/behaviour
  15862. * @param behavior defines the behavior to attach
  15863. * @returns the current Node
  15864. */
  15865. Node.prototype.removeBehavior = function (behavior) {
  15866. var index = this._behaviors.indexOf(behavior);
  15867. if (index === -1) {
  15868. return this;
  15869. }
  15870. this._behaviors[index].detach();
  15871. this._behaviors.splice(index, 1);
  15872. return this;
  15873. };
  15874. Object.defineProperty(Node.prototype, "behaviors", {
  15875. /**
  15876. * Gets the list of attached behaviors
  15877. * @see http://doc.babylonjs.com/features/behaviour
  15878. */
  15879. get: function () {
  15880. return this._behaviors;
  15881. },
  15882. enumerable: true,
  15883. configurable: true
  15884. });
  15885. /**
  15886. * Gets an attached behavior by name
  15887. * @param name defines the name of the behavior to look for
  15888. * @see http://doc.babylonjs.com/features/behaviour
  15889. * @returns null if behavior was not found else the requested behavior
  15890. */
  15891. Node.prototype.getBehaviorByName = function (name) {
  15892. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15893. var behavior = _a[_i];
  15894. if (behavior.name === name) {
  15895. return behavior;
  15896. }
  15897. }
  15898. return null;
  15899. };
  15900. /**
  15901. * Returns the world matrix of the node
  15902. * @returns a matrix containing the node's world matrix
  15903. */
  15904. Node.prototype.getWorldMatrix = function () {
  15905. return BABYLON.Matrix.Identity();
  15906. };
  15907. // override it in derived class if you add new variables to the cache
  15908. // and call the parent class method
  15909. /** @ignore */
  15910. Node.prototype._initCache = function () {
  15911. this._cache = {};
  15912. this._cache.parent = undefined;
  15913. };
  15914. /** @ignore */
  15915. Node.prototype.updateCache = function (force) {
  15916. if (!force && this.isSynchronized())
  15917. return;
  15918. this._cache.parent = this.parent;
  15919. this._updateCache();
  15920. };
  15921. // override it in derived class if you add new variables to the cache
  15922. // and call the parent class method if !ignoreParentClass
  15923. /** @ignore */
  15924. Node.prototype._updateCache = function (ignoreParentClass) {
  15925. };
  15926. // override it in derived class if you add new variables to the cache
  15927. /** @ignore */
  15928. Node.prototype._isSynchronized = function () {
  15929. return true;
  15930. };
  15931. /** @ignore */
  15932. Node.prototype._markSyncedWithParent = function () {
  15933. if (this.parent) {
  15934. this._parentRenderId = this.parent._currentRenderId;
  15935. }
  15936. };
  15937. /** @ignore */
  15938. Node.prototype.isSynchronizedWithParent = function () {
  15939. if (!this.parent) {
  15940. return true;
  15941. }
  15942. if (this._parentRenderId !== this.parent._currentRenderId) {
  15943. return false;
  15944. }
  15945. return this.parent.isSynchronized();
  15946. };
  15947. /** @ignore */
  15948. Node.prototype.isSynchronized = function (updateCache) {
  15949. var check = this.hasNewParent();
  15950. check = check || !this.isSynchronizedWithParent();
  15951. check = check || !this._isSynchronized();
  15952. if (updateCache)
  15953. this.updateCache(true);
  15954. return !check;
  15955. };
  15956. /** @ignore */
  15957. Node.prototype.hasNewParent = function (update) {
  15958. if (this._cache.parent === this.parent)
  15959. return false;
  15960. if (update)
  15961. this._cache.parent = this.parent;
  15962. return true;
  15963. };
  15964. /**
  15965. * Is this node ready to be used/rendered
  15966. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15967. * @return true if the node is ready
  15968. */
  15969. Node.prototype.isReady = function (completeCheck) {
  15970. if (completeCheck === void 0) { completeCheck = false; }
  15971. return this._isReady;
  15972. };
  15973. /**
  15974. * Is this node enabled?
  15975. * 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
  15976. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15977. * @return whether this node (and its parent) is enabled
  15978. * @see setEnabled
  15979. */
  15980. Node.prototype.isEnabled = function (checkAncestors) {
  15981. if (checkAncestors === void 0) { checkAncestors = true; }
  15982. if (checkAncestors === false) {
  15983. return this._isEnabled;
  15984. }
  15985. if (this._isEnabled === false) {
  15986. return false;
  15987. }
  15988. if (this.parent !== undefined && this.parent !== null) {
  15989. return this.parent.isEnabled(checkAncestors);
  15990. }
  15991. return true;
  15992. };
  15993. /**
  15994. * Set the enabled state of this node
  15995. * @param value defines the new enabled state
  15996. * @see isEnabled
  15997. */
  15998. Node.prototype.setEnabled = function (value) {
  15999. this._isEnabled = value;
  16000. };
  16001. /**
  16002. * Is this node a descendant of the given node?
  16003. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  16004. * @param ancestor defines the parent node to inspect
  16005. * @see parent
  16006. * @returns a boolean indicating if this node is a descendant of the given node
  16007. */
  16008. Node.prototype.isDescendantOf = function (ancestor) {
  16009. if (this.parent) {
  16010. if (this.parent === ancestor) {
  16011. return true;
  16012. }
  16013. return this.parent.isDescendantOf(ancestor);
  16014. }
  16015. return false;
  16016. };
  16017. /** @ignore */
  16018. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  16019. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  16020. if (!this._children) {
  16021. return;
  16022. }
  16023. for (var index = 0; index < this._children.length; index++) {
  16024. var item = this._children[index];
  16025. if (!predicate || predicate(item)) {
  16026. results.push(item);
  16027. }
  16028. if (!directDescendantsOnly) {
  16029. item._getDescendants(results, false, predicate);
  16030. }
  16031. }
  16032. };
  16033. /**
  16034. * Will return all nodes that have this node as ascendant
  16035. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  16036. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  16037. * @return all children nodes of all types
  16038. */
  16039. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  16040. var results = new Array();
  16041. this._getDescendants(results, directDescendantsOnly, predicate);
  16042. return results;
  16043. };
  16044. /**
  16045. * Get all child-meshes of this node
  16046. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  16047. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  16048. * @returns an array of {BABYLON.AbstractMesh}
  16049. */
  16050. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  16051. var results = [];
  16052. this._getDescendants(results, directDescendantsOnly, function (node) {
  16053. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  16054. });
  16055. return results;
  16056. };
  16057. /**
  16058. * Get all child-transformNodes of this node
  16059. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  16060. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  16061. * @returns an array of {BABYLON.TransformNode}
  16062. */
  16063. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  16064. var results = [];
  16065. this._getDescendants(results, directDescendantsOnly, function (node) {
  16066. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16067. });
  16068. return results;
  16069. };
  16070. /**
  16071. * Get all direct children of this node
  16072. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  16073. * @returns an array of {BABYLON.Node}
  16074. */
  16075. Node.prototype.getChildren = function (predicate) {
  16076. return this.getDescendants(true, predicate);
  16077. };
  16078. /** @ignore */
  16079. Node.prototype._setReady = function (state) {
  16080. if (state === this._isReady) {
  16081. return;
  16082. }
  16083. if (!state) {
  16084. this._isReady = false;
  16085. return;
  16086. }
  16087. if (this.onReady) {
  16088. this.onReady(this);
  16089. }
  16090. this._isReady = true;
  16091. };
  16092. /**
  16093. * Get an animation by name
  16094. * @param name defines the name of the animation to look for
  16095. * @returns null if not found else the requested animation
  16096. */
  16097. Node.prototype.getAnimationByName = function (name) {
  16098. for (var i = 0; i < this.animations.length; i++) {
  16099. var animation = this.animations[i];
  16100. if (animation.name === name) {
  16101. return animation;
  16102. }
  16103. }
  16104. return null;
  16105. };
  16106. /**
  16107. * Creates an animation range for this node
  16108. * @param name defines the name of the range
  16109. * @param from defines the starting key
  16110. * @param to defines the end key
  16111. */
  16112. Node.prototype.createAnimationRange = function (name, from, to) {
  16113. // check name not already in use
  16114. if (!this._ranges[name]) {
  16115. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16116. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16117. if (this.animations[i]) {
  16118. this.animations[i].createRange(name, from, to);
  16119. }
  16120. }
  16121. }
  16122. };
  16123. /**
  16124. * Delete a specific animation range
  16125. * @param name defines the name of the range to delete
  16126. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16127. */
  16128. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16129. if (deleteFrames === void 0) { deleteFrames = true; }
  16130. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16131. if (this.animations[i]) {
  16132. this.animations[i].deleteRange(name, deleteFrames);
  16133. }
  16134. }
  16135. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16136. };
  16137. /**
  16138. * Get an animation range by name
  16139. * @param name defines the name of the animation range to look for
  16140. * @returns null if not found else the requested animation range
  16141. */
  16142. Node.prototype.getAnimationRange = function (name) {
  16143. return this._ranges[name];
  16144. };
  16145. /**
  16146. * Will start the animation sequence
  16147. * @param name defines the range frames for animation sequence
  16148. * @param loop defines if the animation should loop (false by default)
  16149. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16150. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16151. * @returns the object created for this animation. If range does not exist, it will return null
  16152. */
  16153. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16154. var range = this.getAnimationRange(name);
  16155. if (!range) {
  16156. return null;
  16157. }
  16158. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16159. };
  16160. /**
  16161. * Serialize animation ranges into a JSON compatible object
  16162. * @returns serialization object
  16163. */
  16164. Node.prototype.serializeAnimationRanges = function () {
  16165. var serializationRanges = [];
  16166. for (var name in this._ranges) {
  16167. var localRange = this._ranges[name];
  16168. if (!localRange) {
  16169. continue;
  16170. }
  16171. var range = {};
  16172. range.name = name;
  16173. range.from = localRange.from;
  16174. range.to = localRange.to;
  16175. serializationRanges.push(range);
  16176. }
  16177. return serializationRanges;
  16178. };
  16179. /**
  16180. * Computes the world matrix of the node
  16181. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16182. * @returns the world matrix
  16183. */
  16184. Node.prototype.computeWorldMatrix = function (force) {
  16185. return BABYLON.Matrix.Identity();
  16186. };
  16187. /**
  16188. * Releases resources associated with this node.
  16189. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16190. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16191. */
  16192. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16193. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16194. if (!doNotRecurse) {
  16195. var nodes = this.getDescendants(true);
  16196. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16197. var node = nodes_1[_i];
  16198. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16199. }
  16200. }
  16201. else {
  16202. var transformNodes = this.getChildTransformNodes(true);
  16203. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16204. var transformNode = transformNodes_1[_a];
  16205. transformNode.parent = null;
  16206. transformNode.computeWorldMatrix(true);
  16207. }
  16208. }
  16209. this.parent = null;
  16210. // Callback
  16211. this.onDisposeObservable.notifyObservers(this);
  16212. this.onDisposeObservable.clear();
  16213. // Behaviors
  16214. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16215. var behavior = _c[_b];
  16216. behavior.detach();
  16217. }
  16218. this._behaviors = [];
  16219. this._isDisposed = true;
  16220. };
  16221. /**
  16222. * Parse animation range data from a serialization object and store them into a given node
  16223. * @param node defines where to store the animation ranges
  16224. * @param parsedNode defines the serialization object to read data from
  16225. * @param scene defines the hosting scene
  16226. */
  16227. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16228. if (parsedNode.ranges) {
  16229. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16230. var data = parsedNode.ranges[index];
  16231. node.createAnimationRange(data.name, data.from, data.to);
  16232. }
  16233. }
  16234. };
  16235. __decorate([
  16236. BABYLON.serialize()
  16237. ], Node.prototype, "name", void 0);
  16238. __decorate([
  16239. BABYLON.serialize()
  16240. ], Node.prototype, "id", void 0);
  16241. __decorate([
  16242. BABYLON.serialize()
  16243. ], Node.prototype, "uniqueId", void 0);
  16244. __decorate([
  16245. BABYLON.serialize()
  16246. ], Node.prototype, "state", void 0);
  16247. __decorate([
  16248. BABYLON.serialize()
  16249. ], Node.prototype, "metadata", void 0);
  16250. return Node;
  16251. }());
  16252. BABYLON.Node = Node;
  16253. })(BABYLON || (BABYLON = {}));
  16254. //# sourceMappingURL=babylon.node.js.map
  16255. var BABYLON;
  16256. (function (BABYLON) {
  16257. var BoundingSphere = /** @class */ (function () {
  16258. function BoundingSphere(minimum, maximum) {
  16259. this.minimum = minimum;
  16260. this.maximum = maximum;
  16261. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16262. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16263. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16264. this.radius = distance * 0.5;
  16265. this.centerWorld = BABYLON.Vector3.Zero();
  16266. this._update(BABYLON.Matrix.Identity());
  16267. }
  16268. // Methods
  16269. BoundingSphere.prototype._update = function (world) {
  16270. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16271. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16272. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16273. };
  16274. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16275. for (var i = 0; i < 6; i++) {
  16276. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16277. return false;
  16278. }
  16279. return true;
  16280. };
  16281. BoundingSphere.prototype.intersectsPoint = function (point) {
  16282. var x = this.centerWorld.x - point.x;
  16283. var y = this.centerWorld.y - point.y;
  16284. var z = this.centerWorld.z - point.z;
  16285. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16286. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16287. return false;
  16288. return true;
  16289. };
  16290. // Statics
  16291. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16292. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16293. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16294. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16295. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16296. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16297. return false;
  16298. return true;
  16299. };
  16300. return BoundingSphere;
  16301. }());
  16302. BABYLON.BoundingSphere = BoundingSphere;
  16303. })(BABYLON || (BABYLON = {}));
  16304. //# sourceMappingURL=babylon.boundingSphere.js.map
  16305. var BABYLON;
  16306. (function (BABYLON) {
  16307. var BoundingBox = /** @class */ (function () {
  16308. function BoundingBox(minimum, maximum) {
  16309. this.minimum = minimum;
  16310. this.maximum = maximum;
  16311. this.vectors = new Array();
  16312. this.vectorsWorld = new Array();
  16313. // Bounding vectors
  16314. this.vectors.push(this.minimum.clone());
  16315. this.vectors.push(this.maximum.clone());
  16316. this.vectors.push(this.minimum.clone());
  16317. this.vectors[2].x = this.maximum.x;
  16318. this.vectors.push(this.minimum.clone());
  16319. this.vectors[3].y = this.maximum.y;
  16320. this.vectors.push(this.minimum.clone());
  16321. this.vectors[4].z = this.maximum.z;
  16322. this.vectors.push(this.maximum.clone());
  16323. this.vectors[5].z = this.minimum.z;
  16324. this.vectors.push(this.maximum.clone());
  16325. this.vectors[6].x = this.minimum.x;
  16326. this.vectors.push(this.maximum.clone());
  16327. this.vectors[7].y = this.minimum.y;
  16328. // OBB
  16329. this.center = this.maximum.add(this.minimum).scale(0.5);
  16330. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16331. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16332. // World
  16333. for (var index = 0; index < this.vectors.length; index++) {
  16334. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16335. }
  16336. this.minimumWorld = BABYLON.Vector3.Zero();
  16337. this.maximumWorld = BABYLON.Vector3.Zero();
  16338. this.centerWorld = BABYLON.Vector3.Zero();
  16339. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16340. this._update(BABYLON.Matrix.Identity());
  16341. }
  16342. // Methods
  16343. BoundingBox.prototype.getWorldMatrix = function () {
  16344. return this._worldMatrix;
  16345. };
  16346. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16347. this._worldMatrix.copyFrom(matrix);
  16348. return this;
  16349. };
  16350. BoundingBox.prototype._update = function (world) {
  16351. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16352. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16353. for (var index = 0; index < this.vectors.length; index++) {
  16354. var v = this.vectorsWorld[index];
  16355. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16356. if (v.x < this.minimumWorld.x)
  16357. this.minimumWorld.x = v.x;
  16358. if (v.y < this.minimumWorld.y)
  16359. this.minimumWorld.y = v.y;
  16360. if (v.z < this.minimumWorld.z)
  16361. this.minimumWorld.z = v.z;
  16362. if (v.x > this.maximumWorld.x)
  16363. this.maximumWorld.x = v.x;
  16364. if (v.y > this.maximumWorld.y)
  16365. this.maximumWorld.y = v.y;
  16366. if (v.z > this.maximumWorld.z)
  16367. this.maximumWorld.z = v.z;
  16368. }
  16369. // Extend
  16370. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16371. this.extendSizeWorld.scaleInPlace(0.5);
  16372. // OBB
  16373. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16374. this.centerWorld.scaleInPlace(0.5);
  16375. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16376. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16377. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16378. this._worldMatrix = world;
  16379. };
  16380. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16381. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16382. };
  16383. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16384. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16385. };
  16386. BoundingBox.prototype.intersectsPoint = function (point) {
  16387. var delta = -BABYLON.Epsilon;
  16388. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16389. return false;
  16390. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16391. return false;
  16392. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16393. return false;
  16394. return true;
  16395. };
  16396. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16397. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16398. };
  16399. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16400. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16401. return false;
  16402. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16403. return false;
  16404. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16405. return false;
  16406. return true;
  16407. };
  16408. // Statics
  16409. BoundingBox.Intersects = function (box0, box1) {
  16410. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16411. return false;
  16412. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16413. return false;
  16414. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16415. return false;
  16416. return true;
  16417. };
  16418. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16419. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16420. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16421. return (num <= (sphereRadius * sphereRadius));
  16422. };
  16423. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16424. for (var p = 0; p < 6; p++) {
  16425. for (var i = 0; i < 8; i++) {
  16426. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16427. return false;
  16428. }
  16429. }
  16430. }
  16431. return true;
  16432. };
  16433. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16434. for (var p = 0; p < 6; p++) {
  16435. var inCount = 8;
  16436. for (var i = 0; i < 8; i++) {
  16437. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16438. --inCount;
  16439. }
  16440. else {
  16441. break;
  16442. }
  16443. }
  16444. if (inCount === 0)
  16445. return false;
  16446. }
  16447. return true;
  16448. };
  16449. return BoundingBox;
  16450. }());
  16451. BABYLON.BoundingBox = BoundingBox;
  16452. })(BABYLON || (BABYLON = {}));
  16453. //# sourceMappingURL=babylon.boundingBox.js.map
  16454. var BABYLON;
  16455. (function (BABYLON) {
  16456. var computeBoxExtents = function (axis, box) {
  16457. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16458. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16459. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16460. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16461. var r = r0 + r1 + r2;
  16462. return {
  16463. min: p - r,
  16464. max: p + r
  16465. };
  16466. };
  16467. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16468. var axisOverlap = function (axis, box0, box1) {
  16469. var result0 = computeBoxExtents(axis, box0);
  16470. var result1 = computeBoxExtents(axis, box1);
  16471. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16472. };
  16473. var BoundingInfo = /** @class */ (function () {
  16474. function BoundingInfo(minimum, maximum) {
  16475. this.minimum = minimum;
  16476. this.maximum = maximum;
  16477. this._isLocked = false;
  16478. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16479. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16480. }
  16481. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16482. get: function () {
  16483. return this._isLocked;
  16484. },
  16485. set: function (value) {
  16486. this._isLocked = value;
  16487. },
  16488. enumerable: true,
  16489. configurable: true
  16490. });
  16491. // Methods
  16492. BoundingInfo.prototype.update = function (world) {
  16493. if (this._isLocked) {
  16494. return;
  16495. }
  16496. this.boundingBox._update(world);
  16497. this.boundingSphere._update(world);
  16498. };
  16499. /**
  16500. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16501. * @param center New center of the bounding info
  16502. * @param extend New extend of the bounding info
  16503. */
  16504. BoundingInfo.prototype.centerOn = function (center, extend) {
  16505. this.minimum = center.subtract(extend);
  16506. this.maximum = center.add(extend);
  16507. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16508. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16509. return this;
  16510. };
  16511. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16512. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16513. return false;
  16514. return this.boundingBox.isInFrustum(frustumPlanes);
  16515. };
  16516. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16517. /**
  16518. * Gets the world distance between the min and max points of the bounding box
  16519. */
  16520. get: function () {
  16521. var boundingBox = this.boundingBox;
  16522. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16523. return size.length();
  16524. },
  16525. enumerable: true,
  16526. configurable: true
  16527. });
  16528. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16529. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16530. };
  16531. BoundingInfo.prototype._checkCollision = function (collider) {
  16532. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16533. };
  16534. BoundingInfo.prototype.intersectsPoint = function (point) {
  16535. if (!this.boundingSphere.centerWorld) {
  16536. return false;
  16537. }
  16538. if (!this.boundingSphere.intersectsPoint(point)) {
  16539. return false;
  16540. }
  16541. if (!this.boundingBox.intersectsPoint(point)) {
  16542. return false;
  16543. }
  16544. return true;
  16545. };
  16546. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16547. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16548. return false;
  16549. }
  16550. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16551. return false;
  16552. }
  16553. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16554. return false;
  16555. }
  16556. if (!precise) {
  16557. return true;
  16558. }
  16559. var box0 = this.boundingBox;
  16560. var box1 = boundingInfo.boundingBox;
  16561. if (!axisOverlap(box0.directions[0], box0, box1))
  16562. return false;
  16563. if (!axisOverlap(box0.directions[1], box0, box1))
  16564. return false;
  16565. if (!axisOverlap(box0.directions[2], box0, box1))
  16566. return false;
  16567. if (!axisOverlap(box1.directions[0], box0, box1))
  16568. return false;
  16569. if (!axisOverlap(box1.directions[1], box0, box1))
  16570. return false;
  16571. if (!axisOverlap(box1.directions[2], box0, box1))
  16572. return false;
  16573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16574. return false;
  16575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16576. return false;
  16577. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16578. return false;
  16579. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16580. return false;
  16581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16582. return false;
  16583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16584. return false;
  16585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16586. return false;
  16587. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16588. return false;
  16589. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16590. return false;
  16591. return true;
  16592. };
  16593. return BoundingInfo;
  16594. }());
  16595. BABYLON.BoundingInfo = BoundingInfo;
  16596. })(BABYLON || (BABYLON = {}));
  16597. //# sourceMappingURL=babylon.boundingInfo.js.map
  16598. var BABYLON;
  16599. (function (BABYLON) {
  16600. var TransformNode = /** @class */ (function (_super) {
  16601. __extends(TransformNode, _super);
  16602. function TransformNode(name, scene, isPure) {
  16603. if (scene === void 0) { scene = null; }
  16604. if (isPure === void 0) { isPure = true; }
  16605. var _this = _super.call(this, name, scene) || this;
  16606. // Properties
  16607. _this._rotation = BABYLON.Vector3.Zero();
  16608. _this._scaling = BABYLON.Vector3.One();
  16609. _this._isDirty = false;
  16610. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16611. _this.scalingDeterminant = 1;
  16612. _this.infiniteDistance = false;
  16613. _this.position = BABYLON.Vector3.Zero();
  16614. _this._localWorld = BABYLON.Matrix.Zero();
  16615. _this._worldMatrix = BABYLON.Matrix.Zero();
  16616. _this._worldMatrixDeterminant = 0;
  16617. _this._absolutePosition = BABYLON.Vector3.Zero();
  16618. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16619. _this._postMultiplyPivotMatrix = false;
  16620. _this._isWorldMatrixFrozen = false;
  16621. /**
  16622. * An event triggered after the world matrix is updated
  16623. * @type {BABYLON.Observable}
  16624. */
  16625. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16626. _this._nonUniformScaling = false;
  16627. if (isPure) {
  16628. _this.getScene().addTransformNode(_this);
  16629. }
  16630. return _this;
  16631. }
  16632. /**
  16633. * Gets a string idenfifying the name of the class
  16634. * @returns "TransformNode" string
  16635. */
  16636. TransformNode.prototype.getClassName = function () {
  16637. return "TransformNode";
  16638. };
  16639. Object.defineProperty(TransformNode.prototype, "rotation", {
  16640. /**
  16641. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16642. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16643. * Default : (0.0, 0.0, 0.0)
  16644. */
  16645. get: function () {
  16646. return this._rotation;
  16647. },
  16648. set: function (newRotation) {
  16649. this._rotation = newRotation;
  16650. },
  16651. enumerable: true,
  16652. configurable: true
  16653. });
  16654. Object.defineProperty(TransformNode.prototype, "scaling", {
  16655. /**
  16656. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16657. * Default : (1.0, 1.0, 1.0)
  16658. */
  16659. get: function () {
  16660. return this._scaling;
  16661. },
  16662. /**
  16663. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16664. * Default : (1.0, 1.0, 1.0)
  16665. */
  16666. set: function (newScaling) {
  16667. this._scaling = newScaling;
  16668. },
  16669. enumerable: true,
  16670. configurable: true
  16671. });
  16672. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16673. /**
  16674. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16675. * It's null by default.
  16676. * 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)
  16677. */
  16678. get: function () {
  16679. return this._rotationQuaternion;
  16680. },
  16681. set: function (quaternion) {
  16682. this._rotationQuaternion = quaternion;
  16683. //reset the rotation vector.
  16684. if (quaternion && this.rotation.length()) {
  16685. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16686. }
  16687. },
  16688. enumerable: true,
  16689. configurable: true
  16690. });
  16691. /**
  16692. * Returns the latest update of the World matrix
  16693. * Returns a Matrix.
  16694. */
  16695. TransformNode.prototype.getWorldMatrix = function () {
  16696. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16697. this.computeWorldMatrix();
  16698. }
  16699. return this._worldMatrix;
  16700. };
  16701. /**
  16702. * Returns the latest update of the World matrix determinant.
  16703. */
  16704. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16705. return this._worldMatrixDeterminant;
  16706. };
  16707. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16708. /**
  16709. * Returns directly the latest state of the mesh World matrix.
  16710. * A Matrix is returned.
  16711. */
  16712. get: function () {
  16713. return this._worldMatrix;
  16714. },
  16715. enumerable: true,
  16716. configurable: true
  16717. });
  16718. /**
  16719. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16720. * Returns the AbstractMesh.
  16721. */
  16722. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16723. this._poseMatrix.copyFrom(matrix);
  16724. return this;
  16725. };
  16726. /**
  16727. * Returns the mesh Pose matrix.
  16728. * Returned object : Matrix
  16729. */
  16730. TransformNode.prototype.getPoseMatrix = function () {
  16731. return this._poseMatrix;
  16732. };
  16733. TransformNode.prototype._isSynchronized = function () {
  16734. if (this._isDirty) {
  16735. return false;
  16736. }
  16737. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16738. return false;
  16739. if (this._cache.pivotMatrixUpdated) {
  16740. return false;
  16741. }
  16742. if (this.infiniteDistance) {
  16743. return false;
  16744. }
  16745. if (!this._cache.position.equals(this.position))
  16746. return false;
  16747. if (this.rotationQuaternion) {
  16748. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16749. return false;
  16750. }
  16751. if (!this._cache.rotation.equals(this.rotation))
  16752. return false;
  16753. if (!this._cache.scaling.equals(this.scaling))
  16754. return false;
  16755. return true;
  16756. };
  16757. TransformNode.prototype._initCache = function () {
  16758. _super.prototype._initCache.call(this);
  16759. this._cache.localMatrixUpdated = false;
  16760. this._cache.position = BABYLON.Vector3.Zero();
  16761. this._cache.scaling = BABYLON.Vector3.Zero();
  16762. this._cache.rotation = BABYLON.Vector3.Zero();
  16763. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16764. this._cache.billboardMode = -1;
  16765. };
  16766. TransformNode.prototype.markAsDirty = function (property) {
  16767. if (property === "rotation") {
  16768. this.rotationQuaternion = null;
  16769. }
  16770. this._currentRenderId = Number.MAX_VALUE;
  16771. this._isDirty = true;
  16772. return this;
  16773. };
  16774. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16775. /**
  16776. * Returns the current mesh absolute position.
  16777. * Retuns a Vector3.
  16778. */
  16779. get: function () {
  16780. return this._absolutePosition;
  16781. },
  16782. enumerable: true,
  16783. configurable: true
  16784. });
  16785. /**
  16786. * Sets a new matrix to apply before all other transformation
  16787. * @param matrix defines the transform matrix
  16788. * @returns the current TransformNode
  16789. */
  16790. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16791. return this.setPivotMatrix(matrix, false);
  16792. };
  16793. /**
  16794. * Sets a new pivot matrix to the current node
  16795. * @param matrix defines the new pivot matrix to use
  16796. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  16797. * @returns the current TransformNode
  16798. */
  16799. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16800. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16801. this._pivotMatrix = matrix.clone();
  16802. this._cache.pivotMatrixUpdated = true;
  16803. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16804. if (this._postMultiplyPivotMatrix) {
  16805. if (!this._pivotMatrixInverse) {
  16806. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16807. }
  16808. else {
  16809. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16810. }
  16811. }
  16812. return this;
  16813. };
  16814. /**
  16815. * Returns the mesh pivot matrix.
  16816. * Default : Identity.
  16817. * A Matrix is returned.
  16818. */
  16819. TransformNode.prototype.getPivotMatrix = function () {
  16820. return this._pivotMatrix;
  16821. };
  16822. /**
  16823. * Prevents the World matrix to be computed any longer.
  16824. * Returns the AbstractMesh.
  16825. */
  16826. TransformNode.prototype.freezeWorldMatrix = function () {
  16827. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16828. this.computeWorldMatrix(true);
  16829. this._isWorldMatrixFrozen = true;
  16830. return this;
  16831. };
  16832. /**
  16833. * Allows back the World matrix computation.
  16834. * Returns the AbstractMesh.
  16835. */
  16836. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16837. this._isWorldMatrixFrozen = false;
  16838. this.computeWorldMatrix(true);
  16839. return this;
  16840. };
  16841. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16842. /**
  16843. * True if the World matrix has been frozen.
  16844. * Returns a boolean.
  16845. */
  16846. get: function () {
  16847. return this._isWorldMatrixFrozen;
  16848. },
  16849. enumerable: true,
  16850. configurable: true
  16851. });
  16852. /**
  16853. * Retuns the mesh absolute position in the World.
  16854. * Returns a Vector3.
  16855. */
  16856. TransformNode.prototype.getAbsolutePosition = function () {
  16857. this.computeWorldMatrix();
  16858. return this._absolutePosition;
  16859. };
  16860. /**
  16861. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16862. * Returns the AbstractMesh.
  16863. */
  16864. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16865. if (!absolutePosition) {
  16866. return this;
  16867. }
  16868. var absolutePositionX;
  16869. var absolutePositionY;
  16870. var absolutePositionZ;
  16871. if (absolutePosition.x === undefined) {
  16872. if (arguments.length < 3) {
  16873. return this;
  16874. }
  16875. absolutePositionX = arguments[0];
  16876. absolutePositionY = arguments[1];
  16877. absolutePositionZ = arguments[2];
  16878. }
  16879. else {
  16880. absolutePositionX = absolutePosition.x;
  16881. absolutePositionY = absolutePosition.y;
  16882. absolutePositionZ = absolutePosition.z;
  16883. }
  16884. if (this.parent) {
  16885. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16886. invertParentWorldMatrix.invert();
  16887. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16888. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16889. }
  16890. else {
  16891. this.position.x = absolutePositionX;
  16892. this.position.y = absolutePositionY;
  16893. this.position.z = absolutePositionZ;
  16894. }
  16895. return this;
  16896. };
  16897. /**
  16898. * Sets the mesh position in its local space.
  16899. * Returns the AbstractMesh.
  16900. */
  16901. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16902. this.computeWorldMatrix();
  16903. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16904. return this;
  16905. };
  16906. /**
  16907. * Returns the mesh position in the local space from the current World matrix values.
  16908. * Returns a new Vector3.
  16909. */
  16910. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16911. this.computeWorldMatrix();
  16912. var invLocalWorldMatrix = this._localWorld.clone();
  16913. invLocalWorldMatrix.invert();
  16914. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16915. };
  16916. /**
  16917. * Translates the mesh along the passed Vector3 in its local space.
  16918. * Returns the AbstractMesh.
  16919. */
  16920. TransformNode.prototype.locallyTranslate = function (vector3) {
  16921. this.computeWorldMatrix(true);
  16922. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16923. return this;
  16924. };
  16925. /**
  16926. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16927. * @param targetPoint the position (must be in same space as current mesh) to look at
  16928. * @param yawCor optional yaw (y-axis) correction in radians
  16929. * @param pitchCor optional pitch (x-axis) correction in radians
  16930. * @param rollCor optional roll (z-axis) correction in radians
  16931. * @param space the choosen space of the target
  16932. * @returns the TransformNode.
  16933. */
  16934. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16935. if (yawCor === void 0) { yawCor = 0; }
  16936. if (pitchCor === void 0) { pitchCor = 0; }
  16937. if (rollCor === void 0) { rollCor = 0; }
  16938. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16939. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16940. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16941. targetPoint.subtractToRef(pos, dv);
  16942. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16943. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16944. var pitch = Math.atan2(dv.y, len);
  16945. if (this.rotationQuaternion) {
  16946. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16947. }
  16948. else {
  16949. this.rotation.x = pitch + pitchCor;
  16950. this.rotation.y = yaw + yawCor;
  16951. this.rotation.z = rollCor;
  16952. }
  16953. return this;
  16954. };
  16955. /**
  16956. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16957. * This Vector3 is expressed in the World space.
  16958. */
  16959. TransformNode.prototype.getDirection = function (localAxis) {
  16960. var result = BABYLON.Vector3.Zero();
  16961. this.getDirectionToRef(localAxis, result);
  16962. return result;
  16963. };
  16964. /**
  16965. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16966. * localAxis is expressed in the mesh local space.
  16967. * result is computed in the Wordl space from the mesh World matrix.
  16968. * Returns the AbstractMesh.
  16969. */
  16970. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16971. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16972. return this;
  16973. };
  16974. /**
  16975. * Sets a new pivot point to the current node
  16976. * @param point defines the new pivot point to use
  16977. * @param space defines if the point is in world or local space (local by default)
  16978. * @returns the current TransformNode
  16979. */
  16980. TransformNode.prototype.setPivotPoint = function (point, space) {
  16981. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16982. if (this.getScene().getRenderId() == 0) {
  16983. this.computeWorldMatrix(true);
  16984. }
  16985. var wm = this.getWorldMatrix();
  16986. if (space == BABYLON.Space.WORLD) {
  16987. var tmat = BABYLON.Tmp.Matrix[0];
  16988. wm.invertToRef(tmat);
  16989. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16990. }
  16991. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16992. };
  16993. /**
  16994. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16995. */
  16996. TransformNode.prototype.getPivotPoint = function () {
  16997. var point = BABYLON.Vector3.Zero();
  16998. this.getPivotPointToRef(point);
  16999. return point;
  17000. };
  17001. /**
  17002. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  17003. * Returns the AbstractMesh.
  17004. */
  17005. TransformNode.prototype.getPivotPointToRef = function (result) {
  17006. result.x = -this._pivotMatrix.m[12];
  17007. result.y = -this._pivotMatrix.m[13];
  17008. result.z = -this._pivotMatrix.m[14];
  17009. return this;
  17010. };
  17011. /**
  17012. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  17013. */
  17014. TransformNode.prototype.getAbsolutePivotPoint = function () {
  17015. var point = BABYLON.Vector3.Zero();
  17016. this.getAbsolutePivotPointToRef(point);
  17017. return point;
  17018. };
  17019. /**
  17020. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  17021. * Returns the AbstractMesh.
  17022. */
  17023. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  17024. result.x = this._pivotMatrix.m[12];
  17025. result.y = this._pivotMatrix.m[13];
  17026. result.z = this._pivotMatrix.m[14];
  17027. this.getPivotPointToRef(result);
  17028. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  17029. return this;
  17030. };
  17031. /**
  17032. * Defines the passed node as the parent of the current node.
  17033. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  17034. * Returns the TransformNode.
  17035. */
  17036. TransformNode.prototype.setParent = function (node) {
  17037. if (node === null) {
  17038. var rotation = BABYLON.Tmp.Quaternion[0];
  17039. var position = BABYLON.Tmp.Vector3[0];
  17040. var scale = BABYLON.Tmp.Vector3[1];
  17041. if (this.parent && this.parent.computeWorldMatrix) {
  17042. this.parent.computeWorldMatrix(true);
  17043. }
  17044. this.computeWorldMatrix(true);
  17045. this.getWorldMatrix().decompose(scale, rotation, position);
  17046. if (this.rotationQuaternion) {
  17047. this.rotationQuaternion.copyFrom(rotation);
  17048. }
  17049. else {
  17050. rotation.toEulerAnglesToRef(this.rotation);
  17051. }
  17052. this.scaling.x = scale.x;
  17053. this.scaling.y = scale.y;
  17054. this.scaling.z = scale.z;
  17055. this.position.x = position.x;
  17056. this.position.y = position.y;
  17057. this.position.z = position.z;
  17058. }
  17059. else {
  17060. var rotation = BABYLON.Tmp.Quaternion[0];
  17061. var position = BABYLON.Tmp.Vector3[0];
  17062. var scale = BABYLON.Tmp.Vector3[1];
  17063. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17064. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17065. this.computeWorldMatrix(true);
  17066. node.computeWorldMatrix(true);
  17067. node.getWorldMatrix().invertToRef(invParentMatrix);
  17068. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17069. diffMatrix.decompose(scale, rotation, position);
  17070. if (this.rotationQuaternion) {
  17071. this.rotationQuaternion.copyFrom(rotation);
  17072. }
  17073. else {
  17074. rotation.toEulerAnglesToRef(this.rotation);
  17075. }
  17076. this.position.x = position.x;
  17077. this.position.y = position.y;
  17078. this.position.z = position.z;
  17079. this.scaling.x = scale.x;
  17080. this.scaling.y = scale.y;
  17081. this.scaling.z = scale.z;
  17082. }
  17083. this.parent = node;
  17084. return this;
  17085. };
  17086. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17087. get: function () {
  17088. return this._nonUniformScaling;
  17089. },
  17090. enumerable: true,
  17091. configurable: true
  17092. });
  17093. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17094. if (this._nonUniformScaling === value) {
  17095. return false;
  17096. }
  17097. this._nonUniformScaling = true;
  17098. return true;
  17099. };
  17100. /**
  17101. * Attach the current TransformNode to another TransformNode associated with a bone
  17102. * @param bone Bone affecting the TransformNode
  17103. * @param affectedTransformNode TransformNode associated with the bone
  17104. */
  17105. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17106. this._transformToBoneReferal = affectedTransformNode;
  17107. this.parent = bone;
  17108. if (bone.getWorldMatrix().determinant() < 0) {
  17109. this.scalingDeterminant *= -1;
  17110. }
  17111. return this;
  17112. };
  17113. TransformNode.prototype.detachFromBone = function () {
  17114. if (!this.parent) {
  17115. return this;
  17116. }
  17117. if (this.parent.getWorldMatrix().determinant() < 0) {
  17118. this.scalingDeterminant *= -1;
  17119. }
  17120. this._transformToBoneReferal = null;
  17121. this.parent = null;
  17122. return this;
  17123. };
  17124. /**
  17125. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17126. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17127. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17128. * The passed axis is also normalized.
  17129. * Returns the AbstractMesh.
  17130. */
  17131. TransformNode.prototype.rotate = function (axis, amount, space) {
  17132. axis.normalize();
  17133. if (!this.rotationQuaternion) {
  17134. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17135. this.rotation = BABYLON.Vector3.Zero();
  17136. }
  17137. var rotationQuaternion;
  17138. if (!space || space === BABYLON.Space.LOCAL) {
  17139. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17140. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17141. }
  17142. else {
  17143. if (this.parent) {
  17144. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17145. invertParentWorldMatrix.invert();
  17146. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17147. }
  17148. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17149. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17150. }
  17151. return this;
  17152. };
  17153. /**
  17154. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17155. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17156. * The passed axis is also normalized.
  17157. * Returns the AbstractMesh.
  17158. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17159. */
  17160. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17161. axis.normalize();
  17162. if (!this.rotationQuaternion) {
  17163. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17164. this.rotation.copyFromFloats(0, 0, 0);
  17165. }
  17166. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17167. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17168. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17169. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17170. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17171. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17172. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17173. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17174. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17175. return this;
  17176. };
  17177. /**
  17178. * Translates the mesh along the axis vector for the passed distance in the given space.
  17179. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17180. * Returns the AbstractMesh.
  17181. */
  17182. TransformNode.prototype.translate = function (axis, distance, space) {
  17183. var displacementVector = axis.scale(distance);
  17184. if (!space || space === BABYLON.Space.LOCAL) {
  17185. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17186. this.setPositionWithLocalVector(tempV3);
  17187. }
  17188. else {
  17189. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17190. }
  17191. return this;
  17192. };
  17193. /**
  17194. * Adds a rotation step to the mesh current rotation.
  17195. * x, y, z are Euler angles expressed in radians.
  17196. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17197. * This means this rotation is made in the mesh local space only.
  17198. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17199. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17200. * ```javascript
  17201. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17202. * ```
  17203. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17204. * 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.
  17205. * Returns the AbstractMesh.
  17206. */
  17207. TransformNode.prototype.addRotation = function (x, y, z) {
  17208. var rotationQuaternion;
  17209. if (this.rotationQuaternion) {
  17210. rotationQuaternion = this.rotationQuaternion;
  17211. }
  17212. else {
  17213. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17214. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17215. }
  17216. var accumulation = BABYLON.Tmp.Quaternion[0];
  17217. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17218. rotationQuaternion.multiplyInPlace(accumulation);
  17219. if (!this.rotationQuaternion) {
  17220. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17221. }
  17222. return this;
  17223. };
  17224. /**
  17225. * Computes the mesh World matrix and returns it.
  17226. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17227. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17228. * If the parameter `force`is set to `true`, the actual computation is done.
  17229. * Returns the mesh World Matrix.
  17230. */
  17231. TransformNode.prototype.computeWorldMatrix = function (force) {
  17232. if (this._isWorldMatrixFrozen) {
  17233. return this._worldMatrix;
  17234. }
  17235. if (!force && this.isSynchronized(true)) {
  17236. return this._worldMatrix;
  17237. }
  17238. this._cache.position.copyFrom(this.position);
  17239. this._cache.scaling.copyFrom(this.scaling);
  17240. this._cache.pivotMatrixUpdated = false;
  17241. this._cache.billboardMode = this.billboardMode;
  17242. this._currentRenderId = this.getScene().getRenderId();
  17243. this._isDirty = false;
  17244. // Scaling
  17245. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17246. // Rotation
  17247. //rotate, if quaternion is set and rotation was used
  17248. if (this.rotationQuaternion) {
  17249. var len = this.rotation.length();
  17250. if (len) {
  17251. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17252. this.rotation.copyFromFloats(0, 0, 0);
  17253. }
  17254. }
  17255. if (this.rotationQuaternion) {
  17256. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17257. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17258. }
  17259. else {
  17260. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17261. this._cache.rotation.copyFrom(this.rotation);
  17262. }
  17263. // Translation
  17264. var camera = this.getScene().activeCamera;
  17265. if (this.infiniteDistance && !this.parent && camera) {
  17266. var cameraWorldMatrix = camera.getWorldMatrix();
  17267. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17268. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17269. }
  17270. else {
  17271. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17272. }
  17273. // Composing transformations
  17274. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17275. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17276. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17277. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17278. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17279. // Need to decompose each rotation here
  17280. var currentPosition = BABYLON.Tmp.Vector3[3];
  17281. if (this.parent && this.parent.getWorldMatrix) {
  17282. if (this._transformToBoneReferal) {
  17283. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17284. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17285. }
  17286. else {
  17287. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17288. }
  17289. }
  17290. else {
  17291. currentPosition.copyFrom(this.position);
  17292. }
  17293. currentPosition.subtractInPlace(camera.globalPosition);
  17294. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17295. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17296. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17297. }
  17298. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17299. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17300. }
  17301. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17302. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17303. }
  17304. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17305. }
  17306. else {
  17307. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17308. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17309. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17310. }
  17311. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17312. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17313. }
  17314. // Local world
  17315. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17316. // Parent
  17317. if (this.parent && this.parent.getWorldMatrix) {
  17318. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17319. if (this._transformToBoneReferal) {
  17320. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17321. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17322. }
  17323. else {
  17324. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17325. }
  17326. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17327. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17328. this._worldMatrix.copyFrom(this._localWorld);
  17329. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17330. }
  17331. else {
  17332. if (this._transformToBoneReferal) {
  17333. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17334. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17335. }
  17336. else {
  17337. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17338. }
  17339. }
  17340. this._markSyncedWithParent();
  17341. }
  17342. else {
  17343. this._worldMatrix.copyFrom(this._localWorld);
  17344. }
  17345. // Post multiply inverse of pivotMatrix
  17346. if (this._postMultiplyPivotMatrix) {
  17347. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17348. }
  17349. // Normal matrix
  17350. if (this.scaling.isNonUniform) {
  17351. this._updateNonUniformScalingState(true);
  17352. }
  17353. else if (this.parent && this.parent._nonUniformScaling) {
  17354. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17355. }
  17356. else {
  17357. this._updateNonUniformScalingState(false);
  17358. }
  17359. this._afterComputeWorldMatrix();
  17360. // Absolute position
  17361. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17362. // Callbacks
  17363. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17364. if (!this._poseMatrix) {
  17365. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17366. }
  17367. // Cache the determinant
  17368. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17369. return this._worldMatrix;
  17370. };
  17371. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17372. };
  17373. /**
  17374. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17375. * @param func: callback function to add
  17376. *
  17377. * Returns the TransformNode.
  17378. */
  17379. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17380. this.onAfterWorldMatrixUpdateObservable.add(func);
  17381. return this;
  17382. };
  17383. /**
  17384. * Removes a registered callback function.
  17385. * Returns the TransformNode.
  17386. */
  17387. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17388. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17389. return this;
  17390. };
  17391. /**
  17392. * Clone the current transform node
  17393. * Returns the new transform node
  17394. * @param name Name of the new clone
  17395. * @param newParent New parent for the clone
  17396. * @param doNotCloneChildren Do not clone children hierarchy
  17397. */
  17398. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17399. var _this = this;
  17400. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17401. result.name = name;
  17402. result.id = name;
  17403. if (newParent) {
  17404. result.parent = newParent;
  17405. }
  17406. if (!doNotCloneChildren) {
  17407. // Children
  17408. var directDescendants = this.getDescendants(true);
  17409. for (var index = 0; index < directDescendants.length; index++) {
  17410. var child = directDescendants[index];
  17411. if (child.clone) {
  17412. child.clone(name + "." + child.name, result);
  17413. }
  17414. }
  17415. }
  17416. return result;
  17417. };
  17418. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17419. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17420. serializationObject.type = this.getClassName();
  17421. // Parent
  17422. if (this.parent) {
  17423. serializationObject.parentId = this.parent.id;
  17424. }
  17425. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17426. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17427. }
  17428. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17429. serializationObject.isEnabled = this.isEnabled();
  17430. // Parent
  17431. if (this.parent) {
  17432. serializationObject.parentId = this.parent.id;
  17433. }
  17434. return serializationObject;
  17435. };
  17436. // Statics
  17437. /**
  17438. * Returns a new TransformNode object parsed from the source provided.
  17439. * The parameter `parsedMesh` is the source.
  17440. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17441. */
  17442. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17443. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17444. if (BABYLON.Tags) {
  17445. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17446. }
  17447. if (parsedTransformNode.localMatrix) {
  17448. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17449. }
  17450. else if (parsedTransformNode.pivotMatrix) {
  17451. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17452. }
  17453. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17454. // Parent
  17455. if (parsedTransformNode.parentId) {
  17456. transformNode._waitingParentId = parsedTransformNode.parentId;
  17457. }
  17458. return transformNode;
  17459. };
  17460. /**
  17461. * Releases resources associated with this transform node.
  17462. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17463. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17464. */
  17465. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17466. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17467. // Animations
  17468. this.getScene().stopAnimation(this);
  17469. // Remove from scene
  17470. this.getScene().removeTransformNode(this);
  17471. this.onAfterWorldMatrixUpdateObservable.clear();
  17472. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17473. };
  17474. // Statics
  17475. TransformNode.BILLBOARDMODE_NONE = 0;
  17476. TransformNode.BILLBOARDMODE_X = 1;
  17477. TransformNode.BILLBOARDMODE_Y = 2;
  17478. TransformNode.BILLBOARDMODE_Z = 4;
  17479. TransformNode.BILLBOARDMODE_ALL = 7;
  17480. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17481. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17482. __decorate([
  17483. BABYLON.serializeAsVector3()
  17484. ], TransformNode.prototype, "_rotation", void 0);
  17485. __decorate([
  17486. BABYLON.serializeAsQuaternion()
  17487. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17488. __decorate([
  17489. BABYLON.serializeAsVector3()
  17490. ], TransformNode.prototype, "_scaling", void 0);
  17491. __decorate([
  17492. BABYLON.serialize()
  17493. ], TransformNode.prototype, "billboardMode", void 0);
  17494. __decorate([
  17495. BABYLON.serialize()
  17496. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17497. __decorate([
  17498. BABYLON.serialize()
  17499. ], TransformNode.prototype, "infiniteDistance", void 0);
  17500. __decorate([
  17501. BABYLON.serializeAsVector3()
  17502. ], TransformNode.prototype, "position", void 0);
  17503. return TransformNode;
  17504. }(BABYLON.Node));
  17505. BABYLON.TransformNode = TransformNode;
  17506. })(BABYLON || (BABYLON = {}));
  17507. //# sourceMappingURL=babylon.transformNode.js.map
  17508. var BABYLON;
  17509. (function (BABYLON) {
  17510. var AbstractMesh = /** @class */ (function (_super) {
  17511. __extends(AbstractMesh, _super);
  17512. // Constructor
  17513. function AbstractMesh(name, scene) {
  17514. if (scene === void 0) { scene = null; }
  17515. var _this = _super.call(this, name, scene, false) || this;
  17516. _this._facetNb = 0; // facet number
  17517. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17518. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17519. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17520. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17521. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17522. _this._subDiv = {
  17523. max: 1,
  17524. X: 1,
  17525. Y: 1,
  17526. Z: 1
  17527. };
  17528. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17529. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17530. // Events
  17531. /**
  17532. * An event triggered when this mesh collides with another one
  17533. * @type {BABYLON.Observable}
  17534. */
  17535. _this.onCollideObservable = new BABYLON.Observable();
  17536. /**
  17537. * An event triggered when the collision's position changes
  17538. * @type {BABYLON.Observable}
  17539. */
  17540. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17541. /**
  17542. * An event triggered when material is changed
  17543. * @type {BABYLON.Observable}
  17544. */
  17545. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17546. // Properties
  17547. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17548. /**
  17549. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17550. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17551. * or
  17552. * 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.
  17553. * for more info check WebGl documentations
  17554. */
  17555. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17556. /**
  17557. * 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:
  17558. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17559. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17560. * 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.
  17561. */
  17562. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17563. /**
  17564. * 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.
  17565. * The default value is -1 which means don't break the query and wait till the result.
  17566. */
  17567. _this.occlusionRetryCount = -1;
  17568. _this._occlusionInternalRetryCounter = 0;
  17569. _this._isOccluded = false;
  17570. _this._isOcclusionQueryInProgress = false;
  17571. _this._visibility = 1.0;
  17572. _this.alphaIndex = Number.MAX_VALUE;
  17573. _this.isVisible = true;
  17574. _this.isPickable = true;
  17575. _this.showBoundingBox = false;
  17576. _this.showSubMeshesBoundingBox = false;
  17577. _this.isBlocker = false;
  17578. _this.enablePointerMoveEvents = false;
  17579. _this.renderingGroupId = 0;
  17580. _this._receiveShadows = false;
  17581. _this.renderOutline = false;
  17582. _this.outlineColor = BABYLON.Color3.Red();
  17583. _this.outlineWidth = 0.02;
  17584. _this.renderOverlay = false;
  17585. _this.overlayColor = BABYLON.Color3.Red();
  17586. _this.overlayAlpha = 0.5;
  17587. _this._hasVertexAlpha = false;
  17588. _this._useVertexColors = true;
  17589. _this._computeBonesUsingShaders = true;
  17590. _this._numBoneInfluencers = 4;
  17591. _this._applyFog = true;
  17592. _this.useOctreeForRenderingSelection = true;
  17593. _this.useOctreeForPicking = true;
  17594. _this.useOctreeForCollisions = true;
  17595. _this._layerMask = 0x0FFFFFFF;
  17596. /**
  17597. * True if the mesh must be rendered in any case.
  17598. */
  17599. _this.alwaysSelectAsActiveMesh = false;
  17600. /**
  17601. * This scene's action manager
  17602. * @type {BABYLON.ActionManager}
  17603. */
  17604. _this.actionManager = null;
  17605. // Physics
  17606. _this.physicsImpostor = null;
  17607. // Collisions
  17608. _this._checkCollisions = false;
  17609. _this._collisionMask = -1;
  17610. _this._collisionGroup = -1;
  17611. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17612. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17613. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17614. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17615. // Edges
  17616. _this.edgesWidth = 1;
  17617. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17618. // Cache
  17619. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17620. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17621. _this._renderId = 0;
  17622. _this._intersectionsInProgress = new Array();
  17623. _this._unIndexed = false;
  17624. _this._lightSources = new Array();
  17625. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17626. if (collidedMesh === void 0) { collidedMesh = null; }
  17627. //TODO move this to the collision coordinator!
  17628. if (_this.getScene().workerCollisions)
  17629. newPosition.multiplyInPlace(_this._collider._radius);
  17630. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17631. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17632. _this.position.addInPlace(_this._diffPositionForCollisions);
  17633. }
  17634. if (collidedMesh) {
  17635. _this.onCollideObservable.notifyObservers(collidedMesh);
  17636. }
  17637. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17638. };
  17639. _this.getScene().addMesh(_this);
  17640. _this._resyncLightSources();
  17641. return _this;
  17642. }
  17643. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17644. get: function () {
  17645. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17646. },
  17647. enumerable: true,
  17648. configurable: true
  17649. });
  17650. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17651. get: function () {
  17652. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17653. },
  17654. enumerable: true,
  17655. configurable: true
  17656. });
  17657. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17658. get: function () {
  17659. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17660. },
  17661. enumerable: true,
  17662. configurable: true
  17663. });
  17664. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17665. get: function () {
  17666. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17667. },
  17668. enumerable: true,
  17669. configurable: true
  17670. });
  17671. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17672. get: function () {
  17673. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17674. },
  17675. enumerable: true,
  17676. configurable: true
  17677. });
  17678. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17679. /**
  17680. * Read-only : the number of facets in the mesh
  17681. */
  17682. get: function () {
  17683. return this._facetNb;
  17684. },
  17685. enumerable: true,
  17686. configurable: true
  17687. });
  17688. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17689. /**
  17690. * The number (integer) of subdivisions per axis in the partioning space
  17691. */
  17692. get: function () {
  17693. return this._partitioningSubdivisions;
  17694. },
  17695. set: function (nb) {
  17696. this._partitioningSubdivisions = nb;
  17697. },
  17698. enumerable: true,
  17699. configurable: true
  17700. });
  17701. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17702. /**
  17703. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17704. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17705. */
  17706. get: function () {
  17707. return this._partitioningBBoxRatio;
  17708. },
  17709. set: function (ratio) {
  17710. this._partitioningBBoxRatio = ratio;
  17711. },
  17712. enumerable: true,
  17713. configurable: true
  17714. });
  17715. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17716. /**
  17717. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17718. * Works only for updatable meshes.
  17719. * Doesn't work with multi-materials.
  17720. */
  17721. get: function () {
  17722. return this._facetDepthSort;
  17723. },
  17724. set: function (sort) {
  17725. this._facetDepthSort = sort;
  17726. },
  17727. enumerable: true,
  17728. configurable: true
  17729. });
  17730. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17731. /**
  17732. * The location (Vector3) where the facet depth sort must be computed from.
  17733. * By default, the active camera position.
  17734. * Used only when facet depth sort is enabled.
  17735. */
  17736. get: function () {
  17737. return this._facetDepthSortFrom;
  17738. },
  17739. set: function (location) {
  17740. this._facetDepthSortFrom = location;
  17741. },
  17742. enumerable: true,
  17743. configurable: true
  17744. });
  17745. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17746. /**
  17747. * Read-only boolean : is the feature facetData enabled ?
  17748. */
  17749. get: function () {
  17750. return this._facetDataEnabled;
  17751. },
  17752. enumerable: true,
  17753. configurable: true
  17754. });
  17755. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17756. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17757. return false;
  17758. }
  17759. this._markSubMeshesAsMiscDirty();
  17760. return true;
  17761. };
  17762. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17763. set: function (callback) {
  17764. if (this._onCollideObserver) {
  17765. this.onCollideObservable.remove(this._onCollideObserver);
  17766. }
  17767. this._onCollideObserver = this.onCollideObservable.add(callback);
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17773. set: function (callback) {
  17774. if (this._onCollisionPositionChangeObserver) {
  17775. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17776. }
  17777. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17783. /**
  17784. * 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.
  17785. */
  17786. get: function () {
  17787. return this._isOccluded;
  17788. },
  17789. set: function (value) {
  17790. this._isOccluded = value;
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17796. /**
  17797. * Flag to check the progress status of the query
  17798. */
  17799. get: function () {
  17800. return this._isOcclusionQueryInProgress;
  17801. },
  17802. enumerable: true,
  17803. configurable: true
  17804. });
  17805. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17806. /**
  17807. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17808. */
  17809. get: function () {
  17810. return this._visibility;
  17811. },
  17812. /**
  17813. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17814. */
  17815. set: function (value) {
  17816. if (this._visibility === value) {
  17817. return;
  17818. }
  17819. this._visibility = value;
  17820. this._markSubMeshesAsMiscDirty();
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. Object.defineProperty(AbstractMesh.prototype, "material", {
  17826. get: function () {
  17827. return this._material;
  17828. },
  17829. set: function (value) {
  17830. if (this._material === value) {
  17831. return;
  17832. }
  17833. this._material = value;
  17834. if (this.onMaterialChangedObservable.hasObservers) {
  17835. this.onMaterialChangedObservable.notifyObservers(this);
  17836. }
  17837. if (!this.subMeshes) {
  17838. return;
  17839. }
  17840. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17841. var subMesh = _a[_i];
  17842. subMesh.setEffect(null);
  17843. }
  17844. },
  17845. enumerable: true,
  17846. configurable: true
  17847. });
  17848. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17849. get: function () {
  17850. return this._receiveShadows;
  17851. },
  17852. set: function (value) {
  17853. if (this._receiveShadows === value) {
  17854. return;
  17855. }
  17856. this._receiveShadows = value;
  17857. this._markSubMeshesAsLightDirty();
  17858. },
  17859. enumerable: true,
  17860. configurable: true
  17861. });
  17862. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17863. get: function () {
  17864. return this._hasVertexAlpha;
  17865. },
  17866. set: function (value) {
  17867. if (this._hasVertexAlpha === value) {
  17868. return;
  17869. }
  17870. this._hasVertexAlpha = value;
  17871. this._markSubMeshesAsAttributesDirty();
  17872. this._markSubMeshesAsMiscDirty();
  17873. },
  17874. enumerable: true,
  17875. configurable: true
  17876. });
  17877. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17878. get: function () {
  17879. return this._useVertexColors;
  17880. },
  17881. set: function (value) {
  17882. if (this._useVertexColors === value) {
  17883. return;
  17884. }
  17885. this._useVertexColors = value;
  17886. this._markSubMeshesAsAttributesDirty();
  17887. },
  17888. enumerable: true,
  17889. configurable: true
  17890. });
  17891. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17892. get: function () {
  17893. return this._computeBonesUsingShaders;
  17894. },
  17895. set: function (value) {
  17896. if (this._computeBonesUsingShaders === value) {
  17897. return;
  17898. }
  17899. this._computeBonesUsingShaders = value;
  17900. this._markSubMeshesAsAttributesDirty();
  17901. },
  17902. enumerable: true,
  17903. configurable: true
  17904. });
  17905. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17906. get: function () {
  17907. return this._numBoneInfluencers;
  17908. },
  17909. set: function (value) {
  17910. if (this._numBoneInfluencers === value) {
  17911. return;
  17912. }
  17913. this._numBoneInfluencers = value;
  17914. this._markSubMeshesAsAttributesDirty();
  17915. },
  17916. enumerable: true,
  17917. configurable: true
  17918. });
  17919. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17920. get: function () {
  17921. return this._applyFog;
  17922. },
  17923. set: function (value) {
  17924. if (this._applyFog === value) {
  17925. return;
  17926. }
  17927. this._applyFog = value;
  17928. this._markSubMeshesAsMiscDirty();
  17929. },
  17930. enumerable: true,
  17931. configurable: true
  17932. });
  17933. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17934. get: function () {
  17935. return this._layerMask;
  17936. },
  17937. set: function (value) {
  17938. if (value === this._layerMask) {
  17939. return;
  17940. }
  17941. this._layerMask = value;
  17942. this._resyncLightSources();
  17943. },
  17944. enumerable: true,
  17945. configurable: true
  17946. });
  17947. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17948. get: function () {
  17949. return this._collisionMask;
  17950. },
  17951. set: function (mask) {
  17952. this._collisionMask = !isNaN(mask) ? mask : -1;
  17953. },
  17954. enumerable: true,
  17955. configurable: true
  17956. });
  17957. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17958. get: function () {
  17959. return this._collisionGroup;
  17960. },
  17961. set: function (mask) {
  17962. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17963. },
  17964. enumerable: true,
  17965. configurable: true
  17966. });
  17967. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17968. get: function () {
  17969. return null;
  17970. },
  17971. enumerable: true,
  17972. configurable: true
  17973. });
  17974. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17975. get: function () {
  17976. return this._skeleton;
  17977. },
  17978. set: function (value) {
  17979. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17980. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17981. }
  17982. if (value && value.needInitialSkinMatrix) {
  17983. value._registerMeshWithPoseMatrix(this);
  17984. }
  17985. this._skeleton = value;
  17986. if (!this._skeleton) {
  17987. this._bonesTransformMatrices = null;
  17988. }
  17989. this._markSubMeshesAsAttributesDirty();
  17990. },
  17991. enumerable: true,
  17992. configurable: true
  17993. });
  17994. /**
  17995. * Returns the string "AbstractMesh"
  17996. */
  17997. AbstractMesh.prototype.getClassName = function () {
  17998. return "AbstractMesh";
  17999. };
  18000. /**
  18001. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18002. */
  18003. AbstractMesh.prototype.toString = function (fullDetails) {
  18004. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  18005. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  18006. if (this._skeleton) {
  18007. ret += ", skeleton: " + this._skeleton.name;
  18008. }
  18009. if (fullDetails) {
  18010. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  18011. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  18012. }
  18013. return ret;
  18014. };
  18015. AbstractMesh.prototype._rebuild = function () {
  18016. if (this._occlusionQuery) {
  18017. this._occlusionQuery = null;
  18018. }
  18019. if (this._edgesRenderer) {
  18020. this._edgesRenderer._rebuild();
  18021. }
  18022. if (!this.subMeshes) {
  18023. return;
  18024. }
  18025. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18026. var subMesh = _a[_i];
  18027. subMesh._rebuild();
  18028. }
  18029. };
  18030. AbstractMesh.prototype._resyncLightSources = function () {
  18031. this._lightSources.length = 0;
  18032. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  18033. var light = _a[_i];
  18034. if (!light.isEnabled()) {
  18035. continue;
  18036. }
  18037. if (light.canAffectMesh(this)) {
  18038. this._lightSources.push(light);
  18039. }
  18040. }
  18041. this._markSubMeshesAsLightDirty();
  18042. };
  18043. AbstractMesh.prototype._resyncLighSource = function (light) {
  18044. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18045. var index = this._lightSources.indexOf(light);
  18046. if (index === -1) {
  18047. if (!isIn) {
  18048. return;
  18049. }
  18050. this._lightSources.push(light);
  18051. }
  18052. else {
  18053. if (isIn) {
  18054. return;
  18055. }
  18056. this._lightSources.splice(index, 1);
  18057. }
  18058. this._markSubMeshesAsLightDirty();
  18059. };
  18060. AbstractMesh.prototype._removeLightSource = function (light) {
  18061. var index = this._lightSources.indexOf(light);
  18062. if (index === -1) {
  18063. return;
  18064. }
  18065. this._lightSources.splice(index, 1);
  18066. this._markSubMeshesAsLightDirty();
  18067. };
  18068. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18069. if (!this.subMeshes) {
  18070. return;
  18071. }
  18072. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18073. var subMesh = _a[_i];
  18074. if (subMesh._materialDefines) {
  18075. func(subMesh._materialDefines);
  18076. }
  18077. }
  18078. };
  18079. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18080. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18081. };
  18082. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18083. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18084. };
  18085. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18086. if (!this.subMeshes) {
  18087. return;
  18088. }
  18089. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18090. var subMesh = _a[_i];
  18091. var material = subMesh.getMaterial();
  18092. if (material) {
  18093. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18094. }
  18095. }
  18096. };
  18097. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18098. /**
  18099. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18100. * Default : (1.0, 1.0, 1.0)
  18101. */
  18102. get: function () {
  18103. return this._scaling;
  18104. },
  18105. /**
  18106. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18107. * Default : (1.0, 1.0, 1.0)
  18108. */
  18109. set: function (newScaling) {
  18110. this._scaling = newScaling;
  18111. if (this.physicsImpostor) {
  18112. this.physicsImpostor.forceUpdate();
  18113. }
  18114. },
  18115. enumerable: true,
  18116. configurable: true
  18117. });
  18118. // Methods
  18119. /**
  18120. * Disables the mesh edger rendering mode.
  18121. * Returns the AbstractMesh.
  18122. */
  18123. AbstractMesh.prototype.disableEdgesRendering = function () {
  18124. if (this._edgesRenderer) {
  18125. this._edgesRenderer.dispose();
  18126. this._edgesRenderer = null;
  18127. }
  18128. return this;
  18129. };
  18130. /**
  18131. * Enables the edge rendering mode on the mesh.
  18132. * This mode makes the mesh edges visible.
  18133. * Returns the AbstractMesh.
  18134. */
  18135. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18136. if (epsilon === void 0) { epsilon = 0.95; }
  18137. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18138. this.disableEdgesRendering();
  18139. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18140. return this;
  18141. };
  18142. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18143. /**
  18144. * Returns true if the mesh is blocked. Used by the class Mesh.
  18145. * Returns the boolean `false` by default.
  18146. */
  18147. get: function () {
  18148. return false;
  18149. },
  18150. enumerable: true,
  18151. configurable: true
  18152. });
  18153. /**
  18154. * Returns the mesh itself by default, used by the class Mesh.
  18155. * Returned type : AbstractMesh
  18156. */
  18157. AbstractMesh.prototype.getLOD = function (camera) {
  18158. return this;
  18159. };
  18160. /**
  18161. * Returns 0 by default, used by the class Mesh.
  18162. * Returns an integer.
  18163. */
  18164. AbstractMesh.prototype.getTotalVertices = function () {
  18165. return 0;
  18166. };
  18167. /**
  18168. * Returns null by default, used by the class Mesh.
  18169. * Returned type : integer array
  18170. */
  18171. AbstractMesh.prototype.getIndices = function () {
  18172. return null;
  18173. };
  18174. /**
  18175. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18176. * Returned type : float array or Float32Array
  18177. */
  18178. AbstractMesh.prototype.getVerticesData = function (kind) {
  18179. return null;
  18180. };
  18181. /**
  18182. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18183. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18184. * The `data` are either a numeric array either a Float32Array.
  18185. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18186. * 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).
  18187. * Note that a new underlying VertexBuffer object is created each call.
  18188. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18189. *
  18190. * Possible `kind` values :
  18191. * - BABYLON.VertexBuffer.PositionKind
  18192. * - BABYLON.VertexBuffer.UVKind
  18193. * - BABYLON.VertexBuffer.UV2Kind
  18194. * - BABYLON.VertexBuffer.UV3Kind
  18195. * - BABYLON.VertexBuffer.UV4Kind
  18196. * - BABYLON.VertexBuffer.UV5Kind
  18197. * - BABYLON.VertexBuffer.UV6Kind
  18198. * - BABYLON.VertexBuffer.ColorKind
  18199. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18200. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18201. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18202. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18203. *
  18204. * Returns the Mesh.
  18205. */
  18206. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18207. return this;
  18208. };
  18209. /**
  18210. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18211. * If the mesh has no geometry, it is simply returned as it is.
  18212. * The `data` are either a numeric array either a Float32Array.
  18213. * No new underlying VertexBuffer object is created.
  18214. * 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.
  18215. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18216. *
  18217. * Possible `kind` values :
  18218. * - BABYLON.VertexBuffer.PositionKind
  18219. * - BABYLON.VertexBuffer.UVKind
  18220. * - BABYLON.VertexBuffer.UV2Kind
  18221. * - BABYLON.VertexBuffer.UV3Kind
  18222. * - BABYLON.VertexBuffer.UV4Kind
  18223. * - BABYLON.VertexBuffer.UV5Kind
  18224. * - BABYLON.VertexBuffer.UV6Kind
  18225. * - BABYLON.VertexBuffer.ColorKind
  18226. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18227. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18228. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18229. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18230. *
  18231. * Returns the Mesh.
  18232. */
  18233. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18234. return this;
  18235. };
  18236. /**
  18237. * Sets the mesh indices.
  18238. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18239. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18240. * This method creates a new index buffer each call.
  18241. * Returns the Mesh.
  18242. */
  18243. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18244. return this;
  18245. };
  18246. /** Returns false by default, used by the class Mesh.
  18247. * Returns a boolean
  18248. */
  18249. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18250. return false;
  18251. };
  18252. /**
  18253. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18254. * Returns a BoundingInfo
  18255. */
  18256. AbstractMesh.prototype.getBoundingInfo = function () {
  18257. if (this._masterMesh) {
  18258. return this._masterMesh.getBoundingInfo();
  18259. }
  18260. if (!this._boundingInfo) {
  18261. // this._boundingInfo is being created here
  18262. this._updateBoundingInfo();
  18263. }
  18264. // cannot be null.
  18265. return this._boundingInfo;
  18266. };
  18267. /**
  18268. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18269. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18270. */
  18271. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18272. if (includeDescendants === void 0) { includeDescendants = true; }
  18273. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18274. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18275. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18276. if (maxDimension === 0) {
  18277. return this;
  18278. }
  18279. var scale = 1 / maxDimension;
  18280. this.scaling.scaleInPlace(scale);
  18281. return this;
  18282. };
  18283. /**
  18284. * Sets a mesh new object BoundingInfo.
  18285. * Returns the AbstractMesh.
  18286. */
  18287. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18288. this._boundingInfo = boundingInfo;
  18289. return this;
  18290. };
  18291. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18292. get: function () {
  18293. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18294. },
  18295. enumerable: true,
  18296. configurable: true
  18297. });
  18298. AbstractMesh.prototype._preActivate = function () {
  18299. };
  18300. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18301. };
  18302. AbstractMesh.prototype._activate = function (renderId) {
  18303. this._renderId = renderId;
  18304. };
  18305. /**
  18306. * Returns the latest update of the World matrix
  18307. * Returns a Matrix.
  18308. */
  18309. AbstractMesh.prototype.getWorldMatrix = function () {
  18310. if (this._masterMesh) {
  18311. return this._masterMesh.getWorldMatrix();
  18312. }
  18313. return _super.prototype.getWorldMatrix.call(this);
  18314. };
  18315. /**
  18316. * Returns the latest update of the World matrix determinant.
  18317. */
  18318. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18319. if (this._masterMesh) {
  18320. return this._masterMesh._getWorldMatrixDeterminant();
  18321. }
  18322. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18323. };
  18324. // ================================== Point of View Movement =================================
  18325. /**
  18326. * Perform relative position change from the point of view of behind the front of the mesh.
  18327. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18328. * Supports definition of mesh facing forward or backward.
  18329. * @param {number} amountRight
  18330. * @param {number} amountUp
  18331. * @param {number} amountForward
  18332. *
  18333. * Returns the AbstractMesh.
  18334. */
  18335. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18336. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18337. return this;
  18338. };
  18339. /**
  18340. * Calculate relative position change from the point of view of behind the front of the mesh.
  18341. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18342. * Supports definition of mesh facing forward or backward.
  18343. * @param {number} amountRight
  18344. * @param {number} amountUp
  18345. * @param {number} amountForward
  18346. *
  18347. * Returns a new Vector3.
  18348. */
  18349. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18350. var rotMatrix = new BABYLON.Matrix();
  18351. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18352. rotQuaternion.toRotationMatrix(rotMatrix);
  18353. var translationDelta = BABYLON.Vector3.Zero();
  18354. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18355. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18356. return translationDelta;
  18357. };
  18358. // ================================== Point of View Rotation =================================
  18359. /**
  18360. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18361. * Supports definition of mesh facing forward or backward.
  18362. * @param {number} flipBack
  18363. * @param {number} twirlClockwise
  18364. * @param {number} tiltRight
  18365. *
  18366. * Returns the AbstractMesh.
  18367. */
  18368. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18369. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18370. return this;
  18371. };
  18372. /**
  18373. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18374. * Supports definition of mesh facing forward or backward.
  18375. * @param {number} flipBack
  18376. * @param {number} twirlClockwise
  18377. * @param {number} tiltRight
  18378. *
  18379. * Returns a new Vector3.
  18380. */
  18381. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18382. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18383. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18384. };
  18385. /**
  18386. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18387. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18388. */
  18389. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18390. if (includeDescendants === void 0) { includeDescendants = true; }
  18391. this.computeWorldMatrix(true);
  18392. var min;
  18393. var max;
  18394. var boundingInfo = this.getBoundingInfo();
  18395. if (!this.subMeshes) {
  18396. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18397. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18398. }
  18399. else {
  18400. min = boundingInfo.boundingBox.minimumWorld;
  18401. max = boundingInfo.boundingBox.maximumWorld;
  18402. }
  18403. if (includeDescendants) {
  18404. var descendants = this.getDescendants(false);
  18405. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18406. var descendant = descendants_1[_i];
  18407. var childMesh = descendant;
  18408. childMesh.computeWorldMatrix(true);
  18409. //make sure we have the needed params to get mix and max
  18410. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18411. continue;
  18412. }
  18413. var childBoundingInfo = childMesh.getBoundingInfo();
  18414. var boundingBox = childBoundingInfo.boundingBox;
  18415. var minBox = boundingBox.minimumWorld;
  18416. var maxBox = boundingBox.maximumWorld;
  18417. BABYLON.Tools.CheckExtends(minBox, min, max);
  18418. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18419. }
  18420. }
  18421. return {
  18422. min: min,
  18423. max: max
  18424. };
  18425. };
  18426. /**
  18427. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18428. * Returns the AbstractMesh.
  18429. */
  18430. AbstractMesh.prototype._updateBoundingInfo = function () {
  18431. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18432. this._boundingInfo.update(this.worldMatrixFromCache);
  18433. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18434. return this;
  18435. };
  18436. /**
  18437. * Update a mesh's children BoundingInfo objects only.
  18438. * Returns the AbstractMesh.
  18439. */
  18440. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18441. if (!this.subMeshes) {
  18442. return this;
  18443. }
  18444. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18445. var subMesh = this.subMeshes[subIndex];
  18446. if (!subMesh.IsGlobal) {
  18447. subMesh.updateBoundingInfo(matrix);
  18448. }
  18449. }
  18450. return this;
  18451. };
  18452. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18453. // Bounding info
  18454. this._updateBoundingInfo();
  18455. };
  18456. /**
  18457. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18458. * A mesh is in the frustum if its bounding box intersects the frustum.
  18459. * Boolean returned.
  18460. */
  18461. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18462. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18463. };
  18464. /**
  18465. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18466. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18467. * Boolean returned.
  18468. */
  18469. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18470. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18471. ;
  18472. };
  18473. /**
  18474. * True if the mesh intersects another mesh or a SolidParticle object.
  18475. * 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)
  18476. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18477. * Returns a boolean.
  18478. */
  18479. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18480. if (precise === void 0) { precise = false; }
  18481. if (!this._boundingInfo || !mesh._boundingInfo) {
  18482. return false;
  18483. }
  18484. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18485. return true;
  18486. }
  18487. if (includeDescendants) {
  18488. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18489. var child = _a[_i];
  18490. if (child.intersectsMesh(mesh, precise, true)) {
  18491. return true;
  18492. }
  18493. }
  18494. }
  18495. return false;
  18496. };
  18497. /**
  18498. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18499. * Returns a boolean.
  18500. */
  18501. AbstractMesh.prototype.intersectsPoint = function (point) {
  18502. if (!this._boundingInfo) {
  18503. return false;
  18504. }
  18505. return this._boundingInfo.intersectsPoint(point);
  18506. };
  18507. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18508. return this.physicsImpostor;
  18509. };
  18510. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18511. if (camera === void 0) { camera = null; }
  18512. if (!camera) {
  18513. camera = this.getScene().activeCamera;
  18514. }
  18515. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18516. };
  18517. /**
  18518. * Returns the distance from the mesh to the active camera.
  18519. * Returns a float.
  18520. */
  18521. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18522. if (camera === void 0) { camera = null; }
  18523. if (!camera) {
  18524. camera = this.getScene().activeCamera;
  18525. }
  18526. return this.absolutePosition.subtract(camera.position).length();
  18527. };
  18528. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18529. if (!this.physicsImpostor) {
  18530. return this;
  18531. }
  18532. this.physicsImpostor.applyImpulse(force, contactPoint);
  18533. return this;
  18534. };
  18535. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18536. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18537. return this;
  18538. }
  18539. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18540. mainPivot: pivot1,
  18541. connectedPivot: pivot2,
  18542. nativeParams: options
  18543. });
  18544. return this;
  18545. };
  18546. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18547. // Collisions
  18548. /**
  18549. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18550. * Default `false`.
  18551. */
  18552. get: function () {
  18553. return this._checkCollisions;
  18554. },
  18555. set: function (collisionEnabled) {
  18556. this._checkCollisions = collisionEnabled;
  18557. if (this.getScene().workerCollisions) {
  18558. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18559. }
  18560. },
  18561. enumerable: true,
  18562. configurable: true
  18563. });
  18564. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18565. /**
  18566. * Gets Collider object used to compute collisions (not physics)
  18567. */
  18568. get: function () {
  18569. return this._collider;
  18570. },
  18571. enumerable: true,
  18572. configurable: true
  18573. });
  18574. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18575. var globalPosition = this.getAbsolutePosition();
  18576. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18577. if (!this._collider) {
  18578. this._collider = new BABYLON.Collider();
  18579. }
  18580. this._collider._radius = this.ellipsoid;
  18581. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18582. return this;
  18583. };
  18584. // Submeshes octree
  18585. /**
  18586. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18587. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18588. * Returns an Octree of submeshes.
  18589. */
  18590. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18591. if (maxCapacity === void 0) { maxCapacity = 64; }
  18592. if (maxDepth === void 0) { maxDepth = 2; }
  18593. if (!this._submeshesOctree) {
  18594. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18595. }
  18596. this.computeWorldMatrix(true);
  18597. var boundingInfo = this.getBoundingInfo();
  18598. // Update octree
  18599. var bbox = boundingInfo.boundingBox;
  18600. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18601. return this._submeshesOctree;
  18602. };
  18603. // Collisions
  18604. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18605. this._generatePointsArray();
  18606. if (!this._positions) {
  18607. return this;
  18608. }
  18609. // Transformation
  18610. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18611. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18612. subMesh._lastColliderWorldVertices = [];
  18613. subMesh._trianglePlanes = [];
  18614. var start = subMesh.verticesStart;
  18615. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18616. for (var i = start; i < end; i++) {
  18617. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18618. }
  18619. }
  18620. // Collide
  18621. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18622. if (collider.collisionFound) {
  18623. collider.collidedMesh = this;
  18624. }
  18625. return this;
  18626. };
  18627. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18628. var subMeshes;
  18629. var len;
  18630. // Octrees
  18631. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18632. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18633. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18634. len = intersections.length;
  18635. subMeshes = intersections.data;
  18636. }
  18637. else {
  18638. subMeshes = this.subMeshes;
  18639. len = subMeshes.length;
  18640. }
  18641. for (var index = 0; index < len; index++) {
  18642. var subMesh = subMeshes[index];
  18643. // Bounding test
  18644. if (len > 1 && !subMesh._checkCollision(collider))
  18645. continue;
  18646. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18647. }
  18648. return this;
  18649. };
  18650. AbstractMesh.prototype._checkCollision = function (collider) {
  18651. // Bounding box test
  18652. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18653. return this;
  18654. // Transformation matrix
  18655. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18656. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18657. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18658. return this;
  18659. };
  18660. // Picking
  18661. AbstractMesh.prototype._generatePointsArray = function () {
  18662. return false;
  18663. };
  18664. /**
  18665. * Checks if the passed Ray intersects with the mesh.
  18666. * Returns an object PickingInfo.
  18667. */
  18668. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18669. var pickingInfo = new BABYLON.PickingInfo();
  18670. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18671. return pickingInfo;
  18672. }
  18673. if (!this._generatePointsArray()) {
  18674. return pickingInfo;
  18675. }
  18676. var intersectInfo = null;
  18677. // Octrees
  18678. var subMeshes;
  18679. var len;
  18680. if (this._submeshesOctree && this.useOctreeForPicking) {
  18681. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18682. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18683. len = intersections.length;
  18684. subMeshes = intersections.data;
  18685. }
  18686. else {
  18687. subMeshes = this.subMeshes;
  18688. len = subMeshes.length;
  18689. }
  18690. for (var index = 0; index < len; index++) {
  18691. var subMesh = subMeshes[index];
  18692. // Bounding test
  18693. if (len > 1 && !subMesh.canIntersects(ray))
  18694. continue;
  18695. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18696. if (currentIntersectInfo) {
  18697. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18698. intersectInfo = currentIntersectInfo;
  18699. intersectInfo.subMeshId = index;
  18700. if (fastCheck) {
  18701. break;
  18702. }
  18703. }
  18704. }
  18705. }
  18706. if (intersectInfo) {
  18707. // Get picked point
  18708. var world = this.getWorldMatrix();
  18709. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18710. var direction = ray.direction.clone();
  18711. direction = direction.scale(intersectInfo.distance);
  18712. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18713. var pickedPoint = worldOrigin.add(worldDirection);
  18714. // Return result
  18715. pickingInfo.hit = true;
  18716. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18717. pickingInfo.pickedPoint = pickedPoint;
  18718. pickingInfo.pickedMesh = this;
  18719. pickingInfo.bu = intersectInfo.bu || 0;
  18720. pickingInfo.bv = intersectInfo.bv || 0;
  18721. pickingInfo.faceId = intersectInfo.faceId;
  18722. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18723. return pickingInfo;
  18724. }
  18725. return pickingInfo;
  18726. };
  18727. /**
  18728. * Clones the mesh, used by the class Mesh.
  18729. * Just returns `null` for an AbstractMesh.
  18730. */
  18731. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18732. return null;
  18733. };
  18734. /**
  18735. * Disposes all the mesh submeshes.
  18736. * Returns the AbstractMesh.
  18737. */
  18738. AbstractMesh.prototype.releaseSubMeshes = function () {
  18739. if (this.subMeshes) {
  18740. while (this.subMeshes.length) {
  18741. this.subMeshes[0].dispose();
  18742. }
  18743. }
  18744. else {
  18745. this.subMeshes = new Array();
  18746. }
  18747. return this;
  18748. };
  18749. /**
  18750. * Releases resources associated with this abstract mesh.
  18751. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18752. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18753. */
  18754. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18755. var _this = this;
  18756. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18757. var index;
  18758. // Smart Array Retainers.
  18759. this.getScene().freeActiveMeshes();
  18760. this.getScene().freeRenderingGroups();
  18761. // Action manager
  18762. if (this.actionManager !== undefined && this.actionManager !== null) {
  18763. this.actionManager.dispose();
  18764. this.actionManager = null;
  18765. }
  18766. // Skeleton
  18767. this.skeleton = null;
  18768. // Physics
  18769. if (this.physicsImpostor) {
  18770. this.physicsImpostor.dispose();
  18771. }
  18772. // Intersections in progress
  18773. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18774. var other = this._intersectionsInProgress[index];
  18775. var pos = other._intersectionsInProgress.indexOf(this);
  18776. other._intersectionsInProgress.splice(pos, 1);
  18777. }
  18778. this._intersectionsInProgress = [];
  18779. // Lights
  18780. var lights = this.getScene().lights;
  18781. lights.forEach(function (light) {
  18782. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18783. if (meshIndex !== -1) {
  18784. light.includedOnlyMeshes.splice(meshIndex, 1);
  18785. }
  18786. meshIndex = light.excludedMeshes.indexOf(_this);
  18787. if (meshIndex !== -1) {
  18788. light.excludedMeshes.splice(meshIndex, 1);
  18789. }
  18790. // Shadow generators
  18791. var generator = light.getShadowGenerator();
  18792. if (generator) {
  18793. var shadowMap = generator.getShadowMap();
  18794. if (shadowMap && shadowMap.renderList) {
  18795. meshIndex = shadowMap.renderList.indexOf(_this);
  18796. if (meshIndex !== -1) {
  18797. shadowMap.renderList.splice(meshIndex, 1);
  18798. }
  18799. }
  18800. }
  18801. });
  18802. // Edges
  18803. if (this._edgesRenderer) {
  18804. this._edgesRenderer.dispose();
  18805. this._edgesRenderer = null;
  18806. }
  18807. // SubMeshes
  18808. if (this.getClassName() !== "InstancedMesh") {
  18809. this.releaseSubMeshes();
  18810. }
  18811. // Octree
  18812. var sceneOctree = this.getScene().selectionOctree;
  18813. if (sceneOctree !== undefined && sceneOctree !== null) {
  18814. var index = sceneOctree.dynamicContent.indexOf(this);
  18815. if (index !== -1) {
  18816. sceneOctree.dynamicContent.splice(index, 1);
  18817. }
  18818. }
  18819. // Query
  18820. var engine = this.getScene().getEngine();
  18821. if (this._occlusionQuery) {
  18822. this._isOcclusionQueryInProgress = false;
  18823. engine.deleteQuery(this._occlusionQuery);
  18824. this._occlusionQuery = null;
  18825. }
  18826. // Engine
  18827. engine.wipeCaches();
  18828. // Remove from scene
  18829. this.getScene().removeMesh(this);
  18830. if (disposeMaterialAndTextures) {
  18831. if (this.material) {
  18832. this.material.dispose(false, true);
  18833. }
  18834. }
  18835. if (!doNotRecurse) {
  18836. // Particles
  18837. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18838. if (this.getScene().particleSystems[index].emitter === this) {
  18839. this.getScene().particleSystems[index].dispose();
  18840. index--;
  18841. }
  18842. }
  18843. }
  18844. // facet data
  18845. if (this._facetDataEnabled) {
  18846. this.disableFacetData();
  18847. }
  18848. this.onAfterWorldMatrixUpdateObservable.clear();
  18849. this.onCollideObservable.clear();
  18850. this.onCollisionPositionChangeObservable.clear();
  18851. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18852. };
  18853. /**
  18854. * Adds the passed mesh as a child to the current mesh.
  18855. * Returns the AbstractMesh.
  18856. */
  18857. AbstractMesh.prototype.addChild = function (mesh) {
  18858. mesh.setParent(this);
  18859. return this;
  18860. };
  18861. /**
  18862. * Removes the passed mesh from the current mesh children list.
  18863. * Returns the AbstractMesh.
  18864. */
  18865. AbstractMesh.prototype.removeChild = function (mesh) {
  18866. mesh.setParent(null);
  18867. return this;
  18868. };
  18869. // Facet data
  18870. /**
  18871. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18872. * Returns the AbstractMesh.
  18873. */
  18874. AbstractMesh.prototype._initFacetData = function () {
  18875. if (!this._facetNormals) {
  18876. this._facetNormals = new Array();
  18877. }
  18878. if (!this._facetPositions) {
  18879. this._facetPositions = new Array();
  18880. }
  18881. if (!this._facetPartitioning) {
  18882. this._facetPartitioning = new Array();
  18883. }
  18884. this._facetNb = (this.getIndices().length / 3) | 0;
  18885. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18886. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18887. for (var f = 0; f < this._facetNb; f++) {
  18888. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18889. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18890. }
  18891. this._facetDataEnabled = true;
  18892. return this;
  18893. };
  18894. /**
  18895. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18896. * This method can be called within the render loop.
  18897. * 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.
  18898. * Returns the AbstractMesh.
  18899. */
  18900. AbstractMesh.prototype.updateFacetData = function () {
  18901. if (!this._facetDataEnabled) {
  18902. this._initFacetData();
  18903. }
  18904. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18905. var indices = this.getIndices();
  18906. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18907. var bInfo = this.getBoundingInfo();
  18908. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18909. // init arrays, matrix and sort function on first call
  18910. this._facetDepthSortEnabled = true;
  18911. if (indices instanceof Uint16Array) {
  18912. this._depthSortedIndices = new Uint16Array(indices);
  18913. }
  18914. else if (indices instanceof Uint32Array) {
  18915. this._depthSortedIndices = new Uint32Array(indices);
  18916. }
  18917. else {
  18918. var needs32bits = false;
  18919. for (var i = 0; i < indices.length; i++) {
  18920. if (indices[i] > 65535) {
  18921. needs32bits = true;
  18922. break;
  18923. }
  18924. }
  18925. if (needs32bits) {
  18926. this._depthSortedIndices = new Uint32Array(indices);
  18927. }
  18928. else {
  18929. this._depthSortedIndices = new Uint16Array(indices);
  18930. }
  18931. }
  18932. this._facetDepthSortFunction = function (f1, f2) {
  18933. return (f2.sqDistance - f1.sqDistance);
  18934. };
  18935. if (!this._facetDepthSortFrom) {
  18936. var camera = this.getScene().activeCamera;
  18937. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18938. }
  18939. this._depthSortedFacets = [];
  18940. for (var f = 0; f < this._facetNb; f++) {
  18941. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18942. this._depthSortedFacets.push(depthSortedFacet);
  18943. }
  18944. this._invertedMatrix = BABYLON.Matrix.Identity();
  18945. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18946. }
  18947. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18948. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18949. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18950. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18951. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18952. this._subDiv.max = this._partitioningSubdivisions;
  18953. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18954. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18955. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18956. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18957. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18958. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18959. // set the parameters for ComputeNormals()
  18960. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18961. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18962. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18963. this._facetParameters.bInfo = bInfo;
  18964. this._facetParameters.bbSize = this._bbSize;
  18965. this._facetParameters.subDiv = this._subDiv;
  18966. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18967. this._facetParameters.depthSort = this._facetDepthSort;
  18968. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18969. this.computeWorldMatrix(true);
  18970. this._worldMatrix.invertToRef(this._invertedMatrix);
  18971. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18972. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18973. }
  18974. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18975. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18976. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18977. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18978. var l = (this._depthSortedIndices.length / 3) | 0;
  18979. for (var f = 0; f < l; f++) {
  18980. var sind = this._depthSortedFacets[f].ind;
  18981. this._depthSortedIndices[f * 3] = indices[sind];
  18982. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18983. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18984. }
  18985. this.updateIndices(this._depthSortedIndices);
  18986. }
  18987. return this;
  18988. };
  18989. /**
  18990. * Returns the facetLocalNormals array.
  18991. * The normals are expressed in the mesh local space.
  18992. */
  18993. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18994. if (!this._facetNormals) {
  18995. this.updateFacetData();
  18996. }
  18997. return this._facetNormals;
  18998. };
  18999. /**
  19000. * Returns the facetLocalPositions array.
  19001. * The facet positions are expressed in the mesh local space.
  19002. */
  19003. AbstractMesh.prototype.getFacetLocalPositions = function () {
  19004. if (!this._facetPositions) {
  19005. this.updateFacetData();
  19006. }
  19007. return this._facetPositions;
  19008. };
  19009. /**
  19010. * Returns the facetLocalPartioning array.
  19011. */
  19012. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  19013. if (!this._facetPartitioning) {
  19014. this.updateFacetData();
  19015. }
  19016. return this._facetPartitioning;
  19017. };
  19018. /**
  19019. * Returns the i-th facet position in the world system.
  19020. * This method allocates a new Vector3 per call.
  19021. */
  19022. AbstractMesh.prototype.getFacetPosition = function (i) {
  19023. var pos = BABYLON.Vector3.Zero();
  19024. this.getFacetPositionToRef(i, pos);
  19025. return pos;
  19026. };
  19027. /**
  19028. * Sets the reference Vector3 with the i-th facet position in the world system.
  19029. * Returns the AbstractMesh.
  19030. */
  19031. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  19032. var localPos = (this.getFacetLocalPositions())[i];
  19033. var world = this.getWorldMatrix();
  19034. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  19035. return this;
  19036. };
  19037. /**
  19038. * Returns the i-th facet normal in the world system.
  19039. * This method allocates a new Vector3 per call.
  19040. */
  19041. AbstractMesh.prototype.getFacetNormal = function (i) {
  19042. var norm = BABYLON.Vector3.Zero();
  19043. this.getFacetNormalToRef(i, norm);
  19044. return norm;
  19045. };
  19046. /**
  19047. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19048. * Returns the AbstractMesh.
  19049. */
  19050. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19051. var localNorm = (this.getFacetLocalNormals())[i];
  19052. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19053. return this;
  19054. };
  19055. /**
  19056. * 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).
  19057. */
  19058. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19059. var bInfo = this.getBoundingInfo();
  19060. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19061. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19062. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19063. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19064. return null;
  19065. }
  19066. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19067. };
  19068. /**
  19069. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19070. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19071. * 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.
  19072. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19073. * 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.
  19074. */
  19075. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19076. if (checkFace === void 0) { checkFace = false; }
  19077. if (facing === void 0) { facing = true; }
  19078. var world = this.getWorldMatrix();
  19079. var invMat = BABYLON.Tmp.Matrix[5];
  19080. world.invertToRef(invMat);
  19081. var invVect = BABYLON.Tmp.Vector3[8];
  19082. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19083. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19084. if (projected) {
  19085. // tranform the local computed projected vector to world coordinates
  19086. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19087. }
  19088. return closest;
  19089. };
  19090. /**
  19091. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19092. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19093. * 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.
  19094. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19095. * 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.
  19096. */
  19097. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19098. if (checkFace === void 0) { checkFace = false; }
  19099. if (facing === void 0) { facing = true; }
  19100. var closest = null;
  19101. var tmpx = 0.0;
  19102. var tmpy = 0.0;
  19103. var tmpz = 0.0;
  19104. var d = 0.0; // tmp dot facet normal * facet position
  19105. var t0 = 0.0;
  19106. var projx = 0.0;
  19107. var projy = 0.0;
  19108. var projz = 0.0;
  19109. // Get all the facets in the same partitioning block than (x, y, z)
  19110. var facetPositions = this.getFacetLocalPositions();
  19111. var facetNormals = this.getFacetLocalNormals();
  19112. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19113. if (!facetsInBlock) {
  19114. return null;
  19115. }
  19116. // Get the closest facet to (x, y, z)
  19117. var shortest = Number.MAX_VALUE; // init distance vars
  19118. var tmpDistance = shortest;
  19119. var fib; // current facet in the block
  19120. var norm; // current facet normal
  19121. var p0; // current facet barycenter position
  19122. // loop on all the facets in the current partitioning block
  19123. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19124. fib = facetsInBlock[idx];
  19125. norm = facetNormals[fib];
  19126. p0 = facetPositions[fib];
  19127. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19128. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19129. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19130. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19131. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19132. projx = x + norm.x * t0;
  19133. projy = y + norm.y * t0;
  19134. projz = z + norm.z * t0;
  19135. tmpx = projx - x;
  19136. tmpy = projy - y;
  19137. tmpz = projz - z;
  19138. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19139. if (tmpDistance < shortest) {
  19140. shortest = tmpDistance;
  19141. closest = fib;
  19142. if (projected) {
  19143. projected.x = projx;
  19144. projected.y = projy;
  19145. projected.z = projz;
  19146. }
  19147. }
  19148. }
  19149. }
  19150. return closest;
  19151. };
  19152. /**
  19153. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19154. */
  19155. AbstractMesh.prototype.getFacetDataParameters = function () {
  19156. return this._facetParameters;
  19157. };
  19158. /**
  19159. * Disables the feature FacetData and frees the related memory.
  19160. * Returns the AbstractMesh.
  19161. */
  19162. AbstractMesh.prototype.disableFacetData = function () {
  19163. if (this._facetDataEnabled) {
  19164. this._facetDataEnabled = false;
  19165. this._facetPositions = new Array();
  19166. this._facetNormals = new Array();
  19167. this._facetPartitioning = new Array();
  19168. this._facetParameters = null;
  19169. this._depthSortedIndices = new Uint32Array(0);
  19170. }
  19171. return this;
  19172. };
  19173. /**
  19174. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19175. * Returns the mesh.
  19176. */
  19177. AbstractMesh.prototype.updateIndices = function (indices) {
  19178. return this;
  19179. };
  19180. /**
  19181. * The mesh Geometry. Actually used by the Mesh object.
  19182. * Returns a blank geometry object.
  19183. */
  19184. /**
  19185. * Creates new normals data for the mesh.
  19186. * @param updatable.
  19187. */
  19188. AbstractMesh.prototype.createNormals = function (updatable) {
  19189. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19190. var indices = this.getIndices();
  19191. var normals;
  19192. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19193. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19194. }
  19195. else {
  19196. normals = [];
  19197. }
  19198. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19199. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19200. };
  19201. /**
  19202. * Align the mesh with a normal.
  19203. * Returns the mesh.
  19204. */
  19205. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19206. if (!upDirection) {
  19207. upDirection = BABYLON.Axis.Y;
  19208. }
  19209. var axisX = BABYLON.Tmp.Vector3[0];
  19210. var axisZ = BABYLON.Tmp.Vector3[1];
  19211. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19212. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19213. if (this.rotationQuaternion) {
  19214. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19215. }
  19216. else {
  19217. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19218. }
  19219. return this;
  19220. };
  19221. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19222. var engine = this.getEngine();
  19223. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19224. this._isOccluded = false;
  19225. return;
  19226. }
  19227. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19228. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19229. if (isOcclusionQueryAvailable) {
  19230. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19231. this._isOcclusionQueryInProgress = false;
  19232. this._occlusionInternalRetryCounter = 0;
  19233. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19234. }
  19235. else {
  19236. this._occlusionInternalRetryCounter++;
  19237. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19238. this._isOcclusionQueryInProgress = false;
  19239. this._occlusionInternalRetryCounter = 0;
  19240. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19241. // if strict continue the last state of the object.
  19242. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19243. }
  19244. else {
  19245. return;
  19246. }
  19247. }
  19248. }
  19249. var scene = this.getScene();
  19250. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19251. if (!this._occlusionQuery) {
  19252. this._occlusionQuery = engine.createQuery();
  19253. }
  19254. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19255. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19256. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19257. this._isOcclusionQueryInProgress = true;
  19258. };
  19259. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19260. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19261. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19262. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19263. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19264. return AbstractMesh;
  19265. }(BABYLON.TransformNode));
  19266. BABYLON.AbstractMesh = AbstractMesh;
  19267. })(BABYLON || (BABYLON = {}));
  19268. //# sourceMappingURL=babylon.abstractMesh.js.map
  19269. var BABYLON;
  19270. (function (BABYLON) {
  19271. /**
  19272. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19273. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19274. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  19275. */
  19276. var Light = /** @class */ (function (_super) {
  19277. __extends(Light, _super);
  19278. /**
  19279. * Creates a Light object in the scene.
  19280. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19281. * @param name The firendly name of the light
  19282. * @param scene The scene the light belongs too
  19283. */
  19284. function Light(name, scene) {
  19285. var _this = _super.call(this, name, scene) || this;
  19286. /**
  19287. * Diffuse gives the basic color to an object.
  19288. */
  19289. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19290. /**
  19291. * Specular produces a highlight color on an object.
  19292. * Note: This is note affecting PBR materials.
  19293. */
  19294. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19295. /**
  19296. * Strength of the light.
  19297. * Note: By default it is define in the framework own unit.
  19298. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19299. */
  19300. _this.intensity = 1.0;
  19301. /**
  19302. * Defines how far from the source the light is impacting in scene units.
  19303. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19304. */
  19305. _this.range = Number.MAX_VALUE;
  19306. /**
  19307. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19308. * of light.
  19309. */
  19310. _this._photometricScale = 1.0;
  19311. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19312. _this._radius = 0.00001;
  19313. /**
  19314. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19315. * exceeding the number allowed of the materials.
  19316. */
  19317. _this.renderPriority = 0;
  19318. /**
  19319. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19320. * the current shadow generator.
  19321. */
  19322. _this.shadowEnabled = true;
  19323. _this._excludeWithLayerMask = 0;
  19324. _this._includeOnlyWithLayerMask = 0;
  19325. _this._lightmapMode = 0;
  19326. /**
  19327. * @ignore Internal use only.
  19328. */
  19329. _this._excludedMeshesIds = new Array();
  19330. /**
  19331. * @ignore Internal use only.
  19332. */
  19333. _this._includedOnlyMeshesIds = new Array();
  19334. _this.getScene().addLight(_this);
  19335. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19336. _this._buildUniformLayout();
  19337. _this.includedOnlyMeshes = new Array();
  19338. _this.excludedMeshes = new Array();
  19339. _this._resyncMeshes();
  19340. return _this;
  19341. }
  19342. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19343. /**
  19344. * If every light affecting the material is in this lightmapMode,
  19345. * material.lightmapTexture adds or multiplies
  19346. * (depends on material.useLightmapAsShadowmap)
  19347. * after every other light calculations.
  19348. */
  19349. get: function () {
  19350. return Light._LIGHTMAP_DEFAULT;
  19351. },
  19352. enumerable: true,
  19353. configurable: true
  19354. });
  19355. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19356. /**
  19357. * material.lightmapTexture as only diffuse lighting from this light
  19358. * adds only specular lighting from this light
  19359. * adds dynamic shadows
  19360. */
  19361. get: function () {
  19362. return Light._LIGHTMAP_SPECULAR;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19368. /**
  19369. * material.lightmapTexture as only lighting
  19370. * no light calculation from this light
  19371. * only adds dynamic shadows from this light
  19372. */
  19373. get: function () {
  19374. return Light._LIGHTMAP_SHADOWSONLY;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19380. /**
  19381. * Each light type uses the default quantity according to its type:
  19382. * point/spot lights use luminous intensity
  19383. * directional lights use illuminance
  19384. */
  19385. get: function () {
  19386. return Light._INTENSITYMODE_AUTOMATIC;
  19387. },
  19388. enumerable: true,
  19389. configurable: true
  19390. });
  19391. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19392. /**
  19393. * lumen (lm)
  19394. */
  19395. get: function () {
  19396. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19397. },
  19398. enumerable: true,
  19399. configurable: true
  19400. });
  19401. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19402. /**
  19403. * candela (lm/sr)
  19404. */
  19405. get: function () {
  19406. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19412. /**
  19413. * lux (lm/m^2)
  19414. */
  19415. get: function () {
  19416. return Light._INTENSITYMODE_ILLUMINANCE;
  19417. },
  19418. enumerable: true,
  19419. configurable: true
  19420. });
  19421. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19422. /**
  19423. * nit (cd/m^2)
  19424. */
  19425. get: function () {
  19426. return Light._INTENSITYMODE_LUMINANCE;
  19427. },
  19428. enumerable: true,
  19429. configurable: true
  19430. });
  19431. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19432. /**
  19433. * Light type const id of the point light.
  19434. */
  19435. get: function () {
  19436. return Light._LIGHTTYPEID_POINTLIGHT;
  19437. },
  19438. enumerable: true,
  19439. configurable: true
  19440. });
  19441. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19442. /**
  19443. * Light type const id of the directional light.
  19444. */
  19445. get: function () {
  19446. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19447. },
  19448. enumerable: true,
  19449. configurable: true
  19450. });
  19451. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19452. /**
  19453. * Light type const id of the spot light.
  19454. */
  19455. get: function () {
  19456. return Light._LIGHTTYPEID_SPOTLIGHT;
  19457. },
  19458. enumerable: true,
  19459. configurable: true
  19460. });
  19461. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19462. /**
  19463. * Light type const id of the hemispheric light.
  19464. */
  19465. get: function () {
  19466. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19467. },
  19468. enumerable: true,
  19469. configurable: true
  19470. });
  19471. Object.defineProperty(Light.prototype, "intensityMode", {
  19472. /**
  19473. * Gets the photometric scale used to interpret the intensity.
  19474. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19475. */
  19476. get: function () {
  19477. return this._intensityMode;
  19478. },
  19479. /**
  19480. * Sets the photometric scale used to interpret the intensity.
  19481. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19482. */
  19483. set: function (value) {
  19484. this._intensityMode = value;
  19485. this._computePhotometricScale();
  19486. },
  19487. enumerable: true,
  19488. configurable: true
  19489. });
  19490. ;
  19491. ;
  19492. Object.defineProperty(Light.prototype, "radius", {
  19493. /**
  19494. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19495. */
  19496. get: function () {
  19497. return this._radius;
  19498. },
  19499. /**
  19500. * sets the light radius used by PBR Materials to simulate soft area lights.
  19501. */
  19502. set: function (value) {
  19503. this._radius = value;
  19504. this._computePhotometricScale();
  19505. },
  19506. enumerable: true,
  19507. configurable: true
  19508. });
  19509. ;
  19510. ;
  19511. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19512. /**
  19513. * Gets the only meshes impacted by this light.
  19514. */
  19515. get: function () {
  19516. return this._includedOnlyMeshes;
  19517. },
  19518. /**
  19519. * Sets the only meshes impacted by this light.
  19520. */
  19521. set: function (value) {
  19522. this._includedOnlyMeshes = value;
  19523. this._hookArrayForIncludedOnly(value);
  19524. },
  19525. enumerable: true,
  19526. configurable: true
  19527. });
  19528. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19529. /**
  19530. * Gets the meshes not impacted by this light.
  19531. */
  19532. get: function () {
  19533. return this._excludedMeshes;
  19534. },
  19535. /**
  19536. * Sets the meshes not impacted by this light.
  19537. */
  19538. set: function (value) {
  19539. this._excludedMeshes = value;
  19540. this._hookArrayForExcluded(value);
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19546. /**
  19547. * Gets the layer id use to find what meshes are not impacted by the light.
  19548. * Inactive if 0
  19549. */
  19550. get: function () {
  19551. return this._excludeWithLayerMask;
  19552. },
  19553. /**
  19554. * Sets the layer id use to find what meshes are not impacted by the light.
  19555. * Inactive if 0
  19556. */
  19557. set: function (value) {
  19558. this._excludeWithLayerMask = value;
  19559. this._resyncMeshes();
  19560. },
  19561. enumerable: true,
  19562. configurable: true
  19563. });
  19564. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19565. /**
  19566. * Gets the layer id use to find what meshes are impacted by the light.
  19567. * Inactive if 0
  19568. */
  19569. get: function () {
  19570. return this._includeOnlyWithLayerMask;
  19571. },
  19572. /**
  19573. * Sets the layer id use to find what meshes are impacted by the light.
  19574. * Inactive if 0
  19575. */
  19576. set: function (value) {
  19577. this._includeOnlyWithLayerMask = value;
  19578. this._resyncMeshes();
  19579. },
  19580. enumerable: true,
  19581. configurable: true
  19582. });
  19583. Object.defineProperty(Light.prototype, "lightmapMode", {
  19584. /**
  19585. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19586. */
  19587. get: function () {
  19588. return this._lightmapMode;
  19589. },
  19590. /**
  19591. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19592. */
  19593. set: function (value) {
  19594. if (this._lightmapMode === value) {
  19595. return;
  19596. }
  19597. this._lightmapMode = value;
  19598. this._markMeshesAsLightDirty();
  19599. },
  19600. enumerable: true,
  19601. configurable: true
  19602. });
  19603. /**
  19604. * Returns the string "Light".
  19605. * @returns the class name
  19606. */
  19607. Light.prototype.getClassName = function () {
  19608. return "Light";
  19609. };
  19610. /**
  19611. * Converts the light information to a readable string for debug purpose.
  19612. * @param fullDetails Supports for multiple levels of logging within scene loading
  19613. * @returns the human readable light info
  19614. */
  19615. Light.prototype.toString = function (fullDetails) {
  19616. var ret = "Name: " + this.name;
  19617. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19618. if (this.animations) {
  19619. for (var i = 0; i < this.animations.length; i++) {
  19620. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19621. }
  19622. }
  19623. if (fullDetails) {
  19624. }
  19625. return ret;
  19626. };
  19627. /**
  19628. * Set the enabled state of this node.
  19629. * @param value - the new enabled state
  19630. * @see isEnabled
  19631. */
  19632. Light.prototype.setEnabled = function (value) {
  19633. _super.prototype.setEnabled.call(this, value);
  19634. this._resyncMeshes();
  19635. };
  19636. /**
  19637. * Returns the Light associated shadow generator if any.
  19638. * @return the associated shadow generator.
  19639. */
  19640. Light.prototype.getShadowGenerator = function () {
  19641. return this._shadowGenerator;
  19642. };
  19643. /**
  19644. * Returns a Vector3, the absolute light position in the World.
  19645. * @returns the world space position of the light
  19646. */
  19647. Light.prototype.getAbsolutePosition = function () {
  19648. return BABYLON.Vector3.Zero();
  19649. };
  19650. /**
  19651. * Specifies if the light will affect the passed mesh.
  19652. * @param mesh The mesh to test against the light
  19653. * @return true the mesh is affected otherwise, false.
  19654. */
  19655. Light.prototype.canAffectMesh = function (mesh) {
  19656. if (!mesh) {
  19657. return true;
  19658. }
  19659. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19660. return false;
  19661. }
  19662. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19663. return false;
  19664. }
  19665. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19666. return false;
  19667. }
  19668. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19669. return false;
  19670. }
  19671. return true;
  19672. };
  19673. /**
  19674. * Computes and Returns the light World matrix.
  19675. * @returns the world matrix
  19676. */
  19677. Light.prototype.getWorldMatrix = function () {
  19678. this._currentRenderId = this.getScene().getRenderId();
  19679. var worldMatrix = this._getWorldMatrix();
  19680. if (this.parent && this.parent.getWorldMatrix) {
  19681. if (!this._parentedWorldMatrix) {
  19682. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19683. }
  19684. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19685. this._markSyncedWithParent();
  19686. return this._parentedWorldMatrix;
  19687. }
  19688. return worldMatrix;
  19689. };
  19690. /**
  19691. * Sort function to order lights for rendering.
  19692. * @param a First Light object to compare to second.
  19693. * @param b Second Light object to compare first.
  19694. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19695. */
  19696. Light.CompareLightsPriority = function (a, b) {
  19697. //shadow-casting lights have priority over non-shadow-casting lights
  19698. //the renderPrioirty is a secondary sort criterion
  19699. if (a.shadowEnabled !== b.shadowEnabled) {
  19700. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19701. }
  19702. return b.renderPriority - a.renderPriority;
  19703. };
  19704. /**
  19705. * Releases resources associated with this node.
  19706. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19707. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19708. */
  19709. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19710. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19711. if (this._shadowGenerator) {
  19712. this._shadowGenerator.dispose();
  19713. this._shadowGenerator = null;
  19714. }
  19715. // Animations
  19716. this.getScene().stopAnimation(this);
  19717. // Remove from meshes
  19718. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19719. var mesh = _a[_i];
  19720. mesh._removeLightSource(this);
  19721. }
  19722. this._uniformBuffer.dispose();
  19723. // Remove from scene
  19724. this.getScene().removeLight(this);
  19725. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19726. };
  19727. /**
  19728. * Returns the light type ID (integer).
  19729. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19730. */
  19731. Light.prototype.getTypeID = function () {
  19732. return 0;
  19733. };
  19734. /**
  19735. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19736. * @returns the scaled intensity in intensity mode unit
  19737. */
  19738. Light.prototype.getScaledIntensity = function () {
  19739. return this._photometricScale * this.intensity;
  19740. };
  19741. /**
  19742. * Returns a new Light object, named "name", from the current one.
  19743. * @param name The name of the cloned light
  19744. * @returns the new created light
  19745. */
  19746. Light.prototype.clone = function (name) {
  19747. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19748. if (!constructor) {
  19749. return null;
  19750. }
  19751. return BABYLON.SerializationHelper.Clone(constructor, this);
  19752. };
  19753. /**
  19754. * Serializes the current light into a Serialization object.
  19755. * @returns the serialized object.
  19756. */
  19757. Light.prototype.serialize = function () {
  19758. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19759. // Type
  19760. serializationObject.type = this.getTypeID();
  19761. // Parent
  19762. if (this.parent) {
  19763. serializationObject.parentId = this.parent.id;
  19764. }
  19765. // Inclusion / exclusions
  19766. if (this.excludedMeshes.length > 0) {
  19767. serializationObject.excludedMeshesIds = [];
  19768. this.excludedMeshes.forEach(function (mesh) {
  19769. serializationObject.excludedMeshesIds.push(mesh.id);
  19770. });
  19771. }
  19772. if (this.includedOnlyMeshes.length > 0) {
  19773. serializationObject.includedOnlyMeshesIds = [];
  19774. this.includedOnlyMeshes.forEach(function (mesh) {
  19775. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19776. });
  19777. }
  19778. // Animations
  19779. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19780. serializationObject.ranges = this.serializeAnimationRanges();
  19781. return serializationObject;
  19782. };
  19783. /**
  19784. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19785. * This new light is named "name" and added to the passed scene.
  19786. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19787. * @param name The friendly name of the light
  19788. * @param scene The scene the new light will belong to
  19789. * @returns the constructor function
  19790. */
  19791. Light.GetConstructorFromName = function (type, name, scene) {
  19792. switch (type) {
  19793. case 0:
  19794. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19795. case 1:
  19796. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19797. case 2:
  19798. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19799. case 3:
  19800. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19801. }
  19802. return null;
  19803. };
  19804. /**
  19805. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19806. * @param parsedLight The JSON representation of the light
  19807. * @param scene The scene to create the parsed light in
  19808. * @returns the created light after parsing
  19809. */
  19810. Light.Parse = function (parsedLight, scene) {
  19811. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19812. if (!constructor) {
  19813. return null;
  19814. }
  19815. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19816. // Inclusion / exclusions
  19817. if (parsedLight.excludedMeshesIds) {
  19818. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19819. }
  19820. if (parsedLight.includedOnlyMeshesIds) {
  19821. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19822. }
  19823. // Parent
  19824. if (parsedLight.parentId) {
  19825. light._waitingParentId = parsedLight.parentId;
  19826. }
  19827. // Animations
  19828. if (parsedLight.animations) {
  19829. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19830. var parsedAnimation = parsedLight.animations[animationIndex];
  19831. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19832. }
  19833. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19834. }
  19835. if (parsedLight.autoAnimate) {
  19836. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19837. }
  19838. return light;
  19839. };
  19840. Light.prototype._hookArrayForExcluded = function (array) {
  19841. var _this = this;
  19842. var oldPush = array.push;
  19843. array.push = function () {
  19844. var items = [];
  19845. for (var _i = 0; _i < arguments.length; _i++) {
  19846. items[_i] = arguments[_i];
  19847. }
  19848. var result = oldPush.apply(array, items);
  19849. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19850. var item = items_1[_a];
  19851. item._resyncLighSource(_this);
  19852. }
  19853. return result;
  19854. };
  19855. var oldSplice = array.splice;
  19856. array.splice = function (index, deleteCount) {
  19857. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19858. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19859. var item = deleted_1[_i];
  19860. item._resyncLighSource(_this);
  19861. }
  19862. return deleted;
  19863. };
  19864. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19865. var item = array_1[_i];
  19866. item._resyncLighSource(this);
  19867. }
  19868. };
  19869. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19870. var _this = this;
  19871. var oldPush = array.push;
  19872. array.push = function () {
  19873. var items = [];
  19874. for (var _i = 0; _i < arguments.length; _i++) {
  19875. items[_i] = arguments[_i];
  19876. }
  19877. var result = oldPush.apply(array, items);
  19878. _this._resyncMeshes();
  19879. return result;
  19880. };
  19881. var oldSplice = array.splice;
  19882. array.splice = function (index, deleteCount) {
  19883. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19884. _this._resyncMeshes();
  19885. return deleted;
  19886. };
  19887. this._resyncMeshes();
  19888. };
  19889. Light.prototype._resyncMeshes = function () {
  19890. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19891. var mesh = _a[_i];
  19892. mesh._resyncLighSource(this);
  19893. }
  19894. };
  19895. /**
  19896. * Forces the meshes to update their light related information in their rendering used effects
  19897. * @ignore Internal Use Only
  19898. */
  19899. Light.prototype._markMeshesAsLightDirty = function () {
  19900. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19901. var mesh = _a[_i];
  19902. if (mesh._lightSources.indexOf(this) !== -1) {
  19903. mesh._markSubMeshesAsLightDirty();
  19904. }
  19905. }
  19906. };
  19907. /**
  19908. * Recomputes the cached photometric scale if needed.
  19909. */
  19910. Light.prototype._computePhotometricScale = function () {
  19911. this._photometricScale = this._getPhotometricScale();
  19912. this.getScene().resetCachedMaterial();
  19913. };
  19914. /**
  19915. * Returns the Photometric Scale according to the light type and intensity mode.
  19916. */
  19917. Light.prototype._getPhotometricScale = function () {
  19918. var photometricScale = 0.0;
  19919. var lightTypeID = this.getTypeID();
  19920. //get photometric mode
  19921. var photometricMode = this.intensityMode;
  19922. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19923. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19924. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19925. }
  19926. else {
  19927. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19928. }
  19929. }
  19930. //compute photometric scale
  19931. switch (lightTypeID) {
  19932. case Light.LIGHTTYPEID_POINTLIGHT:
  19933. case Light.LIGHTTYPEID_SPOTLIGHT:
  19934. switch (photometricMode) {
  19935. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19936. photometricScale = 1.0 / (4.0 * Math.PI);
  19937. break;
  19938. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19939. photometricScale = 1.0;
  19940. break;
  19941. case Light.INTENSITYMODE_LUMINANCE:
  19942. photometricScale = this.radius * this.radius;
  19943. break;
  19944. }
  19945. break;
  19946. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19947. switch (photometricMode) {
  19948. case Light.INTENSITYMODE_ILLUMINANCE:
  19949. photometricScale = 1.0;
  19950. break;
  19951. case Light.INTENSITYMODE_LUMINANCE:
  19952. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19953. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19954. var apexAngleRadians = this.radius;
  19955. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19956. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19957. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19958. photometricScale = solidAngle;
  19959. break;
  19960. }
  19961. break;
  19962. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19963. // No fall off in hemisperic light.
  19964. photometricScale = 1.0;
  19965. break;
  19966. }
  19967. return photometricScale;
  19968. };
  19969. /**
  19970. * Reorder the light in the scene according to their defined priority.
  19971. * @ignore Internal Use Only
  19972. */
  19973. Light.prototype._reorderLightsInScene = function () {
  19974. var scene = this.getScene();
  19975. if (this._renderPriority != 0) {
  19976. scene.requireLightSorting = true;
  19977. }
  19978. this.getScene().sortLightsByPriority();
  19979. };
  19980. //lightmapMode Consts
  19981. Light._LIGHTMAP_DEFAULT = 0;
  19982. Light._LIGHTMAP_SPECULAR = 1;
  19983. Light._LIGHTMAP_SHADOWSONLY = 2;
  19984. // Intensity Mode Consts
  19985. Light._INTENSITYMODE_AUTOMATIC = 0;
  19986. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19987. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19988. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19989. Light._INTENSITYMODE_LUMINANCE = 4;
  19990. // Light types ids const.
  19991. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19992. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19993. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19994. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19995. __decorate([
  19996. BABYLON.serializeAsColor3()
  19997. ], Light.prototype, "diffuse", void 0);
  19998. __decorate([
  19999. BABYLON.serializeAsColor3()
  20000. ], Light.prototype, "specular", void 0);
  20001. __decorate([
  20002. BABYLON.serialize()
  20003. ], Light.prototype, "intensity", void 0);
  20004. __decorate([
  20005. BABYLON.serialize()
  20006. ], Light.prototype, "range", void 0);
  20007. __decorate([
  20008. BABYLON.serialize()
  20009. ], Light.prototype, "intensityMode", null);
  20010. __decorate([
  20011. BABYLON.serialize()
  20012. ], Light.prototype, "radius", null);
  20013. __decorate([
  20014. BABYLON.serialize()
  20015. ], Light.prototype, "_renderPriority", void 0);
  20016. __decorate([
  20017. BABYLON.expandToProperty("_reorderLightsInScene")
  20018. ], Light.prototype, "renderPriority", void 0);
  20019. __decorate([
  20020. BABYLON.serialize()
  20021. ], Light.prototype, "shadowEnabled", void 0);
  20022. __decorate([
  20023. BABYLON.serialize("excludeWithLayerMask")
  20024. ], Light.prototype, "_excludeWithLayerMask", void 0);
  20025. __decorate([
  20026. BABYLON.serialize("includeOnlyWithLayerMask")
  20027. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  20028. __decorate([
  20029. BABYLON.serialize("lightmapMode")
  20030. ], Light.prototype, "_lightmapMode", void 0);
  20031. return Light;
  20032. }(BABYLON.Node));
  20033. BABYLON.Light = Light;
  20034. })(BABYLON || (BABYLON = {}));
  20035. //# sourceMappingURL=babylon.light.js.map
  20036. var BABYLON;
  20037. (function (BABYLON) {
  20038. var Camera = /** @class */ (function (_super) {
  20039. __extends(Camera, _super);
  20040. function Camera(name, position, scene) {
  20041. var _this = _super.call(this, name, scene) || this;
  20042. /**
  20043. * The vector the camera should consider as up.
  20044. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20045. */
  20046. _this.upVector = BABYLON.Vector3.Up();
  20047. _this.orthoLeft = null;
  20048. _this.orthoRight = null;
  20049. _this.orthoBottom = null;
  20050. _this.orthoTop = null;
  20051. /**
  20052. * FOV is set in Radians. (default is 0.8)
  20053. */
  20054. _this.fov = 0.8;
  20055. _this.minZ = 1;
  20056. _this.maxZ = 10000.0;
  20057. _this.inertia = 0.9;
  20058. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20059. _this.isIntermediate = false;
  20060. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20061. /**
  20062. * Restricts the camera to viewing objects with the same layerMask.
  20063. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20064. */
  20065. _this.layerMask = 0x0FFFFFFF;
  20066. /**
  20067. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20068. */
  20069. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20070. // Camera rig members
  20071. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20072. _this._rigCameras = new Array();
  20073. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20074. _this._skipRendering = false;
  20075. _this.customRenderTargets = new Array();
  20076. // Observables
  20077. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20078. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20079. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20080. _this.onRestoreStateObservable = new BABYLON.Observable();
  20081. // Cache
  20082. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20083. _this._projectionMatrix = new BABYLON.Matrix();
  20084. _this._doNotComputeProjectionMatrix = false;
  20085. _this._postProcesses = new Array();
  20086. _this._transformMatrix = BABYLON.Matrix.Zero();
  20087. _this._activeMeshes = new BABYLON.SmartArray(256);
  20088. _this._globalPosition = BABYLON.Vector3.Zero();
  20089. _this._refreshFrustumPlanes = true;
  20090. _this.getScene().addCamera(_this);
  20091. if (!_this.getScene().activeCamera) {
  20092. _this.getScene().activeCamera = _this;
  20093. }
  20094. _this.position = position;
  20095. return _this;
  20096. }
  20097. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20098. get: function () {
  20099. return Camera._PERSPECTIVE_CAMERA;
  20100. },
  20101. enumerable: true,
  20102. configurable: true
  20103. });
  20104. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20105. get: function () {
  20106. return Camera._ORTHOGRAPHIC_CAMERA;
  20107. },
  20108. enumerable: true,
  20109. configurable: true
  20110. });
  20111. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20112. /**
  20113. * This is the default FOV mode for perspective cameras.
  20114. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20115. *
  20116. */
  20117. get: function () {
  20118. return Camera._FOVMODE_VERTICAL_FIXED;
  20119. },
  20120. enumerable: true,
  20121. configurable: true
  20122. });
  20123. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20124. /**
  20125. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20126. *
  20127. */
  20128. get: function () {
  20129. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20130. },
  20131. enumerable: true,
  20132. configurable: true
  20133. });
  20134. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20135. get: function () {
  20136. return Camera._RIG_MODE_NONE;
  20137. },
  20138. enumerable: true,
  20139. configurable: true
  20140. });
  20141. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20142. get: function () {
  20143. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20144. },
  20145. enumerable: true,
  20146. configurable: true
  20147. });
  20148. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20149. get: function () {
  20150. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20156. get: function () {
  20157. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20158. },
  20159. enumerable: true,
  20160. configurable: true
  20161. });
  20162. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20163. get: function () {
  20164. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20165. },
  20166. enumerable: true,
  20167. configurable: true
  20168. });
  20169. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20170. get: function () {
  20171. return Camera._RIG_MODE_VR;
  20172. },
  20173. enumerable: true,
  20174. configurable: true
  20175. });
  20176. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20177. get: function () {
  20178. return Camera._RIG_MODE_WEBVR;
  20179. },
  20180. enumerable: true,
  20181. configurable: true
  20182. });
  20183. /**
  20184. * Store current camera state (fov, position, etc..)
  20185. */
  20186. Camera.prototype.storeState = function () {
  20187. this._stateStored = true;
  20188. this._storedFov = this.fov;
  20189. return this;
  20190. };
  20191. /**
  20192. * Restores the camera state values if it has been stored. You must call storeState() first
  20193. */
  20194. Camera.prototype._restoreStateValues = function () {
  20195. if (!this._stateStored) {
  20196. return false;
  20197. }
  20198. this.fov = this._storedFov;
  20199. return true;
  20200. };
  20201. /**
  20202. * Restored camera state. You must call storeState() first
  20203. */
  20204. Camera.prototype.restoreState = function () {
  20205. if (this._restoreStateValues()) {
  20206. this.onRestoreStateObservable.notifyObservers(this);
  20207. return true;
  20208. }
  20209. return false;
  20210. };
  20211. Camera.prototype.getClassName = function () {
  20212. return "Camera";
  20213. };
  20214. /**
  20215. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20216. */
  20217. Camera.prototype.toString = function (fullDetails) {
  20218. var ret = "Name: " + this.name;
  20219. ret += ", type: " + this.getClassName();
  20220. if (this.animations) {
  20221. for (var i = 0; i < this.animations.length; i++) {
  20222. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20223. }
  20224. }
  20225. if (fullDetails) {
  20226. }
  20227. return ret;
  20228. };
  20229. Object.defineProperty(Camera.prototype, "globalPosition", {
  20230. get: function () {
  20231. return this._globalPosition;
  20232. },
  20233. enumerable: true,
  20234. configurable: true
  20235. });
  20236. Camera.prototype.getActiveMeshes = function () {
  20237. return this._activeMeshes;
  20238. };
  20239. Camera.prototype.isActiveMesh = function (mesh) {
  20240. return (this._activeMeshes.indexOf(mesh) !== -1);
  20241. };
  20242. //Cache
  20243. Camera.prototype._initCache = function () {
  20244. _super.prototype._initCache.call(this);
  20245. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20246. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20247. this._cache.mode = undefined;
  20248. this._cache.minZ = undefined;
  20249. this._cache.maxZ = undefined;
  20250. this._cache.fov = undefined;
  20251. this._cache.fovMode = undefined;
  20252. this._cache.aspectRatio = undefined;
  20253. this._cache.orthoLeft = undefined;
  20254. this._cache.orthoRight = undefined;
  20255. this._cache.orthoBottom = undefined;
  20256. this._cache.orthoTop = undefined;
  20257. this._cache.renderWidth = undefined;
  20258. this._cache.renderHeight = undefined;
  20259. };
  20260. Camera.prototype._updateCache = function (ignoreParentClass) {
  20261. if (!ignoreParentClass) {
  20262. _super.prototype._updateCache.call(this);
  20263. }
  20264. this._cache.position.copyFrom(this.position);
  20265. this._cache.upVector.copyFrom(this.upVector);
  20266. };
  20267. // Synchronized
  20268. Camera.prototype._isSynchronized = function () {
  20269. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20270. };
  20271. Camera.prototype._isSynchronizedViewMatrix = function () {
  20272. if (!_super.prototype._isSynchronized.call(this))
  20273. return false;
  20274. return this._cache.position.equals(this.position)
  20275. && this._cache.upVector.equals(this.upVector)
  20276. && this.isSynchronizedWithParent();
  20277. };
  20278. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20279. var check = this._cache.mode === this.mode
  20280. && this._cache.minZ === this.minZ
  20281. && this._cache.maxZ === this.maxZ;
  20282. if (!check) {
  20283. return false;
  20284. }
  20285. var engine = this.getEngine();
  20286. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20287. check = this._cache.fov === this.fov
  20288. && this._cache.fovMode === this.fovMode
  20289. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20290. }
  20291. else {
  20292. check = this._cache.orthoLeft === this.orthoLeft
  20293. && this._cache.orthoRight === this.orthoRight
  20294. && this._cache.orthoBottom === this.orthoBottom
  20295. && this._cache.orthoTop === this.orthoTop
  20296. && this._cache.renderWidth === engine.getRenderWidth()
  20297. && this._cache.renderHeight === engine.getRenderHeight();
  20298. }
  20299. return check;
  20300. };
  20301. // Controls
  20302. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20303. };
  20304. Camera.prototype.detachControl = function (element) {
  20305. };
  20306. Camera.prototype.update = function () {
  20307. this._checkInputs();
  20308. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20309. this._updateRigCameras();
  20310. }
  20311. };
  20312. Camera.prototype._checkInputs = function () {
  20313. this.onAfterCheckInputsObservable.notifyObservers(this);
  20314. };
  20315. Object.defineProperty(Camera.prototype, "rigCameras", {
  20316. get: function () {
  20317. return this._rigCameras;
  20318. },
  20319. enumerable: true,
  20320. configurable: true
  20321. });
  20322. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20323. get: function () {
  20324. return this._rigPostProcess;
  20325. },
  20326. enumerable: true,
  20327. configurable: true
  20328. });
  20329. /**
  20330. * Internal, gets the first post proces.
  20331. * @returns the first post process to be run on this camera.
  20332. */
  20333. Camera.prototype._getFirstPostProcess = function () {
  20334. for (var pp in this._postProcesses) {
  20335. if (this._postProcesses[pp] !== null) {
  20336. return this._postProcesses[pp];
  20337. }
  20338. }
  20339. return null;
  20340. };
  20341. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20342. // invalidate framebuffer
  20343. var firstPostProcess = this._getFirstPostProcess();
  20344. if (firstPostProcess) {
  20345. firstPostProcess.markTextureDirty();
  20346. }
  20347. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20348. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20349. var cam = this._rigCameras[i];
  20350. var rigPostProcess = cam._rigPostProcess;
  20351. // for VR rig, there does not have to be a post process
  20352. if (rigPostProcess) {
  20353. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20354. if (isPass) {
  20355. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20356. cam.isIntermediate = this._postProcesses.length === 0;
  20357. }
  20358. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20359. rigPostProcess.markTextureDirty();
  20360. }
  20361. else {
  20362. cam._postProcesses = this._postProcesses.slice(0);
  20363. }
  20364. }
  20365. };
  20366. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20367. if (insertAt === void 0) { insertAt = null; }
  20368. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20369. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20370. return 0;
  20371. }
  20372. if (insertAt == null || insertAt < 0) {
  20373. this._postProcesses.push(postProcess);
  20374. }
  20375. else if (this._postProcesses[insertAt] === null) {
  20376. this._postProcesses[insertAt] = postProcess;
  20377. }
  20378. else {
  20379. this._postProcesses.splice(insertAt, 0, postProcess);
  20380. }
  20381. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20382. return this._postProcesses.indexOf(postProcess);
  20383. };
  20384. Camera.prototype.detachPostProcess = function (postProcess) {
  20385. var idx = this._postProcesses.indexOf(postProcess);
  20386. if (idx !== -1) {
  20387. this._postProcesses[idx] = null;
  20388. }
  20389. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20390. };
  20391. Camera.prototype.getWorldMatrix = function () {
  20392. if (!this._worldMatrix) {
  20393. this._worldMatrix = BABYLON.Matrix.Identity();
  20394. }
  20395. var viewMatrix = this.getViewMatrix();
  20396. viewMatrix.invertToRef(this._worldMatrix);
  20397. return this._worldMatrix;
  20398. };
  20399. Camera.prototype._getViewMatrix = function () {
  20400. return BABYLON.Matrix.Identity();
  20401. };
  20402. Camera.prototype.getViewMatrix = function (force) {
  20403. if (!force && this._isSynchronizedViewMatrix()) {
  20404. return this._computedViewMatrix;
  20405. }
  20406. this.updateCache();
  20407. this._computedViewMatrix = this._getViewMatrix();
  20408. this._currentRenderId = this.getScene().getRenderId();
  20409. this._refreshFrustumPlanes = true;
  20410. if (!this.parent || !this.parent.getWorldMatrix) {
  20411. this._globalPosition.copyFrom(this.position);
  20412. }
  20413. else {
  20414. if (!this._worldMatrix) {
  20415. this._worldMatrix = BABYLON.Matrix.Identity();
  20416. }
  20417. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20418. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20419. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20420. this._computedViewMatrix.invert();
  20421. this._markSyncedWithParent();
  20422. }
  20423. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20424. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20425. }
  20426. this.onViewMatrixChangedObservable.notifyObservers(this);
  20427. return this._computedViewMatrix;
  20428. };
  20429. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20430. this._doNotComputeProjectionMatrix = true;
  20431. if (projection !== undefined) {
  20432. this._projectionMatrix = projection;
  20433. }
  20434. };
  20435. ;
  20436. Camera.prototype.unfreezeProjectionMatrix = function () {
  20437. this._doNotComputeProjectionMatrix = false;
  20438. };
  20439. ;
  20440. Camera.prototype.getProjectionMatrix = function (force) {
  20441. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20442. return this._projectionMatrix;
  20443. }
  20444. // Cache
  20445. this._cache.mode = this.mode;
  20446. this._cache.minZ = this.minZ;
  20447. this._cache.maxZ = this.maxZ;
  20448. // Matrix
  20449. this._refreshFrustumPlanes = true;
  20450. var engine = this.getEngine();
  20451. var scene = this.getScene();
  20452. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20453. this._cache.fov = this.fov;
  20454. this._cache.fovMode = this.fovMode;
  20455. this._cache.aspectRatio = engine.getAspectRatio(this);
  20456. if (this.minZ <= 0) {
  20457. this.minZ = 0.1;
  20458. }
  20459. if (scene.useRightHandedSystem) {
  20460. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20461. }
  20462. else {
  20463. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20464. }
  20465. }
  20466. else {
  20467. var halfWidth = engine.getRenderWidth() / 2.0;
  20468. var halfHeight = engine.getRenderHeight() / 2.0;
  20469. if (scene.useRightHandedSystem) {
  20470. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20471. }
  20472. else {
  20473. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20474. }
  20475. this._cache.orthoLeft = this.orthoLeft;
  20476. this._cache.orthoRight = this.orthoRight;
  20477. this._cache.orthoBottom = this.orthoBottom;
  20478. this._cache.orthoTop = this.orthoTop;
  20479. this._cache.renderWidth = engine.getRenderWidth();
  20480. this._cache.renderHeight = engine.getRenderHeight();
  20481. }
  20482. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20483. return this._projectionMatrix;
  20484. };
  20485. Camera.prototype.getTranformationMatrix = function () {
  20486. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20487. return this._transformMatrix;
  20488. };
  20489. Camera.prototype.updateFrustumPlanes = function () {
  20490. if (!this._refreshFrustumPlanes) {
  20491. return;
  20492. }
  20493. this.getTranformationMatrix();
  20494. if (!this._frustumPlanes) {
  20495. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20496. }
  20497. else {
  20498. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20499. }
  20500. this._refreshFrustumPlanes = false;
  20501. };
  20502. Camera.prototype.isInFrustum = function (target) {
  20503. this.updateFrustumPlanes();
  20504. return target.isInFrustum(this._frustumPlanes);
  20505. };
  20506. Camera.prototype.isCompletelyInFrustum = function (target) {
  20507. this.updateFrustumPlanes();
  20508. return target.isCompletelyInFrustum(this._frustumPlanes);
  20509. };
  20510. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20511. if (length === void 0) { length = 100; }
  20512. if (!transform) {
  20513. transform = this.getWorldMatrix();
  20514. }
  20515. if (!origin) {
  20516. origin = this.position;
  20517. }
  20518. var forward = new BABYLON.Vector3(0, 0, 1);
  20519. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20520. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20521. return new BABYLON.Ray(origin, direction, length);
  20522. };
  20523. /**
  20524. * Releases resources associated with this node.
  20525. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20526. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20527. */
  20528. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20529. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20530. // Observables
  20531. this.onViewMatrixChangedObservable.clear();
  20532. this.onProjectionMatrixChangedObservable.clear();
  20533. this.onAfterCheckInputsObservable.clear();
  20534. this.onRestoreStateObservable.clear();
  20535. // Inputs
  20536. if (this.inputs) {
  20537. this.inputs.clear();
  20538. }
  20539. // Animations
  20540. this.getScene().stopAnimation(this);
  20541. // Remove from scene
  20542. this.getScene().removeCamera(this);
  20543. while (this._rigCameras.length > 0) {
  20544. var camera = this._rigCameras.pop();
  20545. if (camera) {
  20546. camera.dispose();
  20547. }
  20548. }
  20549. // Postprocesses
  20550. if (this._rigPostProcess) {
  20551. this._rigPostProcess.dispose(this);
  20552. this._rigPostProcess = null;
  20553. this._postProcesses = [];
  20554. }
  20555. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20556. this._rigPostProcess = null;
  20557. this._postProcesses = [];
  20558. }
  20559. else {
  20560. var i = this._postProcesses.length;
  20561. while (--i >= 0) {
  20562. var postProcess = this._postProcesses[i];
  20563. if (postProcess) {
  20564. postProcess.dispose(this);
  20565. }
  20566. }
  20567. }
  20568. // Render targets
  20569. var i = this.customRenderTargets.length;
  20570. while (--i >= 0) {
  20571. this.customRenderTargets[i].dispose();
  20572. }
  20573. this.customRenderTargets = [];
  20574. // Active Meshes
  20575. this._activeMeshes.dispose();
  20576. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20577. };
  20578. Object.defineProperty(Camera.prototype, "leftCamera", {
  20579. // ---- Camera rigs section ----
  20580. get: function () {
  20581. if (this._rigCameras.length < 1) {
  20582. return null;
  20583. }
  20584. return this._rigCameras[0];
  20585. },
  20586. enumerable: true,
  20587. configurable: true
  20588. });
  20589. Object.defineProperty(Camera.prototype, "rightCamera", {
  20590. get: function () {
  20591. if (this._rigCameras.length < 2) {
  20592. return null;
  20593. }
  20594. return this._rigCameras[1];
  20595. },
  20596. enumerable: true,
  20597. configurable: true
  20598. });
  20599. Camera.prototype.getLeftTarget = function () {
  20600. if (this._rigCameras.length < 1) {
  20601. return null;
  20602. }
  20603. return this._rigCameras[0].getTarget();
  20604. };
  20605. Camera.prototype.getRightTarget = function () {
  20606. if (this._rigCameras.length < 2) {
  20607. return null;
  20608. }
  20609. return this._rigCameras[1].getTarget();
  20610. };
  20611. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20612. if (this.cameraRigMode === mode) {
  20613. return;
  20614. }
  20615. while (this._rigCameras.length > 0) {
  20616. var camera = this._rigCameras.pop();
  20617. if (camera) {
  20618. camera.dispose();
  20619. }
  20620. }
  20621. this.cameraRigMode = mode;
  20622. this._cameraRigParams = {};
  20623. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20624. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20625. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20626. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20627. // create the rig cameras, unless none
  20628. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20629. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20630. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20631. if (leftCamera && rightCamera) {
  20632. this._rigCameras.push(leftCamera);
  20633. this._rigCameras.push(rightCamera);
  20634. }
  20635. }
  20636. switch (this.cameraRigMode) {
  20637. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20638. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20639. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20640. break;
  20641. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20642. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20643. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20644. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20645. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20646. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20647. break;
  20648. case Camera.RIG_MODE_VR:
  20649. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20650. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20651. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20652. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20653. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20654. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20655. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20656. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20657. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20658. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20659. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20660. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20661. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20662. if (metrics.compensateDistortion) {
  20663. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20664. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20665. }
  20666. break;
  20667. case Camera.RIG_MODE_WEBVR:
  20668. if (rigParams.vrDisplay) {
  20669. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20670. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20671. //Left eye
  20672. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20673. this._rigCameras[0].setCameraRigParameter("left", true);
  20674. //leaving this for future reference
  20675. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20676. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20677. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20678. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20679. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20680. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20681. this._rigCameras[0].parent = this;
  20682. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20683. //Right eye
  20684. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20685. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20686. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20687. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20688. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20689. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20690. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20691. this._rigCameras[1].parent = this;
  20692. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20693. if (Camera.UseAlternateWebVRRendering) {
  20694. this._rigCameras[1]._skipRendering = true;
  20695. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20696. }
  20697. }
  20698. break;
  20699. }
  20700. this._cascadePostProcessesToRigCams();
  20701. this.update();
  20702. };
  20703. Camera.prototype._getVRProjectionMatrix = function () {
  20704. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20705. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20706. return this._projectionMatrix;
  20707. };
  20708. Camera.prototype._updateCameraRotationMatrix = function () {
  20709. //Here for WebVR
  20710. };
  20711. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20712. //Here for WebVR
  20713. };
  20714. /**
  20715. * This function MUST be overwritten by the different WebVR cameras available.
  20716. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20717. */
  20718. Camera.prototype._getWebVRProjectionMatrix = function () {
  20719. return BABYLON.Matrix.Identity();
  20720. };
  20721. /**
  20722. * This function MUST be overwritten by the different WebVR cameras available.
  20723. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20724. */
  20725. Camera.prototype._getWebVRViewMatrix = function () {
  20726. return BABYLON.Matrix.Identity();
  20727. };
  20728. Camera.prototype.setCameraRigParameter = function (name, value) {
  20729. if (!this._cameraRigParams) {
  20730. this._cameraRigParams = {};
  20731. }
  20732. this._cameraRigParams[name] = value;
  20733. //provisionnally:
  20734. if (name === "interaxialDistance") {
  20735. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20736. }
  20737. };
  20738. /**
  20739. * needs to be overridden by children so sub has required properties to be copied
  20740. */
  20741. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20742. return null;
  20743. };
  20744. /**
  20745. * May need to be overridden by children
  20746. */
  20747. Camera.prototype._updateRigCameras = function () {
  20748. for (var i = 0; i < this._rigCameras.length; i++) {
  20749. this._rigCameras[i].minZ = this.minZ;
  20750. this._rigCameras[i].maxZ = this.maxZ;
  20751. this._rigCameras[i].fov = this.fov;
  20752. }
  20753. // only update viewport when ANAGLYPH
  20754. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20755. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20756. }
  20757. };
  20758. Camera.prototype._setupInputs = function () {
  20759. };
  20760. Camera.prototype.serialize = function () {
  20761. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20762. // Type
  20763. serializationObject.type = this.getClassName();
  20764. // Parent
  20765. if (this.parent) {
  20766. serializationObject.parentId = this.parent.id;
  20767. }
  20768. if (this.inputs) {
  20769. this.inputs.serialize(serializationObject);
  20770. }
  20771. // Animations
  20772. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20773. serializationObject.ranges = this.serializeAnimationRanges();
  20774. return serializationObject;
  20775. };
  20776. Camera.prototype.clone = function (name) {
  20777. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20778. };
  20779. Camera.prototype.getDirection = function (localAxis) {
  20780. var result = BABYLON.Vector3.Zero();
  20781. this.getDirectionToRef(localAxis, result);
  20782. return result;
  20783. };
  20784. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20785. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20786. };
  20787. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20788. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20789. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20790. switch (type) {
  20791. case "ArcRotateCamera":
  20792. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20793. case "DeviceOrientationCamera":
  20794. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20795. case "FollowCamera":
  20796. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20797. case "ArcFollowCamera":
  20798. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20799. case "GamepadCamera":
  20800. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20801. case "TouchCamera":
  20802. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20803. case "VirtualJoysticksCamera":
  20804. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20805. case "WebVRFreeCamera":
  20806. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20807. case "WebVRGamepadCamera":
  20808. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20809. case "VRDeviceOrientationFreeCamera":
  20810. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20811. case "VRDeviceOrientationGamepadCamera":
  20812. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20813. case "AnaglyphArcRotateCamera":
  20814. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20815. case "AnaglyphFreeCamera":
  20816. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20817. case "AnaglyphGamepadCamera":
  20818. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20819. case "AnaglyphUniversalCamera":
  20820. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20821. case "StereoscopicArcRotateCamera":
  20822. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20823. case "StereoscopicFreeCamera":
  20824. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20825. case "StereoscopicGamepadCamera":
  20826. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20827. case "StereoscopicUniversalCamera":
  20828. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20829. case "FreeCamera":// Forcing Universal here
  20830. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20831. default:// Universal Camera is the default value
  20832. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20833. }
  20834. };
  20835. Camera.prototype.computeWorldMatrix = function () {
  20836. return this.getWorldMatrix();
  20837. };
  20838. Camera.Parse = function (parsedCamera, scene) {
  20839. var type = parsedCamera.type;
  20840. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20841. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20842. // Parent
  20843. if (parsedCamera.parentId) {
  20844. camera._waitingParentId = parsedCamera.parentId;
  20845. }
  20846. //If camera has an input manager, let it parse inputs settings
  20847. if (camera.inputs) {
  20848. camera.inputs.parse(parsedCamera);
  20849. camera._setupInputs();
  20850. }
  20851. if (camera.setPosition) {
  20852. camera.position.copyFromFloats(0, 0, 0);
  20853. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20854. }
  20855. // Target
  20856. if (parsedCamera.target) {
  20857. if (camera.setTarget) {
  20858. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20859. }
  20860. }
  20861. // Apply 3d rig, when found
  20862. if (parsedCamera.cameraRigMode) {
  20863. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20864. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20865. }
  20866. // Animations
  20867. if (parsedCamera.animations) {
  20868. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20869. var parsedAnimation = parsedCamera.animations[animationIndex];
  20870. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20871. }
  20872. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20873. }
  20874. if (parsedCamera.autoAnimate) {
  20875. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20876. }
  20877. return camera;
  20878. };
  20879. // Statics
  20880. Camera._PERSPECTIVE_CAMERA = 0;
  20881. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20882. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20883. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20884. Camera._RIG_MODE_NONE = 0;
  20885. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20886. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20887. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20888. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20889. Camera._RIG_MODE_VR = 20;
  20890. Camera._RIG_MODE_WEBVR = 21;
  20891. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20892. Camera.UseAlternateWebVRRendering = false;
  20893. __decorate([
  20894. BABYLON.serializeAsVector3()
  20895. ], Camera.prototype, "position", void 0);
  20896. __decorate([
  20897. BABYLON.serializeAsVector3()
  20898. ], Camera.prototype, "upVector", void 0);
  20899. __decorate([
  20900. BABYLON.serialize()
  20901. ], Camera.prototype, "orthoLeft", void 0);
  20902. __decorate([
  20903. BABYLON.serialize()
  20904. ], Camera.prototype, "orthoRight", void 0);
  20905. __decorate([
  20906. BABYLON.serialize()
  20907. ], Camera.prototype, "orthoBottom", void 0);
  20908. __decorate([
  20909. BABYLON.serialize()
  20910. ], Camera.prototype, "orthoTop", void 0);
  20911. __decorate([
  20912. BABYLON.serialize()
  20913. ], Camera.prototype, "fov", void 0);
  20914. __decorate([
  20915. BABYLON.serialize()
  20916. ], Camera.prototype, "minZ", void 0);
  20917. __decorate([
  20918. BABYLON.serialize()
  20919. ], Camera.prototype, "maxZ", void 0);
  20920. __decorate([
  20921. BABYLON.serialize()
  20922. ], Camera.prototype, "inertia", void 0);
  20923. __decorate([
  20924. BABYLON.serialize()
  20925. ], Camera.prototype, "mode", void 0);
  20926. __decorate([
  20927. BABYLON.serialize()
  20928. ], Camera.prototype, "layerMask", void 0);
  20929. __decorate([
  20930. BABYLON.serialize()
  20931. ], Camera.prototype, "fovMode", void 0);
  20932. __decorate([
  20933. BABYLON.serialize()
  20934. ], Camera.prototype, "cameraRigMode", void 0);
  20935. __decorate([
  20936. BABYLON.serialize()
  20937. ], Camera.prototype, "interaxialDistance", void 0);
  20938. __decorate([
  20939. BABYLON.serialize()
  20940. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20941. return Camera;
  20942. }(BABYLON.Node));
  20943. BABYLON.Camera = Camera;
  20944. })(BABYLON || (BABYLON = {}));
  20945. //# sourceMappingURL=babylon.camera.js.map
  20946. var BABYLON;
  20947. (function (BABYLON) {
  20948. var RenderingManager = /** @class */ (function () {
  20949. function RenderingManager(scene) {
  20950. this._renderingGroups = new Array();
  20951. this._autoClearDepthStencil = {};
  20952. this._customOpaqueSortCompareFn = {};
  20953. this._customAlphaTestSortCompareFn = {};
  20954. this._customTransparentSortCompareFn = {};
  20955. this._renderinGroupInfo = null;
  20956. this._scene = scene;
  20957. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20958. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20959. }
  20960. }
  20961. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20962. if (depth === void 0) { depth = true; }
  20963. if (stencil === void 0) { stencil = true; }
  20964. if (this._depthStencilBufferAlreadyCleaned) {
  20965. return;
  20966. }
  20967. this._scene.getEngine().clear(null, false, depth, stencil);
  20968. this._depthStencilBufferAlreadyCleaned = true;
  20969. };
  20970. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20971. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20972. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20973. var info = null;
  20974. if (observable) {
  20975. if (!this._renderinGroupInfo) {
  20976. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20977. }
  20978. info = this._renderinGroupInfo;
  20979. info.scene = this._scene;
  20980. info.camera = this._scene.activeCamera;
  20981. }
  20982. // Dispatch sprites
  20983. if (renderSprites) {
  20984. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20985. var manager = this._scene.spriteManagers[index];
  20986. this.dispatchSprites(manager);
  20987. }
  20988. }
  20989. // Render
  20990. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20991. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20992. var renderingGroup = this._renderingGroups[index];
  20993. if (!renderingGroup && !observable)
  20994. continue;
  20995. var renderingGroupMask = 0;
  20996. // Fire PRECLEAR stage
  20997. if (observable && info) {
  20998. renderingGroupMask = Math.pow(2, index);
  20999. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  21000. info.renderingGroupId = index;
  21001. observable.notifyObservers(info, renderingGroupMask);
  21002. }
  21003. // Clear depth/stencil if needed
  21004. if (RenderingManager.AUTOCLEAR) {
  21005. var autoClear = this._autoClearDepthStencil[index];
  21006. if (autoClear && autoClear.autoClear) {
  21007. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  21008. }
  21009. }
  21010. if (observable && info) {
  21011. // Fire PREOPAQUE stage
  21012. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  21013. observable.notifyObservers(info, renderingGroupMask);
  21014. // Fire PRETRANSPARENT stage
  21015. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  21016. observable.notifyObservers(info, renderingGroupMask);
  21017. }
  21018. if (renderingGroup)
  21019. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  21020. // Fire POSTTRANSPARENT stage
  21021. if (observable && info) {
  21022. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  21023. observable.notifyObservers(info, renderingGroupMask);
  21024. }
  21025. }
  21026. };
  21027. RenderingManager.prototype.reset = function () {
  21028. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21029. var renderingGroup = this._renderingGroups[index];
  21030. if (renderingGroup) {
  21031. renderingGroup.prepare();
  21032. }
  21033. }
  21034. };
  21035. RenderingManager.prototype.dispose = function () {
  21036. this.freeRenderingGroups();
  21037. this._renderingGroups.length = 0;
  21038. };
  21039. /**
  21040. * Clear the info related to rendering groups preventing retention points during dispose.
  21041. */
  21042. RenderingManager.prototype.freeRenderingGroups = function () {
  21043. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21044. var renderingGroup = this._renderingGroups[index];
  21045. if (renderingGroup) {
  21046. renderingGroup.dispose();
  21047. }
  21048. }
  21049. };
  21050. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21051. if (this._renderingGroups[renderingGroupId] === undefined) {
  21052. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21053. }
  21054. };
  21055. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21056. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21057. this._prepareRenderingGroup(renderingGroupId);
  21058. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21059. };
  21060. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21061. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21062. this._prepareRenderingGroup(renderingGroupId);
  21063. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21064. };
  21065. /**
  21066. * @param subMesh The submesh to dispatch
  21067. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21068. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21069. */
  21070. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21071. if (mesh === undefined) {
  21072. mesh = subMesh.getMesh();
  21073. }
  21074. var renderingGroupId = mesh.renderingGroupId || 0;
  21075. this._prepareRenderingGroup(renderingGroupId);
  21076. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21077. };
  21078. /**
  21079. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21080. * This allowed control for front to back rendering or reversly depending of the special needs.
  21081. *
  21082. * @param renderingGroupId The rendering group id corresponding to its index
  21083. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21084. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21085. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21086. */
  21087. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21088. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21089. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21090. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21091. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21092. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21093. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21094. if (this._renderingGroups[renderingGroupId]) {
  21095. var group = this._renderingGroups[renderingGroupId];
  21096. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21097. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21098. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21099. }
  21100. };
  21101. /**
  21102. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21103. *
  21104. * @param renderingGroupId The rendering group id corresponding to its index
  21105. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21106. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21107. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21108. */
  21109. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21110. if (depth === void 0) { depth = true; }
  21111. if (stencil === void 0) { stencil = true; }
  21112. this._autoClearDepthStencil[renderingGroupId] = {
  21113. autoClear: autoClearDepthStencil,
  21114. depth: depth,
  21115. stencil: stencil
  21116. };
  21117. };
  21118. /**
  21119. * The max id used for rendering groups (not included)
  21120. */
  21121. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21122. /**
  21123. * The min id used for rendering groups (included)
  21124. */
  21125. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21126. /**
  21127. * Used to globally prevent autoclearing scenes.
  21128. */
  21129. RenderingManager.AUTOCLEAR = true;
  21130. return RenderingManager;
  21131. }());
  21132. BABYLON.RenderingManager = RenderingManager;
  21133. })(BABYLON || (BABYLON = {}));
  21134. //# sourceMappingURL=babylon.renderingManager.js.map
  21135. var BABYLON;
  21136. (function (BABYLON) {
  21137. var RenderingGroup = /** @class */ (function () {
  21138. /**
  21139. * Creates a new rendering group.
  21140. * @param index The rendering group index
  21141. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21142. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21143. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21144. */
  21145. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21146. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21147. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21148. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21149. this.index = index;
  21150. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21151. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21152. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21153. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21154. this._particleSystems = new BABYLON.SmartArray(256);
  21155. this._spriteManagers = new BABYLON.SmartArray(256);
  21156. this._edgesRenderers = new BABYLON.SmartArray(16);
  21157. this._scene = scene;
  21158. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21159. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21160. this.transparentSortCompareFn = transparentSortCompareFn;
  21161. }
  21162. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21163. /**
  21164. * Set the opaque sort comparison function.
  21165. * If null the sub meshes will be render in the order they were created
  21166. */
  21167. set: function (value) {
  21168. this._opaqueSortCompareFn = value;
  21169. if (value) {
  21170. this._renderOpaque = this.renderOpaqueSorted;
  21171. }
  21172. else {
  21173. this._renderOpaque = RenderingGroup.renderUnsorted;
  21174. }
  21175. },
  21176. enumerable: true,
  21177. configurable: true
  21178. });
  21179. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21180. /**
  21181. * Set the alpha test sort comparison function.
  21182. * If null the sub meshes will be render in the order they were created
  21183. */
  21184. set: function (value) {
  21185. this._alphaTestSortCompareFn = value;
  21186. if (value) {
  21187. this._renderAlphaTest = this.renderAlphaTestSorted;
  21188. }
  21189. else {
  21190. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21191. }
  21192. },
  21193. enumerable: true,
  21194. configurable: true
  21195. });
  21196. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21197. /**
  21198. * Set the transparent sort comparison function.
  21199. * If null the sub meshes will be render in the order they were created
  21200. */
  21201. set: function (value) {
  21202. if (value) {
  21203. this._transparentSortCompareFn = value;
  21204. }
  21205. else {
  21206. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21207. }
  21208. this._renderTransparent = this.renderTransparentSorted;
  21209. },
  21210. enumerable: true,
  21211. configurable: true
  21212. });
  21213. /**
  21214. * Render all the sub meshes contained in the group.
  21215. * @param customRenderFunction Used to override the default render behaviour of the group.
  21216. * @returns true if rendered some submeshes.
  21217. */
  21218. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21219. if (customRenderFunction) {
  21220. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21221. return;
  21222. }
  21223. var engine = this._scene.getEngine();
  21224. // Depth only
  21225. if (this._depthOnlySubMeshes.length !== 0) {
  21226. engine.setColorWrite(false);
  21227. this._renderAlphaTest(this._depthOnlySubMeshes);
  21228. engine.setColorWrite(true);
  21229. }
  21230. // Opaque
  21231. if (this._opaqueSubMeshes.length !== 0) {
  21232. this._renderOpaque(this._opaqueSubMeshes);
  21233. }
  21234. // Alpha test
  21235. if (this._alphaTestSubMeshes.length !== 0) {
  21236. this._renderAlphaTest(this._alphaTestSubMeshes);
  21237. }
  21238. var stencilState = engine.getStencilBuffer();
  21239. engine.setStencilBuffer(false);
  21240. // Sprites
  21241. if (renderSprites) {
  21242. this._renderSprites();
  21243. }
  21244. // Particles
  21245. if (renderParticles) {
  21246. this._renderParticles(activeMeshes);
  21247. }
  21248. if (this.onBeforeTransparentRendering) {
  21249. this.onBeforeTransparentRendering();
  21250. }
  21251. // Transparent
  21252. if (this._transparentSubMeshes.length !== 0) {
  21253. this._renderTransparent(this._transparentSubMeshes);
  21254. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21255. }
  21256. // Set back stencil to false in case it changes before the edge renderer.
  21257. engine.setStencilBuffer(false);
  21258. // Edges
  21259. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21260. this._edgesRenderers.data[edgesRendererIndex].render();
  21261. }
  21262. // Restore Stencil state.
  21263. engine.setStencilBuffer(stencilState);
  21264. };
  21265. /**
  21266. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21267. * @param subMeshes The submeshes to render
  21268. */
  21269. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21270. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21271. };
  21272. /**
  21273. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21274. * @param subMeshes The submeshes to render
  21275. */
  21276. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21277. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21278. };
  21279. /**
  21280. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21281. * @param subMeshes The submeshes to render
  21282. */
  21283. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21284. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21285. };
  21286. /**
  21287. * Renders the submeshes in a specified order.
  21288. * @param subMeshes The submeshes to sort before render
  21289. * @param sortCompareFn The comparison function use to sort
  21290. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21291. * @param transparent Specifies to activate blending if true
  21292. */
  21293. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21294. var subIndex = 0;
  21295. var subMesh;
  21296. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21297. for (; subIndex < subMeshes.length; subIndex++) {
  21298. subMesh = subMeshes.data[subIndex];
  21299. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21300. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21301. }
  21302. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21303. if (sortCompareFn) {
  21304. sortedArray.sort(sortCompareFn);
  21305. }
  21306. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21307. subMesh = sortedArray[subIndex];
  21308. if (transparent) {
  21309. var material = subMesh.getMaterial();
  21310. if (material && material.needDepthPrePass) {
  21311. var engine = material.getScene().getEngine();
  21312. engine.setColorWrite(false);
  21313. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21314. subMesh.render(false);
  21315. engine.setColorWrite(true);
  21316. }
  21317. }
  21318. subMesh.render(transparent);
  21319. }
  21320. };
  21321. /**
  21322. * Renders the submeshes in the order they were dispatched (no sort applied).
  21323. * @param subMeshes The submeshes to render
  21324. */
  21325. RenderingGroup.renderUnsorted = function (subMeshes) {
  21326. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21327. var submesh = subMeshes.data[subIndex];
  21328. submesh.render(false);
  21329. }
  21330. };
  21331. /**
  21332. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21333. * are rendered back to front if in the same alpha index.
  21334. *
  21335. * @param a The first submesh
  21336. * @param b The second submesh
  21337. * @returns The result of the comparison
  21338. */
  21339. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21340. // Alpha index first
  21341. if (a._alphaIndex > b._alphaIndex) {
  21342. return 1;
  21343. }
  21344. if (a._alphaIndex < b._alphaIndex) {
  21345. return -1;
  21346. }
  21347. // Then distance to camera
  21348. return RenderingGroup.backToFrontSortCompare(a, b);
  21349. };
  21350. /**
  21351. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21352. * are rendered back to front.
  21353. *
  21354. * @param a The first submesh
  21355. * @param b The second submesh
  21356. * @returns The result of the comparison
  21357. */
  21358. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21359. // Then distance to camera
  21360. if (a._distanceToCamera < b._distanceToCamera) {
  21361. return 1;
  21362. }
  21363. if (a._distanceToCamera > b._distanceToCamera) {
  21364. return -1;
  21365. }
  21366. return 0;
  21367. };
  21368. /**
  21369. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21370. * are rendered front to back (prevent overdraw).
  21371. *
  21372. * @param a The first submesh
  21373. * @param b The second submesh
  21374. * @returns The result of the comparison
  21375. */
  21376. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21377. // Then distance to camera
  21378. if (a._distanceToCamera < b._distanceToCamera) {
  21379. return -1;
  21380. }
  21381. if (a._distanceToCamera > b._distanceToCamera) {
  21382. return 1;
  21383. }
  21384. return 0;
  21385. };
  21386. /**
  21387. * Resets the different lists of submeshes to prepare a new frame.
  21388. */
  21389. RenderingGroup.prototype.prepare = function () {
  21390. this._opaqueSubMeshes.reset();
  21391. this._transparentSubMeshes.reset();
  21392. this._alphaTestSubMeshes.reset();
  21393. this._depthOnlySubMeshes.reset();
  21394. this._particleSystems.reset();
  21395. this._spriteManagers.reset();
  21396. this._edgesRenderers.reset();
  21397. };
  21398. RenderingGroup.prototype.dispose = function () {
  21399. this._opaqueSubMeshes.dispose();
  21400. this._transparentSubMeshes.dispose();
  21401. this._alphaTestSubMeshes.dispose();
  21402. this._depthOnlySubMeshes.dispose();
  21403. this._particleSystems.dispose();
  21404. this._spriteManagers.dispose();
  21405. this._edgesRenderers.dispose();
  21406. };
  21407. /**
  21408. * Inserts the submesh in its correct queue depending on its material.
  21409. * @param subMesh The submesh to dispatch
  21410. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21411. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21412. */
  21413. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21414. // Get mesh and materials if not provided
  21415. if (mesh === undefined) {
  21416. mesh = subMesh.getMesh();
  21417. }
  21418. if (material === undefined) {
  21419. material = subMesh.getMaterial();
  21420. }
  21421. if (material === null || material === undefined) {
  21422. return;
  21423. }
  21424. if (material.needAlphaBlendingForMesh(mesh)) {
  21425. this._transparentSubMeshes.push(subMesh);
  21426. }
  21427. else if (material.needAlphaTesting()) {
  21428. if (material.needDepthPrePass) {
  21429. this._depthOnlySubMeshes.push(subMesh);
  21430. }
  21431. this._alphaTestSubMeshes.push(subMesh);
  21432. }
  21433. else {
  21434. if (material.needDepthPrePass) {
  21435. this._depthOnlySubMeshes.push(subMesh);
  21436. }
  21437. this._opaqueSubMeshes.push(subMesh); // Opaque
  21438. }
  21439. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21440. this._edgesRenderers.push(mesh._edgesRenderer);
  21441. }
  21442. };
  21443. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21444. this._spriteManagers.push(spriteManager);
  21445. };
  21446. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21447. this._particleSystems.push(particleSystem);
  21448. };
  21449. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21450. if (this._particleSystems.length === 0) {
  21451. return;
  21452. }
  21453. // Particles
  21454. var activeCamera = this._scene.activeCamera;
  21455. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21456. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21457. var particleSystem = this._particleSystems.data[particleIndex];
  21458. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21459. continue;
  21460. }
  21461. var emitter = particleSystem.emitter;
  21462. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21463. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21464. }
  21465. }
  21466. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21467. };
  21468. RenderingGroup.prototype._renderSprites = function () {
  21469. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21470. return;
  21471. }
  21472. // Sprites
  21473. var activeCamera = this._scene.activeCamera;
  21474. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21475. for (var id = 0; id < this._spriteManagers.length; id++) {
  21476. var spriteManager = this._spriteManagers.data[id];
  21477. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21478. spriteManager.render();
  21479. }
  21480. }
  21481. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21482. };
  21483. return RenderingGroup;
  21484. }());
  21485. BABYLON.RenderingGroup = RenderingGroup;
  21486. })(BABYLON || (BABYLON = {}));
  21487. //# sourceMappingURL=babylon.renderingGroup.js.map
  21488. var BABYLON;
  21489. (function (BABYLON) {
  21490. var ClickInfo = /** @class */ (function () {
  21491. function ClickInfo() {
  21492. this._singleClick = false;
  21493. this._doubleClick = false;
  21494. this._hasSwiped = false;
  21495. this._ignore = false;
  21496. }
  21497. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21498. get: function () {
  21499. return this._singleClick;
  21500. },
  21501. set: function (b) {
  21502. this._singleClick = b;
  21503. },
  21504. enumerable: true,
  21505. configurable: true
  21506. });
  21507. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21508. get: function () {
  21509. return this._doubleClick;
  21510. },
  21511. set: function (b) {
  21512. this._doubleClick = b;
  21513. },
  21514. enumerable: true,
  21515. configurable: true
  21516. });
  21517. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21518. get: function () {
  21519. return this._hasSwiped;
  21520. },
  21521. set: function (b) {
  21522. this._hasSwiped = b;
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21528. get: function () {
  21529. return this._ignore;
  21530. },
  21531. set: function (b) {
  21532. this._ignore = b;
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. return ClickInfo;
  21538. }());
  21539. /**
  21540. * This class is used by the onRenderingGroupObservable
  21541. */
  21542. var RenderingGroupInfo = /** @class */ (function () {
  21543. function RenderingGroupInfo() {
  21544. }
  21545. /**
  21546. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21547. * This stage will be fired no matter what
  21548. */
  21549. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21550. /**
  21551. * Called before opaque object are rendered.
  21552. * This stage will be fired only if there's 3D Opaque content to render
  21553. */
  21554. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21555. /**
  21556. * Called after the opaque objects are rendered and before the transparent ones
  21557. * This stage will be fired only if there's 3D transparent content to render
  21558. */
  21559. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21560. /**
  21561. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21562. * This stage will be fired no matter what
  21563. */
  21564. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21565. return RenderingGroupInfo;
  21566. }());
  21567. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21568. /**
  21569. * Represents a scene to be rendered by the engine.
  21570. * @see http://doc.babylonjs.com/page.php?p=21911
  21571. */
  21572. var Scene = /** @class */ (function () {
  21573. /**
  21574. * @constructor
  21575. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21576. */
  21577. function Scene(engine) {
  21578. // Members
  21579. this.autoClear = true;
  21580. this.autoClearDepthAndStencil = true;
  21581. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21582. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21583. this.forceWireframe = false;
  21584. this._forcePointsCloud = false;
  21585. this.forceShowBoundingBoxes = false;
  21586. this.animationsEnabled = true;
  21587. this.useConstantAnimationDeltaTime = false;
  21588. this.constantlyUpdateMeshUnderPointer = false;
  21589. this.hoverCursor = "pointer";
  21590. this.defaultCursor = "";
  21591. /**
  21592. * This is used to call preventDefault() on pointer down
  21593. * in order to block unwanted artifacts like system double clicks
  21594. */
  21595. this.preventDefaultOnPointerDown = true;
  21596. // Metadata
  21597. this.metadata = null;
  21598. /**
  21599. * An event triggered when the scene is disposed.
  21600. * @type {BABYLON.Observable}
  21601. */
  21602. this.onDisposeObservable = new BABYLON.Observable();
  21603. /**
  21604. * An event triggered before rendering the scene (right after animations and physics)
  21605. * @type {BABYLON.Observable}
  21606. */
  21607. this.onBeforeRenderObservable = new BABYLON.Observable();
  21608. /**
  21609. * An event triggered after rendering the scene
  21610. * @type {BABYLON.Observable}
  21611. */
  21612. this.onAfterRenderObservable = new BABYLON.Observable();
  21613. /**
  21614. * An event triggered before animating the scene
  21615. * @type {BABYLON.Observable}
  21616. */
  21617. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21618. /**
  21619. * An event triggered after animations processing
  21620. * @type {BABYLON.Observable}
  21621. */
  21622. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21623. /**
  21624. * An event triggered before draw calls are ready to be sent
  21625. * @type {BABYLON.Observable}
  21626. */
  21627. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21628. /**
  21629. * An event triggered after draw calls have been sent
  21630. * @type {BABYLON.Observable}
  21631. */
  21632. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21633. /**
  21634. * An event triggered when physic simulation is about to be run
  21635. * @type {BABYLON.Observable}
  21636. */
  21637. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21638. /**
  21639. * An event triggered when physic simulation has been done
  21640. * @type {BABYLON.Observable}
  21641. */
  21642. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21643. /**
  21644. * An event triggered when the scene is ready
  21645. * @type {BABYLON.Observable}
  21646. */
  21647. this.onReadyObservable = new BABYLON.Observable();
  21648. /**
  21649. * An event triggered before rendering a camera
  21650. * @type {BABYLON.Observable}
  21651. */
  21652. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21653. /**
  21654. * An event triggered after rendering a camera
  21655. * @type {BABYLON.Observable}
  21656. */
  21657. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21658. /**
  21659. * An event triggered when active meshes evaluation is about to start
  21660. * @type {BABYLON.Observable}
  21661. */
  21662. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21663. /**
  21664. * An event triggered when active meshes evaluation is done
  21665. * @type {BABYLON.Observable}
  21666. */
  21667. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21668. /**
  21669. * An event triggered when particles rendering is about to start
  21670. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21671. * @type {BABYLON.Observable}
  21672. */
  21673. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21674. /**
  21675. * An event triggered when particles rendering is done
  21676. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21677. * @type {BABYLON.Observable}
  21678. */
  21679. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21680. /**
  21681. * An event triggered when sprites rendering is about to start
  21682. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21683. * @type {BABYLON.Observable}
  21684. */
  21685. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21686. /**
  21687. * An event triggered when sprites rendering is done
  21688. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21689. * @type {BABYLON.Observable}
  21690. */
  21691. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21692. /**
  21693. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21694. * @type {BABYLON.Observable}
  21695. */
  21696. this.onDataLoadedObservable = new BABYLON.Observable();
  21697. /**
  21698. * An event triggered when a camera is created
  21699. * @type {BABYLON.Observable}
  21700. */
  21701. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21702. /**
  21703. * An event triggered when a camera is removed
  21704. * @type {BABYLON.Observable}
  21705. */
  21706. this.onCameraRemovedObservable = new BABYLON.Observable();
  21707. /**
  21708. * An event triggered when a light is created
  21709. * @type {BABYLON.Observable}
  21710. */
  21711. this.onNewLightAddedObservable = new BABYLON.Observable();
  21712. /**
  21713. * An event triggered when a light is removed
  21714. * @type {BABYLON.Observable}
  21715. */
  21716. this.onLightRemovedObservable = new BABYLON.Observable();
  21717. /**
  21718. * An event triggered when a geometry is created
  21719. * @type {BABYLON.Observable}
  21720. */
  21721. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21722. /**
  21723. * An event triggered when a geometry is removed
  21724. * @type {BABYLON.Observable}
  21725. */
  21726. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21727. /**
  21728. * An event triggered when a transform node is created
  21729. * @type {BABYLON.Observable}
  21730. */
  21731. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21732. /**
  21733. * An event triggered when a transform node is removed
  21734. * @type {BABYLON.Observable}
  21735. */
  21736. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21737. /**
  21738. * An event triggered when a mesh is created
  21739. * @type {BABYLON.Observable}
  21740. */
  21741. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21742. /**
  21743. * An event triggered when a mesh is removed
  21744. * @type {BABYLON.Observable}
  21745. */
  21746. this.onMeshRemovedObservable = new BABYLON.Observable();
  21747. /**
  21748. * An event triggered when render targets are about to be rendered
  21749. * Can happen multiple times per frame.
  21750. * @type {BABYLON.Observable}
  21751. */
  21752. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21753. /**
  21754. * An event triggered when render targets were rendered.
  21755. * Can happen multiple times per frame.
  21756. * @type {BABYLON.Observable}
  21757. */
  21758. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21759. /**
  21760. * An event triggered before calculating deterministic simulation step
  21761. * @type {BABYLON.Observable}
  21762. */
  21763. this.onBeforeStepObservable = new BABYLON.Observable();
  21764. /**
  21765. * An event triggered after calculating deterministic simulation step
  21766. * @type {BABYLON.Observable}
  21767. */
  21768. this.onAfterStepObservable = new BABYLON.Observable();
  21769. /**
  21770. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21771. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21772. * 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)
  21773. */
  21774. this.onRenderingGroupObservable = new BABYLON.Observable();
  21775. // Animations
  21776. this.animations = [];
  21777. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21778. /**
  21779. * 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).
  21780. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21781. */
  21782. this.onPrePointerObservable = new BABYLON.Observable();
  21783. /**
  21784. * Observable event triggered each time an input event is received from the rendering canvas
  21785. */
  21786. this.onPointerObservable = new BABYLON.Observable();
  21787. this._meshPickProceed = false;
  21788. this._currentPickResult = null;
  21789. this._previousPickResult = null;
  21790. this._totalPointersPressed = 0;
  21791. this._doubleClickOccured = false;
  21792. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21793. this.cameraToUseForPointers = null;
  21794. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21795. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21796. this._startingPointerTime = 0;
  21797. this._previousStartingPointerTime = 0;
  21798. // Deterministic lockstep
  21799. this._timeAccumulator = 0;
  21800. this._currentStepId = 0;
  21801. this._currentInternalStep = 0;
  21802. // Keyboard
  21803. /**
  21804. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21805. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21806. */
  21807. this.onPreKeyboardObservable = new BABYLON.Observable();
  21808. /**
  21809. * Observable event triggered each time an keyboard event is received from the hosting window
  21810. */
  21811. this.onKeyboardObservable = new BABYLON.Observable();
  21812. // Coordinate system
  21813. /**
  21814. * use right-handed coordinate system on this scene.
  21815. * @type {boolean}
  21816. */
  21817. this._useRightHandedSystem = false;
  21818. // Fog
  21819. this._fogEnabled = true;
  21820. this._fogMode = Scene.FOGMODE_NONE;
  21821. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21822. this.fogDensity = 0.1;
  21823. this.fogStart = 0;
  21824. this.fogEnd = 1000.0;
  21825. // Lights
  21826. /**
  21827. * is shadow enabled on this scene.
  21828. * @type {boolean}
  21829. */
  21830. this._shadowsEnabled = true;
  21831. /**
  21832. * is light enabled on this scene.
  21833. * @type {boolean}
  21834. */
  21835. this._lightsEnabled = true;
  21836. /**
  21837. * All of the lights added to this scene.
  21838. * @see BABYLON.Light
  21839. * @type {BABYLON.Light[]}
  21840. */
  21841. this.lights = new Array();
  21842. // Cameras
  21843. /** All of the cameras added to this scene. */
  21844. this.cameras = new Array();
  21845. /** All of the active cameras added to this scene. */
  21846. this.activeCameras = new Array();
  21847. // Meshes
  21848. /**
  21849. * All of the tranform nodes added to this scene.
  21850. * @see BABYLON.TransformNode
  21851. * @type {BABYLON.TransformNode[]}
  21852. */
  21853. this.transformNodes = new Array();
  21854. /**
  21855. * All of the (abstract) meshes added to this scene.
  21856. * @see BABYLON.AbstractMesh
  21857. * @type {BABYLON.AbstractMesh[]}
  21858. */
  21859. this.meshes = new Array();
  21860. /**
  21861. * All of the animation groups added to this scene.
  21862. * @see BABYLON.AnimationGroup
  21863. * @type {BABYLON.AnimationGroup[]}
  21864. */
  21865. this.animationGroups = new Array();
  21866. // Geometries
  21867. this._geometries = new Array();
  21868. this.materials = new Array();
  21869. this.multiMaterials = new Array();
  21870. // Textures
  21871. this._texturesEnabled = true;
  21872. this.textures = new Array();
  21873. // Particles
  21874. this.particlesEnabled = true;
  21875. this.particleSystems = new Array();
  21876. // Sprites
  21877. this.spritesEnabled = true;
  21878. this.spriteManagers = new Array();
  21879. /**
  21880. * The list of layers (background and foreground) of the scene.
  21881. */
  21882. this.layers = new Array();
  21883. /**
  21884. * The list of effect layers (highlights/glow) contained in the scene.
  21885. */
  21886. this.effectLayers = new Array();
  21887. // Skeletons
  21888. this._skeletonsEnabled = true;
  21889. this.skeletons = new Array();
  21890. // Morph targets
  21891. this.morphTargetManagers = new Array();
  21892. // Lens flares
  21893. this.lensFlaresEnabled = true;
  21894. this.lensFlareSystems = new Array();
  21895. // Collisions
  21896. this.collisionsEnabled = true;
  21897. /** Defines the gravity applied to this scene */
  21898. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21899. // Postprocesses
  21900. this.postProcesses = new Array();
  21901. this.postProcessesEnabled = true;
  21902. // Customs render targets
  21903. this.renderTargetsEnabled = true;
  21904. this.dumpNextRenderTargets = false;
  21905. this.customRenderTargets = new Array();
  21906. // Imported meshes
  21907. this.importedMeshesFiles = new Array();
  21908. // Probes
  21909. this.probesEnabled = true;
  21910. this.reflectionProbes = new Array();
  21911. this._actionManagers = new Array();
  21912. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21913. // Procedural textures
  21914. this.proceduralTexturesEnabled = true;
  21915. this._proceduralTextures = new Array();
  21916. this.soundTracks = new Array();
  21917. this._audioEnabled = true;
  21918. this._headphone = false;
  21919. // Performance counters
  21920. this._totalVertices = new BABYLON.PerfCounter();
  21921. this._activeIndices = new BABYLON.PerfCounter();
  21922. this._activeParticles = new BABYLON.PerfCounter();
  21923. this._activeBones = new BABYLON.PerfCounter();
  21924. this._animationTime = 0;
  21925. this.animationTimeScale = 1;
  21926. this._renderId = 0;
  21927. this._executeWhenReadyTimeoutId = -1;
  21928. this._intermediateRendering = false;
  21929. this._viewUpdateFlag = -1;
  21930. this._projectionUpdateFlag = -1;
  21931. this._alternateViewUpdateFlag = -1;
  21932. this._alternateProjectionUpdateFlag = -1;
  21933. this._toBeDisposed = new BABYLON.SmartArray(256);
  21934. this._activeRequests = new Array();
  21935. this._pendingData = new Array();
  21936. this._isDisposed = false;
  21937. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21938. this._activeMeshes = new BABYLON.SmartArray(256);
  21939. this._processedMaterials = new BABYLON.SmartArray(256);
  21940. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21941. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21942. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21943. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21944. this._activeAnimatables = new Array();
  21945. this._transformMatrix = BABYLON.Matrix.Zero();
  21946. this._useAlternateCameraConfiguration = false;
  21947. this._alternateRendering = false;
  21948. this.requireLightSorting = false;
  21949. this._depthRenderer = {};
  21950. this._activeMeshesFrozen = false;
  21951. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21952. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21953. this._engine.scenes.push(this);
  21954. this._uid = null;
  21955. this._renderingManager = new BABYLON.RenderingManager(this);
  21956. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21957. if (BABYLON.OutlineRenderer) {
  21958. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21959. }
  21960. if (BABYLON.Tools.IsWindowObjectExist()) {
  21961. this.attachControl();
  21962. }
  21963. //simplification queue
  21964. if (BABYLON.SimplificationQueue) {
  21965. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21966. }
  21967. //collision coordinator initialization. For now legacy per default.
  21968. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21969. // Uniform Buffer
  21970. this._createUbo();
  21971. // Default Image processing definition.
  21972. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21973. }
  21974. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21975. /** The fog is deactivated */
  21976. get: function () {
  21977. return Scene._FOGMODE_NONE;
  21978. },
  21979. enumerable: true,
  21980. configurable: true
  21981. });
  21982. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21983. /** The fog density is following an exponential function */
  21984. get: function () {
  21985. return Scene._FOGMODE_EXP;
  21986. },
  21987. enumerable: true,
  21988. configurable: true
  21989. });
  21990. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21991. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21992. get: function () {
  21993. return Scene._FOGMODE_EXP2;
  21994. },
  21995. enumerable: true,
  21996. configurable: true
  21997. });
  21998. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21999. /** The fog density is following a linear function. */
  22000. get: function () {
  22001. return Scene._FOGMODE_LINEAR;
  22002. },
  22003. enumerable: true,
  22004. configurable: true
  22005. });
  22006. Object.defineProperty(Scene.prototype, "environmentTexture", {
  22007. /**
  22008. * Texture used in all pbr material as the reflection texture.
  22009. * As in the majority of the scene they are the same (exception for multi room and so on),
  22010. * this is easier to reference from here than from all the materials.
  22011. */
  22012. get: function () {
  22013. return this._environmentTexture;
  22014. },
  22015. /**
  22016. * Texture used in all pbr material as the reflection texture.
  22017. * As in the majority of the scene they are the same (exception for multi room and so on),
  22018. * this is easier to set here than in all the materials.
  22019. */
  22020. set: function (value) {
  22021. if (this._environmentTexture === value) {
  22022. return;
  22023. }
  22024. this._environmentTexture = value;
  22025. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22026. },
  22027. enumerable: true,
  22028. configurable: true
  22029. });
  22030. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22031. /**
  22032. * Default image processing configuration used either in the rendering
  22033. * Forward main pass or through the imageProcessingPostProcess if present.
  22034. * As in the majority of the scene they are the same (exception for multi camera),
  22035. * this is easier to reference from here than from all the materials and post process.
  22036. *
  22037. * No setter as we it is a shared configuration, you can set the values instead.
  22038. */
  22039. get: function () {
  22040. return this._imageProcessingConfiguration;
  22041. },
  22042. enumerable: true,
  22043. configurable: true
  22044. });
  22045. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22046. get: function () {
  22047. return this._forcePointsCloud;
  22048. },
  22049. set: function (value) {
  22050. if (this._forcePointsCloud === value) {
  22051. return;
  22052. }
  22053. this._forcePointsCloud = value;
  22054. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22055. },
  22056. enumerable: true,
  22057. configurable: true
  22058. });
  22059. Object.defineProperty(Scene.prototype, "onDispose", {
  22060. /** A function to be executed when this scene is disposed. */
  22061. set: function (callback) {
  22062. if (this._onDisposeObserver) {
  22063. this.onDisposeObservable.remove(this._onDisposeObserver);
  22064. }
  22065. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22066. },
  22067. enumerable: true,
  22068. configurable: true
  22069. });
  22070. Object.defineProperty(Scene.prototype, "beforeRender", {
  22071. /** A function to be executed before rendering this scene */
  22072. set: function (callback) {
  22073. if (this._onBeforeRenderObserver) {
  22074. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22075. }
  22076. if (callback) {
  22077. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22078. }
  22079. },
  22080. enumerable: true,
  22081. configurable: true
  22082. });
  22083. Object.defineProperty(Scene.prototype, "afterRender", {
  22084. /** A function to be executed after rendering this scene */
  22085. set: function (callback) {
  22086. if (this._onAfterRenderObserver) {
  22087. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22088. }
  22089. if (callback) {
  22090. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22091. }
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22097. set: function (callback) {
  22098. if (this._onBeforeCameraRenderObserver) {
  22099. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22100. }
  22101. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22102. },
  22103. enumerable: true,
  22104. configurable: true
  22105. });
  22106. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22107. set: function (callback) {
  22108. if (this._onAfterCameraRenderObserver) {
  22109. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22110. }
  22111. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22117. get: function () {
  22118. if (!this._gamepadManager) {
  22119. this._gamepadManager = new BABYLON.GamepadManager(this);
  22120. }
  22121. return this._gamepadManager;
  22122. },
  22123. enumerable: true,
  22124. configurable: true
  22125. });
  22126. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22127. get: function () {
  22128. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22129. },
  22130. enumerable: true,
  22131. configurable: true
  22132. });
  22133. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22134. get: function () {
  22135. return this._useRightHandedSystem;
  22136. },
  22137. set: function (value) {
  22138. if (this._useRightHandedSystem === value) {
  22139. return;
  22140. }
  22141. this._useRightHandedSystem = value;
  22142. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22143. },
  22144. enumerable: true,
  22145. configurable: true
  22146. });
  22147. Scene.prototype.setStepId = function (newStepId) {
  22148. this._currentStepId = newStepId;
  22149. };
  22150. ;
  22151. Scene.prototype.getStepId = function () {
  22152. return this._currentStepId;
  22153. };
  22154. ;
  22155. Scene.prototype.getInternalStep = function () {
  22156. return this._currentInternalStep;
  22157. };
  22158. ;
  22159. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22160. get: function () {
  22161. return this._fogEnabled;
  22162. },
  22163. /**
  22164. * is fog enabled on this scene.
  22165. */
  22166. set: function (value) {
  22167. if (this._fogEnabled === value) {
  22168. return;
  22169. }
  22170. this._fogEnabled = value;
  22171. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22172. },
  22173. enumerable: true,
  22174. configurable: true
  22175. });
  22176. Object.defineProperty(Scene.prototype, "fogMode", {
  22177. get: function () {
  22178. return this._fogMode;
  22179. },
  22180. set: function (value) {
  22181. if (this._fogMode === value) {
  22182. return;
  22183. }
  22184. this._fogMode = value;
  22185. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22186. },
  22187. enumerable: true,
  22188. configurable: true
  22189. });
  22190. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22191. get: function () {
  22192. return this._shadowsEnabled;
  22193. },
  22194. set: function (value) {
  22195. if (this._shadowsEnabled === value) {
  22196. return;
  22197. }
  22198. this._shadowsEnabled = value;
  22199. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22200. },
  22201. enumerable: true,
  22202. configurable: true
  22203. });
  22204. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22205. get: function () {
  22206. return this._lightsEnabled;
  22207. },
  22208. set: function (value) {
  22209. if (this._lightsEnabled === value) {
  22210. return;
  22211. }
  22212. this._lightsEnabled = value;
  22213. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22214. },
  22215. enumerable: true,
  22216. configurable: true
  22217. });
  22218. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22219. /** The default material used on meshes when no material is affected */
  22220. get: function () {
  22221. if (!this._defaultMaterial) {
  22222. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22223. }
  22224. return this._defaultMaterial;
  22225. },
  22226. /** The default material used on meshes when no material is affected */
  22227. set: function (value) {
  22228. this._defaultMaterial = value;
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22234. get: function () {
  22235. return this._texturesEnabled;
  22236. },
  22237. set: function (value) {
  22238. if (this._texturesEnabled === value) {
  22239. return;
  22240. }
  22241. this._texturesEnabled = value;
  22242. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22243. },
  22244. enumerable: true,
  22245. configurable: true
  22246. });
  22247. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22248. get: function () {
  22249. return this._skeletonsEnabled;
  22250. },
  22251. set: function (value) {
  22252. if (this._skeletonsEnabled === value) {
  22253. return;
  22254. }
  22255. this._skeletonsEnabled = value;
  22256. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22257. },
  22258. enumerable: true,
  22259. configurable: true
  22260. });
  22261. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22262. get: function () {
  22263. if (!this._postProcessRenderPipelineManager) {
  22264. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22265. }
  22266. return this._postProcessRenderPipelineManager;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22272. get: function () {
  22273. if (!this._mainSoundTrack) {
  22274. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22275. }
  22276. return this._mainSoundTrack;
  22277. },
  22278. enumerable: true,
  22279. configurable: true
  22280. });
  22281. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22282. get: function () {
  22283. return this._alternateRendering;
  22284. },
  22285. enumerable: true,
  22286. configurable: true
  22287. });
  22288. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22289. get: function () {
  22290. return this._frustumPlanes;
  22291. },
  22292. enumerable: true,
  22293. configurable: true
  22294. });
  22295. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22296. /**
  22297. * Gets the current geometry buffer associated to the scene.
  22298. */
  22299. get: function () {
  22300. return this._geometryBufferRenderer;
  22301. },
  22302. /**
  22303. * Sets the current geometry buffer for the scene.
  22304. */
  22305. set: function (geometryBufferRenderer) {
  22306. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22307. this._geometryBufferRenderer = geometryBufferRenderer;
  22308. }
  22309. },
  22310. enumerable: true,
  22311. configurable: true
  22312. });
  22313. Object.defineProperty(Scene.prototype, "debugLayer", {
  22314. // Properties
  22315. get: function () {
  22316. if (!this._debugLayer) {
  22317. this._debugLayer = new BABYLON.DebugLayer(this);
  22318. }
  22319. return this._debugLayer;
  22320. },
  22321. enumerable: true,
  22322. configurable: true
  22323. });
  22324. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22325. get: function () {
  22326. return this._workerCollisions;
  22327. },
  22328. set: function (enabled) {
  22329. if (!BABYLON.CollisionCoordinatorLegacy) {
  22330. return;
  22331. }
  22332. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22333. this._workerCollisions = enabled;
  22334. if (this.collisionCoordinator) {
  22335. this.collisionCoordinator.destroy();
  22336. }
  22337. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22338. this.collisionCoordinator.init(this);
  22339. },
  22340. enumerable: true,
  22341. configurable: true
  22342. });
  22343. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22344. get: function () {
  22345. return this._selectionOctree;
  22346. },
  22347. enumerable: true,
  22348. configurable: true
  22349. });
  22350. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22351. /**
  22352. * The mesh that is currently under the pointer.
  22353. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22354. */
  22355. get: function () {
  22356. return this._pointerOverMesh;
  22357. },
  22358. enumerable: true,
  22359. configurable: true
  22360. });
  22361. Object.defineProperty(Scene.prototype, "pointerX", {
  22362. /**
  22363. * Current on-screen X position of the pointer
  22364. * @return {number} X position of the pointer
  22365. */
  22366. get: function () {
  22367. return this._pointerX;
  22368. },
  22369. enumerable: true,
  22370. configurable: true
  22371. });
  22372. Object.defineProperty(Scene.prototype, "pointerY", {
  22373. /**
  22374. * Current on-screen Y position of the pointer
  22375. * @return {number} Y position of the pointer
  22376. */
  22377. get: function () {
  22378. return this._pointerY;
  22379. },
  22380. enumerable: true,
  22381. configurable: true
  22382. });
  22383. Scene.prototype.getCachedMaterial = function () {
  22384. return this._cachedMaterial;
  22385. };
  22386. Scene.prototype.getCachedEffect = function () {
  22387. return this._cachedEffect;
  22388. };
  22389. Scene.prototype.getCachedVisibility = function () {
  22390. return this._cachedVisibility;
  22391. };
  22392. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22393. if (visibility === void 0) { visibility = 1; }
  22394. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22395. };
  22396. Scene.prototype.getBoundingBoxRenderer = function () {
  22397. if (!this._boundingBoxRenderer) {
  22398. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22399. }
  22400. return this._boundingBoxRenderer;
  22401. };
  22402. Scene.prototype.getOutlineRenderer = function () {
  22403. return this._outlineRenderer;
  22404. };
  22405. Scene.prototype.getEngine = function () {
  22406. return this._engine;
  22407. };
  22408. Scene.prototype.getTotalVertices = function () {
  22409. return this._totalVertices.current;
  22410. };
  22411. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22412. get: function () {
  22413. return this._totalVertices;
  22414. },
  22415. enumerable: true,
  22416. configurable: true
  22417. });
  22418. Scene.prototype.getActiveIndices = function () {
  22419. return this._activeIndices.current;
  22420. };
  22421. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22422. get: function () {
  22423. return this._activeIndices;
  22424. },
  22425. enumerable: true,
  22426. configurable: true
  22427. });
  22428. Scene.prototype.getActiveParticles = function () {
  22429. return this._activeParticles.current;
  22430. };
  22431. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22432. get: function () {
  22433. return this._activeParticles;
  22434. },
  22435. enumerable: true,
  22436. configurable: true
  22437. });
  22438. Scene.prototype.getActiveBones = function () {
  22439. return this._activeBones.current;
  22440. };
  22441. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22442. get: function () {
  22443. return this._activeBones;
  22444. },
  22445. enumerable: true,
  22446. configurable: true
  22447. });
  22448. // Stats
  22449. Scene.prototype.getInterFramePerfCounter = function () {
  22450. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22451. return 0;
  22452. };
  22453. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22454. get: function () {
  22455. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22456. return null;
  22457. },
  22458. enumerable: true,
  22459. configurable: true
  22460. });
  22461. Scene.prototype.getLastFrameDuration = function () {
  22462. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22463. return 0;
  22464. };
  22465. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22466. get: function () {
  22467. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22468. return null;
  22469. },
  22470. enumerable: true,
  22471. configurable: true
  22472. });
  22473. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22474. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22475. return 0;
  22476. };
  22477. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22478. get: function () {
  22479. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22480. return null;
  22481. },
  22482. enumerable: true,
  22483. configurable: true
  22484. });
  22485. Scene.prototype.getActiveMeshes = function () {
  22486. return this._activeMeshes;
  22487. };
  22488. Scene.prototype.getRenderTargetsDuration = function () {
  22489. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22490. return 0;
  22491. };
  22492. Scene.prototype.getRenderDuration = function () {
  22493. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22494. return 0;
  22495. };
  22496. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22497. get: function () {
  22498. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22499. return null;
  22500. },
  22501. enumerable: true,
  22502. configurable: true
  22503. });
  22504. Scene.prototype.getParticlesDuration = function () {
  22505. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22506. return 0;
  22507. };
  22508. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22509. get: function () {
  22510. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22511. return null;
  22512. },
  22513. enumerable: true,
  22514. configurable: true
  22515. });
  22516. Scene.prototype.getSpritesDuration = function () {
  22517. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22518. return 0;
  22519. };
  22520. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22521. get: function () {
  22522. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22523. return null;
  22524. },
  22525. enumerable: true,
  22526. configurable: true
  22527. });
  22528. Scene.prototype.getAnimationRatio = function () {
  22529. return this._animationRatio;
  22530. };
  22531. Scene.prototype.getRenderId = function () {
  22532. return this._renderId;
  22533. };
  22534. Scene.prototype.incrementRenderId = function () {
  22535. this._renderId++;
  22536. };
  22537. Scene.prototype._updatePointerPosition = function (evt) {
  22538. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22539. if (!canvasRect) {
  22540. return;
  22541. }
  22542. this._pointerX = evt.clientX - canvasRect.left;
  22543. this._pointerY = evt.clientY - canvasRect.top;
  22544. this._unTranslatedPointerX = this._pointerX;
  22545. this._unTranslatedPointerY = this._pointerY;
  22546. };
  22547. Scene.prototype._createUbo = function () {
  22548. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22549. this._sceneUbo.addUniform("viewProjection", 16);
  22550. this._sceneUbo.addUniform("view", 16);
  22551. };
  22552. Scene.prototype._createAlternateUbo = function () {
  22553. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22554. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22555. this._alternateSceneUbo.addUniform("view", 16);
  22556. };
  22557. // Pointers handling
  22558. /**
  22559. * Use this method to simulate a pointer move on a mesh
  22560. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22561. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22562. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22563. */
  22564. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22565. var evt = new PointerEvent("pointermove", pointerEventInit);
  22566. return this._processPointerMove(pickResult, evt);
  22567. };
  22568. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22569. var canvas = this._engine.getRenderingCanvas();
  22570. if (!canvas) {
  22571. return this;
  22572. }
  22573. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22574. this.setPointerOverSprite(null);
  22575. this.setPointerOverMesh(pickResult.pickedMesh);
  22576. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22577. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22578. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22579. }
  22580. else {
  22581. canvas.style.cursor = this.hoverCursor;
  22582. }
  22583. }
  22584. else {
  22585. canvas.style.cursor = this.defaultCursor;
  22586. }
  22587. }
  22588. else {
  22589. this.setPointerOverMesh(null);
  22590. // Sprites
  22591. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22592. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22593. this.setPointerOverSprite(pickResult.pickedSprite);
  22594. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22595. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22596. }
  22597. else {
  22598. canvas.style.cursor = this.hoverCursor;
  22599. }
  22600. }
  22601. else {
  22602. this.setPointerOverSprite(null);
  22603. // Restore pointer
  22604. canvas.style.cursor = this.defaultCursor;
  22605. }
  22606. }
  22607. if (pickResult) {
  22608. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22609. if (this.onPointerMove) {
  22610. this.onPointerMove(evt, pickResult, type);
  22611. }
  22612. if (this.onPointerObservable.hasObservers()) {
  22613. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22614. this.onPointerObservable.notifyObservers(pi, type);
  22615. }
  22616. }
  22617. return this;
  22618. };
  22619. /**
  22620. * Use this method to simulate a pointer down on a mesh
  22621. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22622. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22623. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22624. */
  22625. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22626. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22627. return this._processPointerDown(pickResult, evt);
  22628. };
  22629. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22630. var _this = this;
  22631. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22632. this._pickedDownMesh = pickResult.pickedMesh;
  22633. var actionManager = pickResult.pickedMesh.actionManager;
  22634. if (actionManager) {
  22635. if (actionManager.hasPickTriggers) {
  22636. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22637. switch (evt.button) {
  22638. case 0:
  22639. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22640. break;
  22641. case 1:
  22642. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22643. break;
  22644. case 2:
  22645. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22646. break;
  22647. }
  22648. }
  22649. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22650. window.setTimeout(function () {
  22651. 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);
  22652. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22653. if (_this._totalPointersPressed !== 0 &&
  22654. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22655. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22656. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22657. _this._startingPointerTime = 0;
  22658. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22659. }
  22660. }
  22661. }, Scene.LongPressDelay);
  22662. }
  22663. }
  22664. }
  22665. if (pickResult) {
  22666. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22667. if (this.onPointerDown) {
  22668. this.onPointerDown(evt, pickResult, type);
  22669. }
  22670. if (this.onPointerObservable.hasObservers()) {
  22671. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22672. this.onPointerObservable.notifyObservers(pi, type);
  22673. }
  22674. }
  22675. return this;
  22676. };
  22677. /**
  22678. * Use this method to simulate a pointer up on a mesh
  22679. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22680. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22681. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22682. */
  22683. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22684. var evt = new PointerEvent("pointerup", pointerEventInit);
  22685. var clickInfo = new ClickInfo();
  22686. clickInfo.singleClick = true;
  22687. clickInfo.ignore = true;
  22688. return this._processPointerUp(pickResult, evt, clickInfo);
  22689. };
  22690. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22691. if (pickResult && pickResult && pickResult.pickedMesh) {
  22692. this._pickedUpMesh = pickResult.pickedMesh;
  22693. if (this._pickedDownMesh === this._pickedUpMesh) {
  22694. if (this.onPointerPick) {
  22695. this.onPointerPick(evt, pickResult);
  22696. }
  22697. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22698. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22699. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22700. this.onPointerObservable.notifyObservers(pi, type_1);
  22701. }
  22702. }
  22703. if (pickResult.pickedMesh.actionManager) {
  22704. if (clickInfo.ignore) {
  22705. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22706. }
  22707. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22708. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22709. }
  22710. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22711. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22712. }
  22713. }
  22714. }
  22715. if (this._pickedDownMesh &&
  22716. this._pickedDownMesh.actionManager &&
  22717. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22718. this._pickedDownMesh !== this._pickedUpMesh) {
  22719. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22720. }
  22721. var type = BABYLON.PointerEventTypes.POINTERUP;
  22722. if (this.onPointerObservable.hasObservers()) {
  22723. if (!clickInfo.ignore) {
  22724. if (!clickInfo.hasSwiped) {
  22725. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22726. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22727. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22728. this.onPointerObservable.notifyObservers(pi, type_2);
  22729. }
  22730. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22731. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22732. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22733. this.onPointerObservable.notifyObservers(pi, type_3);
  22734. }
  22735. }
  22736. }
  22737. else {
  22738. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22739. this.onPointerObservable.notifyObservers(pi, type);
  22740. }
  22741. }
  22742. if (this.onPointerUp) {
  22743. this.onPointerUp(evt, pickResult, type);
  22744. }
  22745. return this;
  22746. };
  22747. /**
  22748. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22749. * @param attachUp defines if you want to attach events to pointerup
  22750. * @param attachDown defines if you want to attach events to pointerdown
  22751. * @param attachMove defines if you want to attach events to pointermove
  22752. */
  22753. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22754. var _this = this;
  22755. if (attachUp === void 0) { attachUp = true; }
  22756. if (attachDown === void 0) { attachDown = true; }
  22757. if (attachMove === void 0) { attachMove = true; }
  22758. this._initActionManager = function (act, clickInfo) {
  22759. if (!_this._meshPickProceed) {
  22760. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22761. _this._currentPickResult = pickResult;
  22762. if (pickResult) {
  22763. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22764. }
  22765. _this._meshPickProceed = true;
  22766. }
  22767. return act;
  22768. };
  22769. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22770. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22771. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22772. btn !== _this._previousButtonPressed) {
  22773. _this._doubleClickOccured = false;
  22774. clickInfo.singleClick = true;
  22775. clickInfo.ignore = false;
  22776. cb(clickInfo, _this._currentPickResult);
  22777. }
  22778. };
  22779. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22780. var clickInfo = new ClickInfo();
  22781. _this._currentPickResult = null;
  22782. var act = null;
  22783. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22784. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22785. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22786. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22787. act = _this._initActionManager(act, clickInfo);
  22788. if (act)
  22789. checkPicking = act.hasPickTriggers;
  22790. }
  22791. if (checkPicking) {
  22792. var btn = evt.button;
  22793. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22794. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22795. if (!clickInfo.hasSwiped) {
  22796. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22797. if (!checkSingleClickImmediately) {
  22798. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22799. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22800. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22801. act = _this._initActionManager(act, clickInfo);
  22802. if (act)
  22803. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22804. }
  22805. }
  22806. if (checkSingleClickImmediately) {
  22807. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22808. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22809. btn !== _this._previousButtonPressed) {
  22810. clickInfo.singleClick = true;
  22811. cb(clickInfo, _this._currentPickResult);
  22812. }
  22813. }
  22814. else {
  22815. // wait that no double click has been raised during the double click delay
  22816. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22817. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22818. }
  22819. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22820. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22821. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22822. act = _this._initActionManager(act, clickInfo);
  22823. if (act)
  22824. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22825. }
  22826. if (checkDoubleClick) {
  22827. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22828. if (btn === _this._previousButtonPressed &&
  22829. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22830. !_this._doubleClickOccured) {
  22831. // pointer has not moved for 2 clicks, it's a double click
  22832. if (!clickInfo.hasSwiped &&
  22833. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22834. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22835. _this._previousStartingPointerTime = 0;
  22836. _this._doubleClickOccured = true;
  22837. clickInfo.doubleClick = true;
  22838. clickInfo.ignore = false;
  22839. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22840. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22841. }
  22842. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22843. cb(clickInfo, _this._currentPickResult);
  22844. }
  22845. else {
  22846. _this._doubleClickOccured = false;
  22847. _this._previousStartingPointerTime = _this._startingPointerTime;
  22848. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22849. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22850. _this._previousButtonPressed = btn;
  22851. if (Scene.ExclusiveDoubleClickMode) {
  22852. if (_this._previousDelayedSimpleClickTimeout) {
  22853. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22854. }
  22855. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22856. cb(clickInfo, _this._previousPickResult);
  22857. }
  22858. else {
  22859. cb(clickInfo, _this._currentPickResult);
  22860. }
  22861. }
  22862. }
  22863. else {
  22864. _this._doubleClickOccured = false;
  22865. _this._previousStartingPointerTime = _this._startingPointerTime;
  22866. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22867. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22868. _this._previousButtonPressed = btn;
  22869. }
  22870. }
  22871. }
  22872. }
  22873. clickInfo.ignore = true;
  22874. cb(clickInfo, _this._currentPickResult);
  22875. };
  22876. this._spritePredicate = function (sprite) {
  22877. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22878. };
  22879. this._onPointerMove = function (evt) {
  22880. _this._updatePointerPosition(evt);
  22881. // PreObservable support
  22882. if (_this.onPrePointerObservable.hasObservers()) {
  22883. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22884. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22885. _this.onPrePointerObservable.notifyObservers(pi, type);
  22886. if (pi.skipOnPointerObservable) {
  22887. return;
  22888. }
  22889. }
  22890. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22891. return;
  22892. }
  22893. if (!_this.pointerMovePredicate) {
  22894. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22895. }
  22896. // Meshes
  22897. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22898. _this._processPointerMove(pickResult, evt);
  22899. };
  22900. this._onPointerDown = function (evt) {
  22901. _this._totalPointersPressed++;
  22902. _this._pickedDownMesh = null;
  22903. _this._meshPickProceed = false;
  22904. _this._updatePointerPosition(evt);
  22905. if (_this.preventDefaultOnPointerDown && canvas) {
  22906. evt.preventDefault();
  22907. canvas.focus();
  22908. }
  22909. // PreObservable support
  22910. if (_this.onPrePointerObservable.hasObservers()) {
  22911. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22912. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22913. _this.onPrePointerObservable.notifyObservers(pi, type);
  22914. if (pi.skipOnPointerObservable) {
  22915. return;
  22916. }
  22917. }
  22918. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22919. return;
  22920. }
  22921. _this._startingPointerPosition.x = _this._pointerX;
  22922. _this._startingPointerPosition.y = _this._pointerY;
  22923. _this._startingPointerTime = new Date().getTime();
  22924. if (!_this.pointerDownPredicate) {
  22925. _this.pointerDownPredicate = function (mesh) {
  22926. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22927. };
  22928. }
  22929. // Meshes
  22930. _this._pickedDownMesh = null;
  22931. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22932. _this._processPointerDown(pickResult, evt);
  22933. // Sprites
  22934. _this._pickedDownSprite = null;
  22935. if (_this.spriteManagers.length > 0) {
  22936. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22937. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22938. if (pickResult.pickedSprite.actionManager) {
  22939. _this._pickedDownSprite = pickResult.pickedSprite;
  22940. switch (evt.button) {
  22941. case 0:
  22942. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22943. break;
  22944. case 1:
  22945. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22946. break;
  22947. case 2:
  22948. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22949. break;
  22950. }
  22951. if (pickResult.pickedSprite.actionManager) {
  22952. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22953. }
  22954. }
  22955. }
  22956. }
  22957. };
  22958. this._onPointerUp = function (evt) {
  22959. if (_this._totalPointersPressed === 0) {
  22960. return; // So we need to test it the pointer down was pressed before.
  22961. }
  22962. _this._totalPointersPressed--;
  22963. _this._pickedUpMesh = null;
  22964. _this._meshPickProceed = false;
  22965. _this._updatePointerPosition(evt);
  22966. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22967. // PreObservable support
  22968. if (_this.onPrePointerObservable.hasObservers()) {
  22969. if (!clickInfo.ignore) {
  22970. if (!clickInfo.hasSwiped) {
  22971. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22972. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22973. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22974. _this.onPrePointerObservable.notifyObservers(pi, type);
  22975. if (pi.skipOnPointerObservable) {
  22976. return;
  22977. }
  22978. }
  22979. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22980. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22981. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22982. _this.onPrePointerObservable.notifyObservers(pi, type);
  22983. if (pi.skipOnPointerObservable) {
  22984. return;
  22985. }
  22986. }
  22987. }
  22988. }
  22989. else {
  22990. var type = BABYLON.PointerEventTypes.POINTERUP;
  22991. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22992. _this.onPrePointerObservable.notifyObservers(pi, type);
  22993. if (pi.skipOnPointerObservable) {
  22994. return;
  22995. }
  22996. }
  22997. }
  22998. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22999. return;
  23000. }
  23001. if (!_this.pointerUpPredicate) {
  23002. _this.pointerUpPredicate = function (mesh) {
  23003. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23004. };
  23005. }
  23006. // Meshes
  23007. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23008. _this._initActionManager(null, clickInfo);
  23009. }
  23010. if (!pickResult) {
  23011. pickResult = _this._currentPickResult;
  23012. }
  23013. _this._processPointerUp(pickResult, evt, clickInfo);
  23014. // Sprites
  23015. if (_this.spriteManagers.length > 0) {
  23016. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23017. if (spritePickResult) {
  23018. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23019. if (spritePickResult.pickedSprite.actionManager) {
  23020. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23021. if (spritePickResult.pickedSprite.actionManager) {
  23022. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23023. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23024. }
  23025. }
  23026. }
  23027. }
  23028. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23029. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23030. }
  23031. }
  23032. }
  23033. _this._previousPickResult = _this._currentPickResult;
  23034. });
  23035. };
  23036. this._onKeyDown = function (evt) {
  23037. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23038. if (_this.onPreKeyboardObservable.hasObservers()) {
  23039. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23040. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23041. if (pi.skipOnPointerObservable) {
  23042. return;
  23043. }
  23044. }
  23045. if (_this.onKeyboardObservable.hasObservers()) {
  23046. var pi = new BABYLON.KeyboardInfo(type, evt);
  23047. _this.onKeyboardObservable.notifyObservers(pi, type);
  23048. }
  23049. if (_this.actionManager) {
  23050. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23051. }
  23052. };
  23053. this._onKeyUp = function (evt) {
  23054. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23055. if (_this.onPreKeyboardObservable.hasObservers()) {
  23056. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23057. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23058. if (pi.skipOnPointerObservable) {
  23059. return;
  23060. }
  23061. }
  23062. if (_this.onKeyboardObservable.hasObservers()) {
  23063. var pi = new BABYLON.KeyboardInfo(type, evt);
  23064. _this.onKeyboardObservable.notifyObservers(pi, type);
  23065. }
  23066. if (_this.actionManager) {
  23067. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23068. }
  23069. };
  23070. var engine = this.getEngine();
  23071. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23072. if (!canvas) {
  23073. return;
  23074. }
  23075. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23076. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23077. });
  23078. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23079. if (!canvas) {
  23080. return;
  23081. }
  23082. canvas.removeEventListener("keydown", _this._onKeyDown);
  23083. canvas.removeEventListener("keyup", _this._onKeyUp);
  23084. });
  23085. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23086. var canvas = this._engine.getRenderingCanvas();
  23087. if (!canvas) {
  23088. return;
  23089. }
  23090. if (attachMove) {
  23091. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23092. // Wheel
  23093. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23094. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23095. }
  23096. if (attachDown) {
  23097. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23098. }
  23099. if (attachUp) {
  23100. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23101. }
  23102. canvas.tabIndex = 1;
  23103. };
  23104. Scene.prototype.detachControl = function () {
  23105. var engine = this.getEngine();
  23106. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23107. var canvas = engine.getRenderingCanvas();
  23108. if (!canvas) {
  23109. return;
  23110. }
  23111. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23112. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23113. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23114. if (this._onCanvasBlurObserver) {
  23115. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23116. }
  23117. if (this._onCanvasFocusObserver) {
  23118. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23119. }
  23120. // Wheel
  23121. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23122. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23123. // Keyboard
  23124. canvas.removeEventListener("keydown", this._onKeyDown);
  23125. canvas.removeEventListener("keyup", this._onKeyUp);
  23126. // Observables
  23127. this.onKeyboardObservable.clear();
  23128. this.onPreKeyboardObservable.clear();
  23129. this.onPointerObservable.clear();
  23130. this.onPrePointerObservable.clear();
  23131. };
  23132. /**
  23133. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23134. * Delay loaded resources are not taking in account
  23135. * @return true if all required resources are ready
  23136. */
  23137. Scene.prototype.isReady = function () {
  23138. if (this._isDisposed) {
  23139. return false;
  23140. }
  23141. if (this._pendingData.length > 0) {
  23142. return false;
  23143. }
  23144. var index;
  23145. var engine = this.getEngine();
  23146. // Geometries
  23147. for (index = 0; index < this._geometries.length; index++) {
  23148. var geometry = this._geometries[index];
  23149. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23150. return false;
  23151. }
  23152. }
  23153. // Meshes
  23154. for (index = 0; index < this.meshes.length; index++) {
  23155. var mesh = this.meshes[index];
  23156. if (!mesh.isEnabled()) {
  23157. continue;
  23158. }
  23159. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23160. continue;
  23161. }
  23162. if (!mesh.isReady(true)) {
  23163. return false;
  23164. }
  23165. // Effect layers
  23166. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23167. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23168. var layer = _a[_i];
  23169. if (!layer.hasMesh(mesh)) {
  23170. continue;
  23171. }
  23172. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23173. var subMesh = _c[_b];
  23174. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23175. return false;
  23176. }
  23177. }
  23178. }
  23179. }
  23180. // Particles
  23181. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23182. var particleSystem = _e[_d];
  23183. if (!particleSystem.isReady()) {
  23184. return false;
  23185. }
  23186. }
  23187. return true;
  23188. };
  23189. Scene.prototype.resetCachedMaterial = function () {
  23190. this._cachedMaterial = null;
  23191. this._cachedEffect = null;
  23192. this._cachedVisibility = null;
  23193. };
  23194. Scene.prototype.registerBeforeRender = function (func) {
  23195. this.onBeforeRenderObservable.add(func);
  23196. };
  23197. Scene.prototype.unregisterBeforeRender = function (func) {
  23198. this.onBeforeRenderObservable.removeCallback(func);
  23199. };
  23200. Scene.prototype.registerAfterRender = function (func) {
  23201. this.onAfterRenderObservable.add(func);
  23202. };
  23203. Scene.prototype.unregisterAfterRender = function (func) {
  23204. this.onAfterRenderObservable.removeCallback(func);
  23205. };
  23206. Scene.prototype._executeOnceBeforeRender = function (func) {
  23207. var _this = this;
  23208. var execFunc = function () {
  23209. func();
  23210. setTimeout(function () {
  23211. _this.unregisterBeforeRender(execFunc);
  23212. });
  23213. };
  23214. this.registerBeforeRender(execFunc);
  23215. };
  23216. /**
  23217. * The provided function will run before render once and will be disposed afterwards.
  23218. * A timeout delay can be provided so that the function will be executed in N ms.
  23219. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23220. * @param func The function to be executed.
  23221. * @param timeout optional delay in ms
  23222. */
  23223. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23224. var _this = this;
  23225. if (timeout !== undefined) {
  23226. setTimeout(function () {
  23227. _this._executeOnceBeforeRender(func);
  23228. }, timeout);
  23229. }
  23230. else {
  23231. this._executeOnceBeforeRender(func);
  23232. }
  23233. };
  23234. Scene.prototype._addPendingData = function (data) {
  23235. this._pendingData.push(data);
  23236. };
  23237. Scene.prototype._removePendingData = function (data) {
  23238. var wasLoading = this.isLoading;
  23239. var index = this._pendingData.indexOf(data);
  23240. if (index !== -1) {
  23241. this._pendingData.splice(index, 1);
  23242. }
  23243. if (wasLoading && !this.isLoading) {
  23244. this.onDataLoadedObservable.notifyObservers(this);
  23245. }
  23246. };
  23247. Scene.prototype.getWaitingItemsCount = function () {
  23248. return this._pendingData.length;
  23249. };
  23250. Object.defineProperty(Scene.prototype, "isLoading", {
  23251. get: function () {
  23252. return this._pendingData.length > 0;
  23253. },
  23254. enumerable: true,
  23255. configurable: true
  23256. });
  23257. /**
  23258. * Registers a function to be executed when the scene is ready.
  23259. * @param {Function} func - the function to be executed.
  23260. */
  23261. Scene.prototype.executeWhenReady = function (func) {
  23262. var _this = this;
  23263. this.onReadyObservable.add(func);
  23264. if (this._executeWhenReadyTimeoutId !== -1) {
  23265. return;
  23266. }
  23267. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23268. _this._checkIsReady();
  23269. }, 150);
  23270. };
  23271. /**
  23272. * Returns a promise that resolves when the scene is ready.
  23273. * @returns A promise that resolves when the scene is ready.
  23274. */
  23275. Scene.prototype.whenReadyAsync = function () {
  23276. var _this = this;
  23277. return new Promise(function (resolve) {
  23278. _this.executeWhenReady(function () {
  23279. resolve();
  23280. });
  23281. });
  23282. };
  23283. Scene.prototype._checkIsReady = function () {
  23284. var _this = this;
  23285. if (this.isReady()) {
  23286. this.onReadyObservable.notifyObservers(this);
  23287. this.onReadyObservable.clear();
  23288. this._executeWhenReadyTimeoutId = -1;
  23289. return;
  23290. }
  23291. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23292. _this._checkIsReady();
  23293. }, 150);
  23294. };
  23295. // Animations
  23296. /**
  23297. * Will start the animation sequence of a given target
  23298. * @param target defines the target
  23299. * @param from defines from which frame should animation start
  23300. * @param to defines until which frame should animation run.
  23301. * @param weight defines the weight to apply to the animation (1.0 by default)
  23302. * @param loop defines if the animation loops
  23303. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23304. * @param onAnimationEnd defines the function to be executed when the animation ends
  23305. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23306. * @returns the animatable object created for this animation
  23307. * @see BABYLON.Animatable
  23308. */
  23309. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23310. if (weight === void 0) { weight = 1.0; }
  23311. if (speedRatio === void 0) { speedRatio = 1.0; }
  23312. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23313. returnedAnimatable.weight = weight;
  23314. return returnedAnimatable;
  23315. };
  23316. /**
  23317. * Will start the animation sequence of a given target
  23318. * @param target defines the target
  23319. * @param from defines from which frame should animation start
  23320. * @param to defines until which frame should animation run.
  23321. * @param loop defines if the animation loops
  23322. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23323. * @param onAnimationEnd defines the function to be executed when the animation ends
  23324. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23325. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23326. * @returns the animatable object created for this animation
  23327. * @see BABYLON.Animatable
  23328. */
  23329. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23330. if (speedRatio === void 0) { speedRatio = 1.0; }
  23331. if (stopCurrent === void 0) { stopCurrent = true; }
  23332. if (from > to && speedRatio > 0) {
  23333. speedRatio *= -1;
  23334. }
  23335. if (stopCurrent) {
  23336. this.stopAnimation(target);
  23337. }
  23338. if (!animatable) {
  23339. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23340. }
  23341. // Local animations
  23342. if (target.animations) {
  23343. animatable.appendAnimations(target, target.animations);
  23344. }
  23345. // Children animations
  23346. if (target.getAnimatables) {
  23347. var animatables = target.getAnimatables();
  23348. for (var index = 0; index < animatables.length; index++) {
  23349. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23350. }
  23351. }
  23352. if (stopCurrent) {
  23353. animatable.reset();
  23354. }
  23355. return animatable;
  23356. };
  23357. /**
  23358. * Begin a new animation on a given node
  23359. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23360. * @param {BABYLON.Animation[]} defines the list of animations to start
  23361. * @param {number} from defines the initial value
  23362. * @param {number} to defines the final value
  23363. * @param {boolean} loop defines if you want animation to loop (off by default)
  23364. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23365. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23366. * @returns the list of created animatables
  23367. */
  23368. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23369. if (speedRatio === undefined) {
  23370. speedRatio = 1.0;
  23371. }
  23372. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23373. return animatable;
  23374. };
  23375. /**
  23376. * Begin a new animation on a given node and its hierarchy
  23377. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23378. * @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.
  23379. * @param {BABYLON.Animation[]} defines the list of animations to start
  23380. * @param {number} from defines the initial value
  23381. * @param {number} to defines the final value
  23382. * @param {boolean} loop defines if you want animation to loop (off by default)
  23383. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23384. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23385. * @returns the list of animatables created for all nodes
  23386. */
  23387. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23388. var children = target.getDescendants(directDescendantsOnly);
  23389. var result = [];
  23390. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23391. var child = children_1[_i];
  23392. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23393. }
  23394. return result;
  23395. };
  23396. Scene.prototype.getAnimatableByTarget = function (target) {
  23397. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23398. if (this._activeAnimatables[index].target === target) {
  23399. return this._activeAnimatables[index];
  23400. }
  23401. }
  23402. return null;
  23403. };
  23404. Object.defineProperty(Scene.prototype, "animatables", {
  23405. get: function () {
  23406. return this._activeAnimatables;
  23407. },
  23408. enumerable: true,
  23409. configurable: true
  23410. });
  23411. /**
  23412. * Will stop the animation of the given target
  23413. * @param target - the target
  23414. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23415. * @see beginAnimation
  23416. */
  23417. Scene.prototype.stopAnimation = function (target, animationName) {
  23418. var animatable = this.getAnimatableByTarget(target);
  23419. if (animatable) {
  23420. animatable.stop(animationName);
  23421. }
  23422. };
  23423. /**
  23424. * Stops and removes all animations that have been applied to the scene
  23425. */
  23426. Scene.prototype.stopAllAnimations = function () {
  23427. if (this._activeAnimatables) {
  23428. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23429. this._activeAnimatables[i].stop();
  23430. }
  23431. this._activeAnimatables = [];
  23432. }
  23433. };
  23434. Scene.prototype._animate = function () {
  23435. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23436. return;
  23437. }
  23438. // Getting time
  23439. var now = BABYLON.Tools.Now;
  23440. if (!this._animationTimeLast) {
  23441. if (this._pendingData.length > 0) {
  23442. return;
  23443. }
  23444. this._animationTimeLast = now;
  23445. }
  23446. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23447. this._animationTime += deltaTime;
  23448. this._animationTimeLast = now;
  23449. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23450. this._activeAnimatables[index]._animate(this._animationTime);
  23451. }
  23452. // Late animation bindings
  23453. this._processLateAnimationBindings();
  23454. };
  23455. /** @ignore */
  23456. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23457. var target = runtimeAnimation.target;
  23458. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23459. if (!target._lateAnimationHolders) {
  23460. target._lateAnimationHolders = {};
  23461. }
  23462. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23463. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23464. totalWeight: 0,
  23465. animations: []
  23466. };
  23467. }
  23468. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23469. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23470. };
  23471. Scene.prototype._processLateAnimationBindings = function () {
  23472. if (!this._registeredForLateAnimationBindings.length) {
  23473. return;
  23474. }
  23475. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23476. var target = this._registeredForLateAnimationBindings.data[index];
  23477. for (var path in target._lateAnimationHolders) {
  23478. var holder = target._lateAnimationHolders[path];
  23479. // Sanity check
  23480. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23481. continue;
  23482. }
  23483. var normalizer = 1.0;
  23484. var finalValue = void 0;
  23485. if (holder.totalWeight < 1.0) {
  23486. // We need to mix the original value in
  23487. var originalValue = holder.animations[0].originalValue;
  23488. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23489. }
  23490. else {
  23491. // We need to normalize the weights
  23492. normalizer = holder.totalWeight;
  23493. }
  23494. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23495. var runtimeAnimation = holder.animations[animIndex];
  23496. if (finalValue) {
  23497. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23498. }
  23499. else {
  23500. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23501. }
  23502. }
  23503. runtimeAnimation.target[path] = finalValue;
  23504. }
  23505. target._lateAnimationHolders = {};
  23506. }
  23507. this._registeredForLateAnimationBindings.reset();
  23508. };
  23509. // Matrix
  23510. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23511. this._useAlternateCameraConfiguration = active;
  23512. };
  23513. Scene.prototype.getViewMatrix = function () {
  23514. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23515. };
  23516. Scene.prototype.getProjectionMatrix = function () {
  23517. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23518. };
  23519. Scene.prototype.getTransformMatrix = function () {
  23520. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23521. };
  23522. Scene.prototype.setTransformMatrix = function (view, projection) {
  23523. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23524. return;
  23525. }
  23526. this._viewUpdateFlag = view.updateFlag;
  23527. this._projectionUpdateFlag = projection.updateFlag;
  23528. this._viewMatrix = view;
  23529. this._projectionMatrix = projection;
  23530. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23531. // Update frustum
  23532. if (!this._frustumPlanes) {
  23533. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23534. }
  23535. else {
  23536. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23537. }
  23538. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23539. var otherCamera = this.activeCamera._alternateCamera;
  23540. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23541. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23542. }
  23543. if (this._sceneUbo.useUbo) {
  23544. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23545. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23546. this._sceneUbo.update();
  23547. }
  23548. };
  23549. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23550. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23551. return;
  23552. }
  23553. this._alternateViewUpdateFlag = view.updateFlag;
  23554. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23555. this._alternateViewMatrix = view;
  23556. this._alternateProjectionMatrix = projection;
  23557. if (!this._alternateTransformMatrix) {
  23558. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23559. }
  23560. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23561. if (!this._alternateSceneUbo) {
  23562. this._createAlternateUbo();
  23563. }
  23564. if (this._alternateSceneUbo.useUbo) {
  23565. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23566. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23567. this._alternateSceneUbo.update();
  23568. }
  23569. };
  23570. Scene.prototype.getSceneUniformBuffer = function () {
  23571. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23572. };
  23573. // Methods
  23574. Scene.prototype.getUniqueId = function () {
  23575. var result = Scene._uniqueIdCounter;
  23576. Scene._uniqueIdCounter++;
  23577. return result;
  23578. };
  23579. Scene.prototype.addMesh = function (newMesh) {
  23580. this.meshes.push(newMesh);
  23581. //notify the collision coordinator
  23582. if (this.collisionCoordinator) {
  23583. this.collisionCoordinator.onMeshAdded(newMesh);
  23584. }
  23585. newMesh._resyncLightSources();
  23586. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23587. };
  23588. Scene.prototype.removeMesh = function (toRemove) {
  23589. var index = this.meshes.indexOf(toRemove);
  23590. if (index !== -1) {
  23591. // Remove from the scene if mesh found
  23592. this.meshes.splice(index, 1);
  23593. }
  23594. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23595. return index;
  23596. };
  23597. Scene.prototype.addTransformNode = function (newTransformNode) {
  23598. this.transformNodes.push(newTransformNode);
  23599. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23600. };
  23601. Scene.prototype.removeTransformNode = function (toRemove) {
  23602. var index = this.transformNodes.indexOf(toRemove);
  23603. if (index !== -1) {
  23604. // Remove from the scene if found
  23605. this.transformNodes.splice(index, 1);
  23606. }
  23607. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23608. return index;
  23609. };
  23610. Scene.prototype.removeSkeleton = function (toRemove) {
  23611. var index = this.skeletons.indexOf(toRemove);
  23612. if (index !== -1) {
  23613. // Remove from the scene if found
  23614. this.skeletons.splice(index, 1);
  23615. }
  23616. return index;
  23617. };
  23618. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23619. var index = this.morphTargetManagers.indexOf(toRemove);
  23620. if (index !== -1) {
  23621. // Remove from the scene if found
  23622. this.morphTargetManagers.splice(index, 1);
  23623. }
  23624. return index;
  23625. };
  23626. Scene.prototype.removeLight = function (toRemove) {
  23627. var index = this.lights.indexOf(toRemove);
  23628. if (index !== -1) {
  23629. // Remove from meshes
  23630. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23631. var mesh = _a[_i];
  23632. mesh._removeLightSource(toRemove);
  23633. }
  23634. // Remove from the scene if mesh found
  23635. this.lights.splice(index, 1);
  23636. this.sortLightsByPriority();
  23637. }
  23638. this.onLightRemovedObservable.notifyObservers(toRemove);
  23639. return index;
  23640. };
  23641. Scene.prototype.removeCamera = function (toRemove) {
  23642. var index = this.cameras.indexOf(toRemove);
  23643. if (index !== -1) {
  23644. // Remove from the scene if mesh found
  23645. this.cameras.splice(index, 1);
  23646. }
  23647. // Remove from activeCameras
  23648. var index2 = this.activeCameras.indexOf(toRemove);
  23649. if (index2 !== -1) {
  23650. // Remove from the scene if mesh found
  23651. this.activeCameras.splice(index2, 1);
  23652. }
  23653. // Reset the activeCamera
  23654. if (this.activeCamera === toRemove) {
  23655. if (this.cameras.length > 0) {
  23656. this.activeCamera = this.cameras[0];
  23657. }
  23658. else {
  23659. this.activeCamera = null;
  23660. }
  23661. }
  23662. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23663. return index;
  23664. };
  23665. Scene.prototype.removeParticleSystem = function (toRemove) {
  23666. var index = this.particleSystems.indexOf(toRemove);
  23667. if (index !== -1) {
  23668. this.particleSystems.splice(index, 1);
  23669. }
  23670. return index;
  23671. };
  23672. ;
  23673. Scene.prototype.removeAnimation = function (toRemove) {
  23674. var index = this.animations.indexOf(toRemove);
  23675. if (index !== -1) {
  23676. this.animations.splice(index, 1);
  23677. }
  23678. return index;
  23679. };
  23680. ;
  23681. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23682. var index = this.multiMaterials.indexOf(toRemove);
  23683. if (index !== -1) {
  23684. this.multiMaterials.splice(index, 1);
  23685. }
  23686. return index;
  23687. };
  23688. ;
  23689. Scene.prototype.removeMaterial = function (toRemove) {
  23690. var index = this.materials.indexOf(toRemove);
  23691. if (index !== -1) {
  23692. this.materials.splice(index, 1);
  23693. }
  23694. return index;
  23695. };
  23696. ;
  23697. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23698. var index = this.lensFlareSystems.indexOf(toRemove);
  23699. if (index !== -1) {
  23700. this.lensFlareSystems.splice(index, 1);
  23701. }
  23702. return index;
  23703. };
  23704. ;
  23705. Scene.prototype.removeActionManager = function (toRemove) {
  23706. var index = this._actionManagers.indexOf(toRemove);
  23707. if (index !== -1) {
  23708. this._actionManagers.splice(index, 1);
  23709. }
  23710. return index;
  23711. };
  23712. ;
  23713. Scene.prototype.addLight = function (newLight) {
  23714. this.lights.push(newLight);
  23715. this.sortLightsByPriority();
  23716. // Add light to all meshes (To support if the light is removed and then readded)
  23717. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23718. var mesh = _a[_i];
  23719. if (mesh._lightSources.indexOf(newLight) === -1) {
  23720. mesh._lightSources.push(newLight);
  23721. mesh._resyncLightSources();
  23722. }
  23723. }
  23724. this.onNewLightAddedObservable.notifyObservers(newLight);
  23725. };
  23726. Scene.prototype.sortLightsByPriority = function () {
  23727. if (this.requireLightSorting) {
  23728. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23729. }
  23730. };
  23731. Scene.prototype.addCamera = function (newCamera) {
  23732. this.cameras.push(newCamera);
  23733. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23734. };
  23735. Scene.prototype.addSkeleton = function (newSkeleton) {
  23736. this.skeletons.push(newSkeleton);
  23737. };
  23738. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23739. this.particleSystems.push(newParticleSystem);
  23740. };
  23741. Scene.prototype.addAnimation = function (newAnimation) {
  23742. this.animations.push(newAnimation);
  23743. };
  23744. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23745. this.multiMaterials.push(newMultiMaterial);
  23746. };
  23747. Scene.prototype.addMaterial = function (newMaterial) {
  23748. this.materials.push(newMaterial);
  23749. };
  23750. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23751. this.morphTargetManagers.push(newMorphTargetManager);
  23752. };
  23753. Scene.prototype.addGeometry = function (newGeometrie) {
  23754. this._geometries.push(newGeometrie);
  23755. };
  23756. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23757. this.lensFlareSystems.push(newLensFlareSystem);
  23758. };
  23759. Scene.prototype.addActionManager = function (newActionManager) {
  23760. this._actionManagers.push(newActionManager);
  23761. };
  23762. /**
  23763. * Switch active camera
  23764. * @param {Camera} newCamera - new active camera
  23765. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23766. */
  23767. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23768. if (attachControl === void 0) { attachControl = true; }
  23769. var canvas = this._engine.getRenderingCanvas();
  23770. if (!canvas) {
  23771. return;
  23772. }
  23773. if (this.activeCamera) {
  23774. this.activeCamera.detachControl(canvas);
  23775. }
  23776. this.activeCamera = newCamera;
  23777. if (attachControl) {
  23778. newCamera.attachControl(canvas);
  23779. }
  23780. };
  23781. /**
  23782. * sets the active camera of the scene using its ID
  23783. * @param {string} id - the camera's ID
  23784. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23785. * @see activeCamera
  23786. */
  23787. Scene.prototype.setActiveCameraByID = function (id) {
  23788. var camera = this.getCameraByID(id);
  23789. if (camera) {
  23790. this.activeCamera = camera;
  23791. return camera;
  23792. }
  23793. return null;
  23794. };
  23795. /**
  23796. * sets the active camera of the scene using its name
  23797. * @param {string} name - the camera's name
  23798. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23799. * @see activeCamera
  23800. */
  23801. Scene.prototype.setActiveCameraByName = function (name) {
  23802. var camera = this.getCameraByName(name);
  23803. if (camera) {
  23804. this.activeCamera = camera;
  23805. return camera;
  23806. }
  23807. return null;
  23808. };
  23809. /**
  23810. * get an animation group using its name
  23811. * @param {string} the material's name
  23812. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23813. */
  23814. Scene.prototype.getAnimationGroupByName = function (name) {
  23815. for (var index = 0; index < this.animationGroups.length; index++) {
  23816. if (this.animationGroups[index].name === name) {
  23817. return this.animationGroups[index];
  23818. }
  23819. }
  23820. return null;
  23821. };
  23822. /**
  23823. * get a material using its id
  23824. * @param {string} the material's ID
  23825. * @return {BABYLON.Material|null} the material or null if none found.
  23826. */
  23827. Scene.prototype.getMaterialByID = function (id) {
  23828. for (var index = 0; index < this.materials.length; index++) {
  23829. if (this.materials[index].id === id) {
  23830. return this.materials[index];
  23831. }
  23832. }
  23833. return null;
  23834. };
  23835. /**
  23836. * get a material using its name
  23837. * @param {string} the material's name
  23838. * @return {BABYLON.Material|null} the material or null if none found.
  23839. */
  23840. Scene.prototype.getMaterialByName = function (name) {
  23841. for (var index = 0; index < this.materials.length; index++) {
  23842. if (this.materials[index].name === name) {
  23843. return this.materials[index];
  23844. }
  23845. }
  23846. return null;
  23847. };
  23848. Scene.prototype.getLensFlareSystemByName = function (name) {
  23849. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23850. if (this.lensFlareSystems[index].name === name) {
  23851. return this.lensFlareSystems[index];
  23852. }
  23853. }
  23854. return null;
  23855. };
  23856. Scene.prototype.getLensFlareSystemByID = function (id) {
  23857. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23858. if (this.lensFlareSystems[index].id === id) {
  23859. return this.lensFlareSystems[index];
  23860. }
  23861. }
  23862. return null;
  23863. };
  23864. Scene.prototype.getCameraByID = function (id) {
  23865. for (var index = 0; index < this.cameras.length; index++) {
  23866. if (this.cameras[index].id === id) {
  23867. return this.cameras[index];
  23868. }
  23869. }
  23870. return null;
  23871. };
  23872. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23873. for (var index = 0; index < this.cameras.length; index++) {
  23874. if (this.cameras[index].uniqueId === uniqueId) {
  23875. return this.cameras[index];
  23876. }
  23877. }
  23878. return null;
  23879. };
  23880. /**
  23881. * get a camera using its name
  23882. * @param {string} the camera's name
  23883. * @return {BABYLON.Camera|null} the camera or null if none found.
  23884. */
  23885. Scene.prototype.getCameraByName = function (name) {
  23886. for (var index = 0; index < this.cameras.length; index++) {
  23887. if (this.cameras[index].name === name) {
  23888. return this.cameras[index];
  23889. }
  23890. }
  23891. return null;
  23892. };
  23893. /**
  23894. * get a bone using its id
  23895. * @param {string} the bone's id
  23896. * @return {BABYLON.Bone|null} the bone or null if not found
  23897. */
  23898. Scene.prototype.getBoneByID = function (id) {
  23899. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23900. var skeleton = this.skeletons[skeletonIndex];
  23901. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23902. if (skeleton.bones[boneIndex].id === id) {
  23903. return skeleton.bones[boneIndex];
  23904. }
  23905. }
  23906. }
  23907. return null;
  23908. };
  23909. /**
  23910. * get a bone using its id
  23911. * @param {string} the bone's name
  23912. * @return {BABYLON.Bone|null} the bone or null if not found
  23913. */
  23914. Scene.prototype.getBoneByName = function (name) {
  23915. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23916. var skeleton = this.skeletons[skeletonIndex];
  23917. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23918. if (skeleton.bones[boneIndex].name === name) {
  23919. return skeleton.bones[boneIndex];
  23920. }
  23921. }
  23922. }
  23923. return null;
  23924. };
  23925. /**
  23926. * get a light node using its name
  23927. * @param {string} the light's name
  23928. * @return {BABYLON.Light|null} the light or null if none found.
  23929. */
  23930. Scene.prototype.getLightByName = function (name) {
  23931. for (var index = 0; index < this.lights.length; index++) {
  23932. if (this.lights[index].name === name) {
  23933. return this.lights[index];
  23934. }
  23935. }
  23936. return null;
  23937. };
  23938. /**
  23939. * get a light node using its ID
  23940. * @param {string} the light's id
  23941. * @return {BABYLON.Light|null} the light or null if none found.
  23942. */
  23943. Scene.prototype.getLightByID = function (id) {
  23944. for (var index = 0; index < this.lights.length; index++) {
  23945. if (this.lights[index].id === id) {
  23946. return this.lights[index];
  23947. }
  23948. }
  23949. return null;
  23950. };
  23951. /**
  23952. * get a light node using its scene-generated unique ID
  23953. * @param {number} the light's unique id
  23954. * @return {BABYLON.Light|null} the light or null if none found.
  23955. */
  23956. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23957. for (var index = 0; index < this.lights.length; index++) {
  23958. if (this.lights[index].uniqueId === uniqueId) {
  23959. return this.lights[index];
  23960. }
  23961. }
  23962. return null;
  23963. };
  23964. /**
  23965. * get a particle system by id
  23966. * @param id {number} the particle system id
  23967. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23968. */
  23969. Scene.prototype.getParticleSystemByID = function (id) {
  23970. for (var index = 0; index < this.particleSystems.length; index++) {
  23971. if (this.particleSystems[index].id === id) {
  23972. return this.particleSystems[index];
  23973. }
  23974. }
  23975. return null;
  23976. };
  23977. /**
  23978. * get a geometry using its ID
  23979. * @param {string} the geometry's id
  23980. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23981. */
  23982. Scene.prototype.getGeometryByID = function (id) {
  23983. for (var index = 0; index < this._geometries.length; index++) {
  23984. if (this._geometries[index].id === id) {
  23985. return this._geometries[index];
  23986. }
  23987. }
  23988. return null;
  23989. };
  23990. /**
  23991. * add a new geometry to this scene.
  23992. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23993. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23994. * @return {boolean} was the geometry added or not
  23995. */
  23996. Scene.prototype.pushGeometry = function (geometry, force) {
  23997. if (!force && this.getGeometryByID(geometry.id)) {
  23998. return false;
  23999. }
  24000. this._geometries.push(geometry);
  24001. //notify the collision coordinator
  24002. if (this.collisionCoordinator) {
  24003. this.collisionCoordinator.onGeometryAdded(geometry);
  24004. }
  24005. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24006. return true;
  24007. };
  24008. /**
  24009. * Removes an existing geometry
  24010. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24011. * @return {boolean} was the geometry removed or not
  24012. */
  24013. Scene.prototype.removeGeometry = function (geometry) {
  24014. var index = this._geometries.indexOf(geometry);
  24015. if (index > -1) {
  24016. this._geometries.splice(index, 1);
  24017. //notify the collision coordinator
  24018. if (this.collisionCoordinator) {
  24019. this.collisionCoordinator.onGeometryDeleted(geometry);
  24020. }
  24021. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24022. return true;
  24023. }
  24024. return false;
  24025. };
  24026. Scene.prototype.getGeometries = function () {
  24027. return this._geometries;
  24028. };
  24029. /**
  24030. * Get the first added mesh found of a given ID
  24031. * @param {string} id - the id to search for
  24032. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24033. */
  24034. Scene.prototype.getMeshByID = function (id) {
  24035. for (var index = 0; index < this.meshes.length; index++) {
  24036. if (this.meshes[index].id === id) {
  24037. return this.meshes[index];
  24038. }
  24039. }
  24040. return null;
  24041. };
  24042. Scene.prototype.getMeshesByID = function (id) {
  24043. return this.meshes.filter(function (m) {
  24044. return m.id === id;
  24045. });
  24046. };
  24047. /**
  24048. * Get the first added transform node found of a given ID
  24049. * @param {string} id - the id to search for
  24050. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24051. */
  24052. Scene.prototype.getTransformNodeByID = function (id) {
  24053. for (var index = 0; index < this.transformNodes.length; index++) {
  24054. if (this.transformNodes[index].id === id) {
  24055. return this.transformNodes[index];
  24056. }
  24057. }
  24058. return null;
  24059. };
  24060. Scene.prototype.getTransformNodesByID = function (id) {
  24061. return this.transformNodes.filter(function (m) {
  24062. return m.id === id;
  24063. });
  24064. };
  24065. /**
  24066. * Get a mesh with its auto-generated unique id
  24067. * @param {number} uniqueId - the unique id to search for
  24068. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24069. */
  24070. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24071. for (var index = 0; index < this.meshes.length; index++) {
  24072. if (this.meshes[index].uniqueId === uniqueId) {
  24073. return this.meshes[index];
  24074. }
  24075. }
  24076. return null;
  24077. };
  24078. /**
  24079. * Get a the last added mesh found of a given ID
  24080. * @param {string} id - the id to search for
  24081. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24082. */
  24083. Scene.prototype.getLastMeshByID = function (id) {
  24084. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24085. if (this.meshes[index].id === id) {
  24086. return this.meshes[index];
  24087. }
  24088. }
  24089. return null;
  24090. };
  24091. /**
  24092. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24093. * @param {string} id - the id to search for
  24094. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24095. */
  24096. Scene.prototype.getLastEntryByID = function (id) {
  24097. var index;
  24098. for (index = this.meshes.length - 1; index >= 0; index--) {
  24099. if (this.meshes[index].id === id) {
  24100. return this.meshes[index];
  24101. }
  24102. }
  24103. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24104. if (this.transformNodes[index].id === id) {
  24105. return this.transformNodes[index];
  24106. }
  24107. }
  24108. for (index = this.cameras.length - 1; index >= 0; index--) {
  24109. if (this.cameras[index].id === id) {
  24110. return this.cameras[index];
  24111. }
  24112. }
  24113. for (index = this.lights.length - 1; index >= 0; index--) {
  24114. if (this.lights[index].id === id) {
  24115. return this.lights[index];
  24116. }
  24117. }
  24118. return null;
  24119. };
  24120. Scene.prototype.getNodeByID = function (id) {
  24121. var mesh = this.getMeshByID(id);
  24122. if (mesh) {
  24123. return mesh;
  24124. }
  24125. var light = this.getLightByID(id);
  24126. if (light) {
  24127. return light;
  24128. }
  24129. var camera = this.getCameraByID(id);
  24130. if (camera) {
  24131. return camera;
  24132. }
  24133. var bone = this.getBoneByID(id);
  24134. return bone;
  24135. };
  24136. Scene.prototype.getNodeByName = function (name) {
  24137. var mesh = this.getMeshByName(name);
  24138. if (mesh) {
  24139. return mesh;
  24140. }
  24141. var light = this.getLightByName(name);
  24142. if (light) {
  24143. return light;
  24144. }
  24145. var camera = this.getCameraByName(name);
  24146. if (camera) {
  24147. return camera;
  24148. }
  24149. var bone = this.getBoneByName(name);
  24150. return bone;
  24151. };
  24152. Scene.prototype.getMeshByName = function (name) {
  24153. for (var index = 0; index < this.meshes.length; index++) {
  24154. if (this.meshes[index].name === name) {
  24155. return this.meshes[index];
  24156. }
  24157. }
  24158. return null;
  24159. };
  24160. Scene.prototype.getTransformNodeByName = function (name) {
  24161. for (var index = 0; index < this.transformNodes.length; index++) {
  24162. if (this.transformNodes[index].name === name) {
  24163. return this.transformNodes[index];
  24164. }
  24165. }
  24166. return null;
  24167. };
  24168. Scene.prototype.getSoundByName = function (name) {
  24169. var index;
  24170. if (BABYLON.AudioEngine) {
  24171. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24172. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24173. return this.mainSoundTrack.soundCollection[index];
  24174. }
  24175. }
  24176. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24177. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24178. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24179. return this.soundTracks[sdIndex].soundCollection[index];
  24180. }
  24181. }
  24182. }
  24183. }
  24184. return null;
  24185. };
  24186. Scene.prototype.getLastSkeletonByID = function (id) {
  24187. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24188. if (this.skeletons[index].id === id) {
  24189. return this.skeletons[index];
  24190. }
  24191. }
  24192. return null;
  24193. };
  24194. Scene.prototype.getSkeletonById = function (id) {
  24195. for (var index = 0; index < this.skeletons.length; index++) {
  24196. if (this.skeletons[index].id === id) {
  24197. return this.skeletons[index];
  24198. }
  24199. }
  24200. return null;
  24201. };
  24202. Scene.prototype.getSkeletonByName = function (name) {
  24203. for (var index = 0; index < this.skeletons.length; index++) {
  24204. if (this.skeletons[index].name === name) {
  24205. return this.skeletons[index];
  24206. }
  24207. }
  24208. return null;
  24209. };
  24210. Scene.prototype.getMorphTargetManagerById = function (id) {
  24211. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24212. if (this.morphTargetManagers[index].uniqueId === id) {
  24213. return this.morphTargetManagers[index];
  24214. }
  24215. }
  24216. return null;
  24217. };
  24218. Scene.prototype.isActiveMesh = function (mesh) {
  24219. return (this._activeMeshes.indexOf(mesh) !== -1);
  24220. };
  24221. /**
  24222. * Return a the first highlight layer of the scene with a given name.
  24223. * @param name The name of the highlight layer to look for.
  24224. * @return The highlight layer if found otherwise null.
  24225. */
  24226. Scene.prototype.getHighlightLayerByName = function (name) {
  24227. for (var index = 0; index < this.effectLayers.length; index++) {
  24228. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24229. return this.effectLayers[index];
  24230. }
  24231. }
  24232. return null;
  24233. };
  24234. /**
  24235. * Return a the first highlight layer of the scene with a given name.
  24236. * @param name The name of the highlight layer to look for.
  24237. * @return The highlight layer if found otherwise null.
  24238. */
  24239. Scene.prototype.getGlowLayerByName = function (name) {
  24240. for (var index = 0; index < this.effectLayers.length; index++) {
  24241. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24242. return this.effectLayers[index];
  24243. }
  24244. }
  24245. return null;
  24246. };
  24247. Object.defineProperty(Scene.prototype, "uid", {
  24248. /**
  24249. * Return a unique id as a string which can serve as an identifier for the scene
  24250. */
  24251. get: function () {
  24252. if (!this._uid) {
  24253. this._uid = BABYLON.Tools.RandomId();
  24254. }
  24255. return this._uid;
  24256. },
  24257. enumerable: true,
  24258. configurable: true
  24259. });
  24260. /**
  24261. * Add an externaly attached data from its key.
  24262. * This method call will fail and return false, if such key already exists.
  24263. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24264. * @param key the unique key that identifies the data
  24265. * @param data the data object to associate to the key for this Engine instance
  24266. * @return true if no such key were already present and the data was added successfully, false otherwise
  24267. */
  24268. Scene.prototype.addExternalData = function (key, data) {
  24269. if (!this._externalData) {
  24270. this._externalData = new BABYLON.StringDictionary();
  24271. }
  24272. return this._externalData.add(key, data);
  24273. };
  24274. /**
  24275. * Get an externaly attached data from its key
  24276. * @param key the unique key that identifies the data
  24277. * @return the associated data, if present (can be null), or undefined if not present
  24278. */
  24279. Scene.prototype.getExternalData = function (key) {
  24280. if (!this._externalData) {
  24281. return null;
  24282. }
  24283. return this._externalData.get(key);
  24284. };
  24285. /**
  24286. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24287. * @param key the unique key that identifies the data
  24288. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24289. * @return the associated data, can be null if the factory returned null.
  24290. */
  24291. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24292. if (!this._externalData) {
  24293. this._externalData = new BABYLON.StringDictionary();
  24294. }
  24295. return this._externalData.getOrAddWithFactory(key, factory);
  24296. };
  24297. /**
  24298. * Remove an externaly attached data from the Engine instance
  24299. * @param key the unique key that identifies the data
  24300. * @return true if the data was successfully removed, false if it doesn't exist
  24301. */
  24302. Scene.prototype.removeExternalData = function (key) {
  24303. return this._externalData.remove(key);
  24304. };
  24305. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24306. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24307. if (mesh.showSubMeshesBoundingBox) {
  24308. var boundingInfo = subMesh.getBoundingInfo();
  24309. if (boundingInfo !== null && boundingInfo !== undefined) {
  24310. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24311. }
  24312. }
  24313. var material = subMesh.getMaterial();
  24314. if (material !== null && material !== undefined) {
  24315. // Render targets
  24316. if (material.getRenderTargetTextures !== undefined) {
  24317. if (this._processedMaterials.indexOf(material) === -1) {
  24318. this._processedMaterials.push(material);
  24319. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24320. }
  24321. }
  24322. // Dispatch
  24323. this._activeIndices.addCount(subMesh.indexCount, false);
  24324. this._renderingManager.dispatch(subMesh, mesh, material);
  24325. }
  24326. }
  24327. };
  24328. /**
  24329. * Clear the processed materials smart array preventing retention point in material dispose.
  24330. */
  24331. Scene.prototype.freeProcessedMaterials = function () {
  24332. this._processedMaterials.dispose();
  24333. };
  24334. /**
  24335. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24336. */
  24337. Scene.prototype.freeActiveMeshes = function () {
  24338. this._activeMeshes.dispose();
  24339. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24340. this.activeCamera._activeMeshes.dispose();
  24341. }
  24342. if (this.activeCameras) {
  24343. for (var i = 0; i < this.activeCameras.length; i++) {
  24344. var activeCamera = this.activeCameras[i];
  24345. if (activeCamera && activeCamera._activeMeshes) {
  24346. activeCamera._activeMeshes.dispose();
  24347. }
  24348. }
  24349. }
  24350. };
  24351. /**
  24352. * Clear the info related to rendering groups preventing retention points during dispose.
  24353. */
  24354. Scene.prototype.freeRenderingGroups = function () {
  24355. if (this._renderingManager) {
  24356. this._renderingManager.freeRenderingGroups();
  24357. }
  24358. if (this.textures) {
  24359. for (var i = 0; i < this.textures.length; i++) {
  24360. var texture = this.textures[i];
  24361. if (texture && texture.renderList) {
  24362. texture.freeRenderingGroups();
  24363. }
  24364. }
  24365. }
  24366. };
  24367. Scene.prototype._isInIntermediateRendering = function () {
  24368. return this._intermediateRendering;
  24369. };
  24370. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24371. this._activeMeshCandidateProvider = provider;
  24372. };
  24373. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24374. return this._activeMeshCandidateProvider;
  24375. };
  24376. /**
  24377. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24378. */
  24379. Scene.prototype.freezeActiveMeshes = function () {
  24380. if (!this.activeCamera) {
  24381. return this;
  24382. }
  24383. if (!this._frustumPlanes) {
  24384. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24385. }
  24386. this._evaluateActiveMeshes();
  24387. this._activeMeshesFrozen = true;
  24388. return this;
  24389. };
  24390. /**
  24391. * Use this function to restart evaluating active meshes on every frame
  24392. */
  24393. Scene.prototype.unfreezeActiveMeshes = function () {
  24394. this._activeMeshesFrozen = false;
  24395. return this;
  24396. };
  24397. Scene.prototype._evaluateActiveMeshes = function () {
  24398. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24399. return;
  24400. }
  24401. if (!this.activeCamera) {
  24402. return;
  24403. }
  24404. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24405. this.activeCamera._activeMeshes.reset();
  24406. this._activeMeshes.reset();
  24407. this._renderingManager.reset();
  24408. this._processedMaterials.reset();
  24409. this._activeParticleSystems.reset();
  24410. this._activeSkeletons.reset();
  24411. this._softwareSkinnedMeshes.reset();
  24412. if (this._boundingBoxRenderer) {
  24413. this._boundingBoxRenderer.reset();
  24414. }
  24415. // Meshes
  24416. var meshes;
  24417. var len;
  24418. var checkIsEnabled = true;
  24419. // Determine mesh candidates
  24420. if (this._activeMeshCandidateProvider !== undefined) {
  24421. // Use _activeMeshCandidateProvider
  24422. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24423. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24424. if (meshes !== undefined) {
  24425. len = meshes.length;
  24426. }
  24427. else {
  24428. len = 0;
  24429. }
  24430. }
  24431. else if (this._selectionOctree !== undefined) {
  24432. // Octree
  24433. var selection = this._selectionOctree.select(this._frustumPlanes);
  24434. meshes = selection.data;
  24435. len = selection.length;
  24436. }
  24437. else {
  24438. // Full scene traversal
  24439. len = this.meshes.length;
  24440. meshes = this.meshes;
  24441. }
  24442. // Check each mesh
  24443. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24444. mesh = meshes[meshIndex];
  24445. if (mesh.isBlocked) {
  24446. continue;
  24447. }
  24448. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24449. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24450. continue;
  24451. }
  24452. mesh.computeWorldMatrix();
  24453. // Intersections
  24454. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24455. this._meshesForIntersections.pushNoDuplicate(mesh);
  24456. }
  24457. // Switch to current LOD
  24458. meshLOD = mesh.getLOD(this.activeCamera);
  24459. if (meshLOD === undefined || meshLOD === null) {
  24460. continue;
  24461. }
  24462. mesh._preActivate();
  24463. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24464. this._activeMeshes.push(mesh);
  24465. this.activeCamera._activeMeshes.push(mesh);
  24466. mesh._activate(this._renderId);
  24467. if (meshLOD !== mesh) {
  24468. meshLOD._activate(this._renderId);
  24469. }
  24470. this._activeMesh(mesh, meshLOD);
  24471. }
  24472. }
  24473. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24474. // Particle systems
  24475. if (this.particlesEnabled) {
  24476. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24477. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24478. var particleSystem = this.particleSystems[particleIndex];
  24479. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24480. continue;
  24481. }
  24482. var emitter = particleSystem.emitter;
  24483. if (!emitter.position || emitter.isEnabled()) {
  24484. this._activeParticleSystems.push(particleSystem);
  24485. particleSystem.animate();
  24486. this._renderingManager.dispatchParticles(particleSystem);
  24487. }
  24488. }
  24489. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24490. }
  24491. };
  24492. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24493. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24494. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24495. mesh.skeleton.prepare();
  24496. }
  24497. if (!mesh.computeBonesUsingShaders) {
  24498. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24499. }
  24500. }
  24501. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24502. var boundingInfo = sourceMesh.getBoundingInfo();
  24503. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24504. }
  24505. if (mesh !== undefined && mesh !== null
  24506. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24507. // Submeshes Octrees
  24508. var len;
  24509. var subMeshes;
  24510. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24511. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24512. len = intersections.length;
  24513. subMeshes = intersections.data;
  24514. }
  24515. else {
  24516. subMeshes = mesh.subMeshes;
  24517. len = subMeshes.length;
  24518. }
  24519. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24520. subMesh = subMeshes[subIndex];
  24521. this._evaluateSubMesh(subMesh, mesh);
  24522. }
  24523. }
  24524. };
  24525. Scene.prototype.updateTransformMatrix = function (force) {
  24526. if (!this.activeCamera) {
  24527. return;
  24528. }
  24529. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24530. };
  24531. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24532. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24533. };
  24534. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24535. if (camera && camera._skipRendering) {
  24536. return;
  24537. }
  24538. var engine = this._engine;
  24539. this.activeCamera = camera;
  24540. if (!this.activeCamera)
  24541. throw new Error("Active camera not set");
  24542. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24543. // Viewport
  24544. engine.setViewport(this.activeCamera.viewport);
  24545. // Camera
  24546. this.resetCachedMaterial();
  24547. this._renderId++;
  24548. this.updateTransformMatrix();
  24549. if (camera._alternateCamera) {
  24550. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24551. this._alternateRendering = true;
  24552. }
  24553. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24554. // Meshes
  24555. this._evaluateActiveMeshes();
  24556. // Software skinning
  24557. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24558. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24559. mesh.applySkeleton(mesh.skeleton);
  24560. }
  24561. // Render targets
  24562. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24563. var needsRestoreFrameBuffer = false;
  24564. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24565. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24566. }
  24567. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24568. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24569. }
  24570. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24571. this._intermediateRendering = true;
  24572. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24573. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24574. var renderTarget = this._renderTargets.data[renderIndex];
  24575. if (renderTarget._shouldRender()) {
  24576. this._renderId++;
  24577. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24578. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24579. }
  24580. }
  24581. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24582. this._intermediateRendering = false;
  24583. this._renderId++;
  24584. needsRestoreFrameBuffer = true; // Restore back buffer
  24585. }
  24586. // Render EffecttLayer Texture
  24587. var stencilState = this._engine.getStencilBuffer();
  24588. var renderEffects = false;
  24589. var needStencil = false;
  24590. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24591. this._intermediateRendering = true;
  24592. for (var i = 0; i < this.effectLayers.length; i++) {
  24593. var effectLayer = this.effectLayers[i];
  24594. if (effectLayer.shouldRender() &&
  24595. (!effectLayer.camera ||
  24596. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24597. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24598. renderEffects = true;
  24599. needStencil = needStencil || effectLayer.needStencil();
  24600. var renderTarget = effectLayer._mainTexture;
  24601. if (renderTarget._shouldRender()) {
  24602. this._renderId++;
  24603. renderTarget.render(false, false);
  24604. needsRestoreFrameBuffer = true;
  24605. }
  24606. }
  24607. }
  24608. this._intermediateRendering = false;
  24609. this._renderId++;
  24610. }
  24611. if (needsRestoreFrameBuffer) {
  24612. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24613. }
  24614. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24615. // Prepare Frame
  24616. this.postProcessManager._prepareFrame();
  24617. // Backgrounds
  24618. var layerIndex;
  24619. var layer;
  24620. if (this.layers.length) {
  24621. engine.setDepthBuffer(false);
  24622. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24623. layer = this.layers[layerIndex];
  24624. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24625. layer.render();
  24626. }
  24627. }
  24628. engine.setDepthBuffer(true);
  24629. }
  24630. // Activate effect Layer stencil
  24631. if (needStencil) {
  24632. this._engine.setStencilBuffer(true);
  24633. }
  24634. // Render
  24635. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24636. this._renderingManager.render(null, null, true, true);
  24637. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24638. // Restore effect Layer stencil
  24639. if (needStencil) {
  24640. this._engine.setStencilBuffer(stencilState);
  24641. }
  24642. // Bounding boxes
  24643. if (this._boundingBoxRenderer) {
  24644. this._boundingBoxRenderer.render();
  24645. }
  24646. // Lens flares
  24647. if (this.lensFlaresEnabled) {
  24648. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24649. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24650. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24651. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24652. lensFlareSystem.render();
  24653. }
  24654. }
  24655. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24656. }
  24657. // Foregrounds
  24658. if (this.layers.length) {
  24659. engine.setDepthBuffer(false);
  24660. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24661. layer = this.layers[layerIndex];
  24662. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24663. layer.render();
  24664. }
  24665. }
  24666. engine.setDepthBuffer(true);
  24667. }
  24668. // Effect Layer
  24669. if (renderEffects) {
  24670. engine.setDepthBuffer(false);
  24671. for (var i = 0; i < this.effectLayers.length; i++) {
  24672. if (this.effectLayers[i].shouldRender()) {
  24673. this.effectLayers[i].render();
  24674. }
  24675. }
  24676. engine.setDepthBuffer(true);
  24677. }
  24678. // Finalize frame
  24679. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24680. // Reset some special arrays
  24681. this._renderTargets.reset();
  24682. this._alternateRendering = false;
  24683. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24684. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24685. };
  24686. Scene.prototype._processSubCameras = function (camera) {
  24687. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24688. this._renderForCamera(camera);
  24689. return;
  24690. }
  24691. // rig cameras
  24692. for (var index = 0; index < camera._rigCameras.length; index++) {
  24693. this._renderForCamera(camera._rigCameras[index], camera);
  24694. }
  24695. this.activeCamera = camera;
  24696. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24697. };
  24698. Scene.prototype._checkIntersections = function () {
  24699. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24700. var sourceMesh = this._meshesForIntersections.data[index];
  24701. if (!sourceMesh.actionManager) {
  24702. continue;
  24703. }
  24704. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24705. var action = sourceMesh.actionManager.actions[actionIndex];
  24706. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24707. var parameters = action.getTriggerParameter();
  24708. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24709. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24710. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24711. if (areIntersecting && currentIntersectionInProgress === -1) {
  24712. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24713. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24714. sourceMesh._intersectionsInProgress.push(otherMesh);
  24715. }
  24716. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24717. sourceMesh._intersectionsInProgress.push(otherMesh);
  24718. }
  24719. }
  24720. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24721. //They intersected, and now they don't.
  24722. //is this trigger an exit trigger? execute an event.
  24723. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24724. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24725. }
  24726. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24727. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24728. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24729. }
  24730. }
  24731. }
  24732. }
  24733. }
  24734. };
  24735. Scene.prototype.render = function () {
  24736. if (this.isDisposed) {
  24737. return;
  24738. }
  24739. this._activeParticles.fetchNewFrame();
  24740. this._totalVertices.fetchNewFrame();
  24741. this._activeIndices.fetchNewFrame();
  24742. this._activeBones.fetchNewFrame();
  24743. this._meshesForIntersections.reset();
  24744. this.resetCachedMaterial();
  24745. this.onBeforeAnimationsObservable.notifyObservers(this);
  24746. // Actions
  24747. if (this.actionManager) {
  24748. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24749. }
  24750. //Simplification Queue
  24751. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24752. this.simplificationQueue.executeNext();
  24753. }
  24754. if (this._engine.isDeterministicLockStep()) {
  24755. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24756. var defaultFPS = (60.0 / 1000.0);
  24757. var defaultFrameTime = 1000 / 60; // frame time in MS
  24758. if (this._physicsEngine) {
  24759. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24760. }
  24761. var stepsTaken = 0;
  24762. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24763. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24764. internalSteps = Math.min(internalSteps, maxSubSteps);
  24765. do {
  24766. this.onBeforeStepObservable.notifyObservers(this);
  24767. // Animations
  24768. this._animationRatio = defaultFrameTime * defaultFPS;
  24769. this._animate();
  24770. this.onAfterAnimationsObservable.notifyObservers(this);
  24771. // Physics
  24772. if (this._physicsEngine) {
  24773. this.onBeforePhysicsObservable.notifyObservers(this);
  24774. this._physicsEngine._step(defaultFrameTime / 1000);
  24775. this.onAfterPhysicsObservable.notifyObservers(this);
  24776. }
  24777. this.onAfterStepObservable.notifyObservers(this);
  24778. this._currentStepId++;
  24779. stepsTaken++;
  24780. deltaTime -= defaultFrameTime;
  24781. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24782. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24783. }
  24784. else {
  24785. // Animations
  24786. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24787. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24788. this._animate();
  24789. this.onAfterAnimationsObservable.notifyObservers(this);
  24790. // Physics
  24791. if (this._physicsEngine) {
  24792. this.onBeforePhysicsObservable.notifyObservers(this);
  24793. this._physicsEngine._step(deltaTime / 1000.0);
  24794. this.onAfterPhysicsObservable.notifyObservers(this);
  24795. }
  24796. }
  24797. // update gamepad manager
  24798. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24799. this._gamepadManager._checkGamepadsStatus();
  24800. }
  24801. // Update Cameras
  24802. if (this.activeCameras.length > 0) {
  24803. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24804. var camera = this.activeCameras[cameraIndex];
  24805. camera.update();
  24806. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24807. // rig cameras
  24808. for (var index = 0; index < camera._rigCameras.length; index++) {
  24809. camera._rigCameras[index].update();
  24810. }
  24811. }
  24812. }
  24813. }
  24814. else if (this.activeCamera) {
  24815. this.activeCamera.update();
  24816. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24817. // rig cameras
  24818. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24819. this.activeCamera._rigCameras[index].update();
  24820. }
  24821. }
  24822. }
  24823. // Before render
  24824. this.onBeforeRenderObservable.notifyObservers(this);
  24825. // Customs render targets
  24826. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24827. var engine = this.getEngine();
  24828. var currentActiveCamera = this.activeCamera;
  24829. if (this.renderTargetsEnabled) {
  24830. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24831. this._intermediateRendering = true;
  24832. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24833. var renderTarget = this.customRenderTargets[customIndex];
  24834. if (renderTarget._shouldRender()) {
  24835. this._renderId++;
  24836. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24837. if (!this.activeCamera)
  24838. throw new Error("Active camera not set");
  24839. // Viewport
  24840. engine.setViewport(this.activeCamera.viewport);
  24841. // Camera
  24842. this.updateTransformMatrix();
  24843. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24844. }
  24845. }
  24846. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24847. this._intermediateRendering = false;
  24848. this._renderId++;
  24849. }
  24850. // Restore back buffer
  24851. if (this.customRenderTargets.length > 0) {
  24852. engine.restoreDefaultFramebuffer();
  24853. }
  24854. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24855. this.activeCamera = currentActiveCamera;
  24856. // Procedural textures
  24857. if (this.proceduralTexturesEnabled) {
  24858. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24859. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24860. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24861. if (proceduralTexture._shouldRender()) {
  24862. proceduralTexture.render();
  24863. }
  24864. }
  24865. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24866. }
  24867. // Clear
  24868. if (this.autoClearDepthAndStencil || this.autoClear) {
  24869. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24870. }
  24871. // Shadows
  24872. if (this.shadowsEnabled) {
  24873. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24874. var light = this.lights[lightIndex];
  24875. var shadowGenerator = light.getShadowGenerator();
  24876. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24877. var shadowMap = (shadowGenerator.getShadowMap());
  24878. if (this.textures.indexOf(shadowMap) !== -1) {
  24879. this._renderTargets.push(shadowMap);
  24880. }
  24881. }
  24882. }
  24883. }
  24884. // Depth renderer
  24885. for (var key in this._depthRenderer) {
  24886. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24887. }
  24888. // Geometry renderer
  24889. if (this._geometryBufferRenderer) {
  24890. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24891. }
  24892. // RenderPipeline
  24893. if (this._postProcessRenderPipelineManager) {
  24894. this._postProcessRenderPipelineManager.update();
  24895. }
  24896. // Multi-cameras?
  24897. if (this.activeCameras.length > 0) {
  24898. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24899. if (cameraIndex > 0) {
  24900. this._engine.clear(null, false, true, true);
  24901. }
  24902. this._processSubCameras(this.activeCameras[cameraIndex]);
  24903. }
  24904. }
  24905. else {
  24906. if (!this.activeCamera) {
  24907. throw new Error("No camera defined");
  24908. }
  24909. this._processSubCameras(this.activeCamera);
  24910. }
  24911. // Intersection checks
  24912. this._checkIntersections();
  24913. // Update the audio listener attached to the camera
  24914. if (BABYLON.AudioEngine) {
  24915. this._updateAudioParameters();
  24916. }
  24917. // After render
  24918. if (this.afterRender) {
  24919. this.afterRender();
  24920. }
  24921. this.onAfterRenderObservable.notifyObservers(this);
  24922. // Cleaning
  24923. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24924. var data = this._toBeDisposed.data[index];
  24925. if (data) {
  24926. data.dispose();
  24927. }
  24928. this._toBeDisposed[index] = null;
  24929. }
  24930. this._toBeDisposed.reset();
  24931. if (this.dumpNextRenderTargets) {
  24932. this.dumpNextRenderTargets = false;
  24933. }
  24934. this._activeBones.addCount(0, true);
  24935. this._activeIndices.addCount(0, true);
  24936. this._activeParticles.addCount(0, true);
  24937. };
  24938. Scene.prototype._updateAudioParameters = function () {
  24939. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24940. return;
  24941. }
  24942. var listeningCamera;
  24943. var audioEngine = BABYLON.Engine.audioEngine;
  24944. if (this.activeCameras.length > 0) {
  24945. listeningCamera = this.activeCameras[0];
  24946. }
  24947. else {
  24948. listeningCamera = this.activeCamera;
  24949. }
  24950. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24951. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24952. // for VR cameras
  24953. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24954. listeningCamera = listeningCamera.rigCameras[0];
  24955. }
  24956. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24957. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24958. cameraDirection.normalize();
  24959. // To avoid some errors on GearVR
  24960. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24961. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24962. }
  24963. var i;
  24964. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24965. var sound = this.mainSoundTrack.soundCollection[i];
  24966. if (sound.useCustomAttenuation) {
  24967. sound.updateDistanceFromListener();
  24968. }
  24969. }
  24970. for (i = 0; i < this.soundTracks.length; i++) {
  24971. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24972. sound = this.soundTracks[i].soundCollection[j];
  24973. if (sound.useCustomAttenuation) {
  24974. sound.updateDistanceFromListener();
  24975. }
  24976. }
  24977. }
  24978. }
  24979. };
  24980. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24981. // Audio
  24982. get: function () {
  24983. return this._audioEnabled;
  24984. },
  24985. set: function (value) {
  24986. this._audioEnabled = value;
  24987. if (BABYLON.AudioEngine) {
  24988. if (this._audioEnabled) {
  24989. this._enableAudio();
  24990. }
  24991. else {
  24992. this._disableAudio();
  24993. }
  24994. }
  24995. },
  24996. enumerable: true,
  24997. configurable: true
  24998. });
  24999. Scene.prototype._disableAudio = function () {
  25000. var i;
  25001. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25002. this.mainSoundTrack.soundCollection[i].pause();
  25003. }
  25004. for (i = 0; i < this.soundTracks.length; i++) {
  25005. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25006. this.soundTracks[i].soundCollection[j].pause();
  25007. }
  25008. }
  25009. };
  25010. Scene.prototype._enableAudio = function () {
  25011. var i;
  25012. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25013. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25014. this.mainSoundTrack.soundCollection[i].play();
  25015. }
  25016. }
  25017. for (i = 0; i < this.soundTracks.length; i++) {
  25018. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25019. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25020. this.soundTracks[i].soundCollection[j].play();
  25021. }
  25022. }
  25023. }
  25024. };
  25025. Object.defineProperty(Scene.prototype, "headphone", {
  25026. get: function () {
  25027. return this._headphone;
  25028. },
  25029. set: function (value) {
  25030. this._headphone = value;
  25031. if (BABYLON.AudioEngine) {
  25032. if (this._headphone) {
  25033. this._switchAudioModeForHeadphones();
  25034. }
  25035. else {
  25036. this._switchAudioModeForNormalSpeakers();
  25037. }
  25038. }
  25039. },
  25040. enumerable: true,
  25041. configurable: true
  25042. });
  25043. Scene.prototype._switchAudioModeForHeadphones = function () {
  25044. this.mainSoundTrack.switchPanningModelToHRTF();
  25045. for (var i = 0; i < this.soundTracks.length; i++) {
  25046. this.soundTracks[i].switchPanningModelToHRTF();
  25047. }
  25048. };
  25049. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25050. this.mainSoundTrack.switchPanningModelToEqualPower();
  25051. for (var i = 0; i < this.soundTracks.length; i++) {
  25052. this.soundTracks[i].switchPanningModelToEqualPower();
  25053. }
  25054. };
  25055. /**
  25056. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25057. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25058. * @returns the created depth renderer
  25059. */
  25060. Scene.prototype.enableDepthRenderer = function (camera) {
  25061. camera = camera || this.activeCamera;
  25062. if (!camera) {
  25063. throw "No camera available to enable depth renderer";
  25064. }
  25065. if (!this._depthRenderer[camera.id]) {
  25066. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25067. }
  25068. return this._depthRenderer[camera.id];
  25069. };
  25070. /**
  25071. * Disables a depth renderer for a given camera
  25072. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25073. */
  25074. Scene.prototype.disableDepthRenderer = function (camera) {
  25075. camera = camera || this.activeCamera;
  25076. if (!camera || !this._depthRenderer[camera.id]) {
  25077. return;
  25078. }
  25079. this._depthRenderer[camera.id].dispose();
  25080. delete this._depthRenderer[camera.id];
  25081. };
  25082. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25083. if (ratio === void 0) { ratio = 1; }
  25084. if (this._geometryBufferRenderer) {
  25085. return this._geometryBufferRenderer;
  25086. }
  25087. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25088. if (!this._geometryBufferRenderer.isSupported) {
  25089. this._geometryBufferRenderer = null;
  25090. }
  25091. return this._geometryBufferRenderer;
  25092. };
  25093. Scene.prototype.disableGeometryBufferRenderer = function () {
  25094. if (!this._geometryBufferRenderer) {
  25095. return;
  25096. }
  25097. this._geometryBufferRenderer.dispose();
  25098. this._geometryBufferRenderer = null;
  25099. };
  25100. Scene.prototype.freezeMaterials = function () {
  25101. for (var i = 0; i < this.materials.length; i++) {
  25102. this.materials[i].freeze();
  25103. }
  25104. };
  25105. Scene.prototype.unfreezeMaterials = function () {
  25106. for (var i = 0; i < this.materials.length; i++) {
  25107. this.materials[i].unfreeze();
  25108. }
  25109. };
  25110. Scene.prototype.dispose = function () {
  25111. this.beforeRender = null;
  25112. this.afterRender = null;
  25113. this.skeletons = [];
  25114. this.morphTargetManagers = [];
  25115. this.importedMeshesFiles = new Array();
  25116. this.stopAllAnimations();
  25117. this.resetCachedMaterial();
  25118. for (var key in this._depthRenderer) {
  25119. this._depthRenderer[key].dispose();
  25120. }
  25121. if (this._gamepadManager) {
  25122. this._gamepadManager.dispose();
  25123. this._gamepadManager = null;
  25124. }
  25125. // Smart arrays
  25126. if (this.activeCamera) {
  25127. this.activeCamera._activeMeshes.dispose();
  25128. this.activeCamera = null;
  25129. }
  25130. this._activeMeshes.dispose();
  25131. this._renderingManager.dispose();
  25132. this._processedMaterials.dispose();
  25133. this._activeParticleSystems.dispose();
  25134. this._activeSkeletons.dispose();
  25135. this._softwareSkinnedMeshes.dispose();
  25136. this._renderTargets.dispose();
  25137. this._registeredForLateAnimationBindings.dispose();
  25138. if (this._boundingBoxRenderer) {
  25139. this._boundingBoxRenderer.dispose();
  25140. }
  25141. this._meshesForIntersections.dispose();
  25142. this._toBeDisposed.dispose();
  25143. // Abort active requests
  25144. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25145. var request = _a[_i];
  25146. request.abort();
  25147. }
  25148. // Debug layer
  25149. if (this._debugLayer) {
  25150. this._debugLayer.hide();
  25151. }
  25152. // Events
  25153. this.onDisposeObservable.notifyObservers(this);
  25154. this.onDisposeObservable.clear();
  25155. this.onBeforeRenderObservable.clear();
  25156. this.onAfterRenderObservable.clear();
  25157. this.OnBeforeRenderTargetsRenderObservable.clear();
  25158. this.OnAfterRenderTargetsRenderObservable.clear();
  25159. this.onAfterStepObservable.clear();
  25160. this.onBeforeStepObservable.clear();
  25161. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25162. this.onAfterActiveMeshesEvaluationObservable.clear();
  25163. this.onBeforeParticlesRenderingObservable.clear();
  25164. this.onAfterParticlesRenderingObservable.clear();
  25165. this.onBeforeSpritesRenderingObservable.clear();
  25166. this.onAfterSpritesRenderingObservable.clear();
  25167. this.onBeforeDrawPhaseObservable.clear();
  25168. this.onAfterDrawPhaseObservable.clear();
  25169. this.onBeforePhysicsObservable.clear();
  25170. this.onAfterPhysicsObservable.clear();
  25171. this.onBeforeAnimationsObservable.clear();
  25172. this.onAfterAnimationsObservable.clear();
  25173. this.onDataLoadedObservable.clear();
  25174. this.detachControl();
  25175. // Release sounds & sounds tracks
  25176. if (BABYLON.AudioEngine) {
  25177. this.disposeSounds();
  25178. }
  25179. // VR Helper
  25180. if (this.VRHelper) {
  25181. this.VRHelper.dispose();
  25182. }
  25183. // Detach cameras
  25184. var canvas = this._engine.getRenderingCanvas();
  25185. if (canvas) {
  25186. var index;
  25187. for (index = 0; index < this.cameras.length; index++) {
  25188. this.cameras[index].detachControl(canvas);
  25189. }
  25190. }
  25191. // Release animation groups
  25192. while (this.animationGroups.length) {
  25193. this.animationGroups[0].dispose();
  25194. }
  25195. // Release lights
  25196. while (this.lights.length) {
  25197. this.lights[0].dispose();
  25198. }
  25199. // Release meshes
  25200. while (this.meshes.length) {
  25201. this.meshes[0].dispose(true);
  25202. }
  25203. while (this.transformNodes.length) {
  25204. this.removeTransformNode(this.transformNodes[0]);
  25205. }
  25206. // Release cameras
  25207. while (this.cameras.length) {
  25208. this.cameras[0].dispose();
  25209. }
  25210. // Release materials
  25211. if (this.defaultMaterial) {
  25212. this.defaultMaterial.dispose();
  25213. }
  25214. while (this.multiMaterials.length) {
  25215. this.multiMaterials[0].dispose();
  25216. }
  25217. while (this.materials.length) {
  25218. this.materials[0].dispose();
  25219. }
  25220. // Release particles
  25221. while (this.particleSystems.length) {
  25222. this.particleSystems[0].dispose();
  25223. }
  25224. // Release sprites
  25225. while (this.spriteManagers.length) {
  25226. this.spriteManagers[0].dispose();
  25227. }
  25228. // Release postProcesses
  25229. while (this.postProcesses.length) {
  25230. this.postProcesses[0].dispose();
  25231. }
  25232. // Release layers
  25233. while (this.layers.length) {
  25234. this.layers[0].dispose();
  25235. }
  25236. while (this.effectLayers.length) {
  25237. this.effectLayers[0].dispose();
  25238. }
  25239. // Release textures
  25240. while (this.textures.length) {
  25241. this.textures[0].dispose();
  25242. }
  25243. // Release UBO
  25244. this._sceneUbo.dispose();
  25245. if (this._alternateSceneUbo) {
  25246. this._alternateSceneUbo.dispose();
  25247. }
  25248. // Post-processes
  25249. this.postProcessManager.dispose();
  25250. if (this._postProcessRenderPipelineManager) {
  25251. this._postProcessRenderPipelineManager.dispose();
  25252. }
  25253. // Physics
  25254. if (this._physicsEngine) {
  25255. this.disablePhysicsEngine();
  25256. }
  25257. // Remove from engine
  25258. index = this._engine.scenes.indexOf(this);
  25259. if (index > -1) {
  25260. this._engine.scenes.splice(index, 1);
  25261. }
  25262. this._engine.wipeCaches(true);
  25263. this._isDisposed = true;
  25264. };
  25265. Object.defineProperty(Scene.prototype, "isDisposed", {
  25266. get: function () {
  25267. return this._isDisposed;
  25268. },
  25269. enumerable: true,
  25270. configurable: true
  25271. });
  25272. // Release sounds & sounds tracks
  25273. Scene.prototype.disposeSounds = function () {
  25274. if (!this._mainSoundTrack) {
  25275. return;
  25276. }
  25277. this.mainSoundTrack.dispose();
  25278. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25279. this.soundTracks[scIndex].dispose();
  25280. }
  25281. };
  25282. // Octrees
  25283. /**
  25284. * Get the world extend vectors with an optional filter
  25285. *
  25286. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25287. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25288. */
  25289. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25290. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25291. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25292. filterPredicate = filterPredicate || (function () { return true; });
  25293. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25294. mesh.computeWorldMatrix(true);
  25295. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25296. return;
  25297. }
  25298. var boundingInfo = mesh.getBoundingInfo();
  25299. var minBox = boundingInfo.boundingBox.minimumWorld;
  25300. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25301. BABYLON.Tools.CheckExtends(minBox, min, max);
  25302. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25303. });
  25304. return {
  25305. min: min,
  25306. max: max
  25307. };
  25308. };
  25309. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25310. if (maxCapacity === void 0) { maxCapacity = 64; }
  25311. if (maxDepth === void 0) { maxDepth = 2; }
  25312. if (!this._selectionOctree) {
  25313. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25314. }
  25315. var worldExtends = this.getWorldExtends();
  25316. // Update octree
  25317. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25318. return this._selectionOctree;
  25319. };
  25320. // Picking
  25321. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25322. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25323. var result = BABYLON.Ray.Zero();
  25324. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25325. return result;
  25326. };
  25327. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25328. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25329. var engine = this._engine;
  25330. if (!camera) {
  25331. if (!this.activeCamera)
  25332. throw new Error("Active camera not set");
  25333. camera = this.activeCamera;
  25334. }
  25335. var cameraViewport = camera.viewport;
  25336. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25337. // Moving coordinates to local viewport world
  25338. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25339. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25340. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25341. return this;
  25342. };
  25343. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25344. var result = BABYLON.Ray.Zero();
  25345. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25346. return result;
  25347. };
  25348. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25349. if (!BABYLON.PickingInfo) {
  25350. return this;
  25351. }
  25352. var engine = this._engine;
  25353. if (!camera) {
  25354. if (!this.activeCamera)
  25355. throw new Error("Active camera not set");
  25356. camera = this.activeCamera;
  25357. }
  25358. var cameraViewport = camera.viewport;
  25359. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25360. var identity = BABYLON.Matrix.Identity();
  25361. // Moving coordinates to local viewport world
  25362. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25363. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25364. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25365. return this;
  25366. };
  25367. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25368. if (!BABYLON.PickingInfo) {
  25369. return null;
  25370. }
  25371. var pickingInfo = null;
  25372. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25373. var mesh = this.meshes[meshIndex];
  25374. if (predicate) {
  25375. if (!predicate(mesh)) {
  25376. continue;
  25377. }
  25378. }
  25379. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25380. continue;
  25381. }
  25382. var world = mesh.getWorldMatrix();
  25383. var ray = rayFunction(world);
  25384. var result = mesh.intersects(ray, fastCheck);
  25385. if (!result || !result.hit)
  25386. continue;
  25387. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25388. continue;
  25389. pickingInfo = result;
  25390. if (fastCheck) {
  25391. break;
  25392. }
  25393. }
  25394. return pickingInfo || new BABYLON.PickingInfo();
  25395. };
  25396. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25397. if (!BABYLON.PickingInfo) {
  25398. return null;
  25399. }
  25400. var pickingInfos = new Array();
  25401. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25402. var mesh = this.meshes[meshIndex];
  25403. if (predicate) {
  25404. if (!predicate(mesh)) {
  25405. continue;
  25406. }
  25407. }
  25408. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25409. continue;
  25410. }
  25411. var world = mesh.getWorldMatrix();
  25412. var ray = rayFunction(world);
  25413. var result = mesh.intersects(ray, false);
  25414. if (!result || !result.hit)
  25415. continue;
  25416. pickingInfos.push(result);
  25417. }
  25418. return pickingInfos;
  25419. };
  25420. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25421. if (!BABYLON.PickingInfo) {
  25422. return null;
  25423. }
  25424. var pickingInfo = null;
  25425. if (!camera) {
  25426. if (!this.activeCamera) {
  25427. return null;
  25428. }
  25429. camera = this.activeCamera;
  25430. }
  25431. if (this.spriteManagers.length > 0) {
  25432. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25433. var spriteManager = this.spriteManagers[spriteIndex];
  25434. if (!spriteManager.isPickable) {
  25435. continue;
  25436. }
  25437. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25438. if (!result || !result.hit)
  25439. continue;
  25440. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25441. continue;
  25442. pickingInfo = result;
  25443. if (fastCheck) {
  25444. break;
  25445. }
  25446. }
  25447. }
  25448. return pickingInfo || new BABYLON.PickingInfo();
  25449. };
  25450. /** Launch a ray to try to pick a mesh in the scene
  25451. * @param x position on screen
  25452. * @param y position on screen
  25453. * @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
  25454. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25455. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25456. */
  25457. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25458. var _this = this;
  25459. if (!BABYLON.PickingInfo) {
  25460. return null;
  25461. }
  25462. return this._internalPick(function (world) {
  25463. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25464. return _this._tempPickingRay;
  25465. }, predicate, fastCheck);
  25466. };
  25467. /** Launch a ray to try to pick a sprite in the scene
  25468. * @param x position on screen
  25469. * @param y position on screen
  25470. * @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
  25471. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25472. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25473. */
  25474. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25475. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25476. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25477. };
  25478. /** Use the given ray to pick a mesh in the scene
  25479. * @param ray The ray to use to pick meshes
  25480. * @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
  25481. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25482. */
  25483. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25484. var _this = this;
  25485. return this._internalPick(function (world) {
  25486. if (!_this._pickWithRayInverseMatrix) {
  25487. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25488. }
  25489. world.invertToRef(_this._pickWithRayInverseMatrix);
  25490. if (!_this._cachedRayForTransform) {
  25491. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25492. }
  25493. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25494. return _this._cachedRayForTransform;
  25495. }, predicate, fastCheck);
  25496. };
  25497. /**
  25498. * Launch a ray to try to pick a mesh in the scene
  25499. * @param x X position on screen
  25500. * @param y Y position on screen
  25501. * @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
  25502. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25503. */
  25504. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25505. var _this = this;
  25506. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25507. };
  25508. /**
  25509. * Launch a ray to try to pick a mesh in the scene
  25510. * @param ray Ray to use
  25511. * @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
  25512. */
  25513. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25514. var _this = this;
  25515. return this._internalMultiPick(function (world) {
  25516. if (!_this._pickWithRayInverseMatrix) {
  25517. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25518. }
  25519. world.invertToRef(_this._pickWithRayInverseMatrix);
  25520. if (!_this._cachedRayForTransform) {
  25521. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25522. }
  25523. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25524. return _this._cachedRayForTransform;
  25525. }, predicate);
  25526. };
  25527. Scene.prototype.setPointerOverMesh = function (mesh) {
  25528. if (this._pointerOverMesh === mesh) {
  25529. return;
  25530. }
  25531. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25532. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25533. }
  25534. this._pointerOverMesh = mesh;
  25535. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25536. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25537. }
  25538. };
  25539. Scene.prototype.getPointerOverMesh = function () {
  25540. return this._pointerOverMesh;
  25541. };
  25542. Scene.prototype.setPointerOverSprite = function (sprite) {
  25543. if (this._pointerOverSprite === sprite) {
  25544. return;
  25545. }
  25546. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25547. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25548. }
  25549. this._pointerOverSprite = sprite;
  25550. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25551. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25552. }
  25553. };
  25554. Scene.prototype.getPointerOverSprite = function () {
  25555. return this._pointerOverSprite;
  25556. };
  25557. // Physics
  25558. Scene.prototype.getPhysicsEngine = function () {
  25559. return this._physicsEngine;
  25560. };
  25561. /**
  25562. * Enables physics to the current scene
  25563. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25564. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25565. * @return {boolean} was the physics engine initialized
  25566. */
  25567. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25568. if (gravity === void 0) { gravity = null; }
  25569. if (this._physicsEngine) {
  25570. return true;
  25571. }
  25572. try {
  25573. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25574. return true;
  25575. }
  25576. catch (e) {
  25577. BABYLON.Tools.Error(e.message);
  25578. return false;
  25579. }
  25580. };
  25581. Scene.prototype.disablePhysicsEngine = function () {
  25582. if (!this._physicsEngine) {
  25583. return;
  25584. }
  25585. this._physicsEngine.dispose();
  25586. this._physicsEngine = null;
  25587. };
  25588. Scene.prototype.isPhysicsEnabled = function () {
  25589. return this._physicsEngine !== undefined;
  25590. };
  25591. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25592. var mesh = compound.parts[0].mesh;
  25593. if (mesh.physicsImpostor) {
  25594. mesh.physicsImpostor.dispose();
  25595. mesh.physicsImpostor = null;
  25596. }
  25597. };
  25598. // Misc.
  25599. Scene.prototype._rebuildGeometries = function () {
  25600. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25601. var geometry = _a[_i];
  25602. geometry._rebuild();
  25603. }
  25604. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25605. var mesh = _c[_b];
  25606. mesh._rebuild();
  25607. }
  25608. if (this.postProcessManager) {
  25609. this.postProcessManager._rebuild();
  25610. }
  25611. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25612. var layer = _e[_d];
  25613. layer._rebuild();
  25614. }
  25615. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25616. var effectLayer = _g[_f];
  25617. effectLayer._rebuild();
  25618. }
  25619. if (this._boundingBoxRenderer) {
  25620. this._boundingBoxRenderer._rebuild();
  25621. }
  25622. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25623. var system = _j[_h];
  25624. system.rebuild();
  25625. }
  25626. if (this._postProcessRenderPipelineManager) {
  25627. this._postProcessRenderPipelineManager._rebuild();
  25628. }
  25629. };
  25630. Scene.prototype._rebuildTextures = function () {
  25631. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25632. var texture = _a[_i];
  25633. texture._rebuild();
  25634. }
  25635. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25636. };
  25637. /**
  25638. * Creates a default light for the scene.
  25639. * @param replace Whether to replace the existing lights in the scene.
  25640. */
  25641. Scene.prototype.createDefaultLight = function (replace) {
  25642. if (replace === void 0) { replace = false; }
  25643. // Dispose existing light in replace mode.
  25644. if (replace) {
  25645. if (this.lights) {
  25646. for (var i = 0; i < this.lights.length; i++) {
  25647. this.lights[i].dispose();
  25648. }
  25649. }
  25650. }
  25651. // Light
  25652. if (this.lights.length === 0) {
  25653. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25654. }
  25655. };
  25656. /**
  25657. * Creates a default camera for the scene.
  25658. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25659. * @param replace Whether to replace the existing active camera in the scene.
  25660. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25661. */
  25662. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25663. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25664. if (replace === void 0) { replace = false; }
  25665. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25666. // Dispose existing camera in replace mode.
  25667. if (replace) {
  25668. if (this.activeCamera) {
  25669. this.activeCamera.dispose();
  25670. this.activeCamera = null;
  25671. }
  25672. }
  25673. // Camera
  25674. if (!this.activeCamera) {
  25675. var worldExtends = this.getWorldExtends();
  25676. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25677. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25678. var camera;
  25679. var radius = worldSize.length() * 1.5;
  25680. // empty scene scenario!
  25681. if (!isFinite(radius)) {
  25682. radius = 1;
  25683. worldCenter.copyFromFloats(0, 0, 0);
  25684. }
  25685. if (createArcRotateCamera) {
  25686. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25687. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25688. arcRotateCamera.wheelPrecision = 100 / radius;
  25689. camera = arcRotateCamera;
  25690. }
  25691. else {
  25692. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25693. freeCamera.setTarget(worldCenter);
  25694. camera = freeCamera;
  25695. }
  25696. camera.minZ = radius * 0.01;
  25697. camera.maxZ = radius * 1000;
  25698. camera.speed = radius * 0.2;
  25699. this.activeCamera = camera;
  25700. var canvas = this.getEngine().getRenderingCanvas();
  25701. if (attachCameraControls && canvas) {
  25702. camera.attachControl(canvas);
  25703. }
  25704. }
  25705. };
  25706. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25707. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25708. if (replace === void 0) { replace = false; }
  25709. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25710. this.createDefaultLight(replace);
  25711. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25712. };
  25713. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25714. if (pbr === void 0) { pbr = false; }
  25715. if (scale === void 0) { scale = 1000; }
  25716. if (blur === void 0) { blur = 0; }
  25717. if (environmentTexture) {
  25718. this.environmentTexture = environmentTexture;
  25719. }
  25720. if (!this.environmentTexture) {
  25721. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25722. return null;
  25723. }
  25724. // Skybox
  25725. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25726. if (pbr) {
  25727. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25728. hdrSkyboxMaterial.backFaceCulling = false;
  25729. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25730. if (hdrSkyboxMaterial.reflectionTexture) {
  25731. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25732. }
  25733. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25734. hdrSkyboxMaterial.disableLighting = true;
  25735. hdrSkyboxMaterial.twoSidedLighting = true;
  25736. hdrSkybox.infiniteDistance = true;
  25737. hdrSkybox.material = hdrSkyboxMaterial;
  25738. }
  25739. else {
  25740. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25741. skyboxMaterial.backFaceCulling = false;
  25742. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25743. if (skyboxMaterial.reflectionTexture) {
  25744. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25745. }
  25746. skyboxMaterial.disableLighting = true;
  25747. hdrSkybox.infiniteDistance = true;
  25748. hdrSkybox.material = skyboxMaterial;
  25749. }
  25750. return hdrSkybox;
  25751. };
  25752. Scene.prototype.createDefaultEnvironment = function (options) {
  25753. if (BABYLON.EnvironmentHelper) {
  25754. return new BABYLON.EnvironmentHelper(options, this);
  25755. }
  25756. return null;
  25757. };
  25758. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25759. if (webVROptions === void 0) { webVROptions = {}; }
  25760. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25761. };
  25762. // Tags
  25763. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25764. if (tagsQuery === undefined) {
  25765. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25766. return list;
  25767. }
  25768. var listByTags = [];
  25769. forEach = forEach || (function (item) { return; });
  25770. for (var i in list) {
  25771. var item = list[i];
  25772. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25773. listByTags.push(item);
  25774. forEach(item);
  25775. }
  25776. }
  25777. return listByTags;
  25778. };
  25779. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25780. return this._getByTags(this.meshes, tagsQuery, forEach);
  25781. };
  25782. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25783. return this._getByTags(this.cameras, tagsQuery, forEach);
  25784. };
  25785. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25786. return this._getByTags(this.lights, tagsQuery, forEach);
  25787. };
  25788. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25789. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25790. };
  25791. /**
  25792. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25793. * This allowed control for front to back rendering or reversly depending of the special needs.
  25794. *
  25795. * @param renderingGroupId The rendering group id corresponding to its index
  25796. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25797. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25798. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25799. */
  25800. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25801. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25802. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25803. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25804. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25805. };
  25806. /**
  25807. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25808. *
  25809. * @param renderingGroupId The rendering group id corresponding to its index
  25810. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25811. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25812. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25813. */
  25814. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25815. if (depth === void 0) { depth = true; }
  25816. if (stencil === void 0) { stencil = true; }
  25817. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25818. };
  25819. /**
  25820. * Will flag all materials as dirty to trigger new shader compilation
  25821. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25822. */
  25823. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25824. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25825. var material = _a[_i];
  25826. if (predicate && !predicate(material)) {
  25827. continue;
  25828. }
  25829. material.markAsDirty(flag);
  25830. }
  25831. };
  25832. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25833. var _this = this;
  25834. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25835. this._activeRequests.push(request);
  25836. request.onCompleteObservable.add(function (request) {
  25837. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25838. });
  25839. return request;
  25840. };
  25841. /** @ignore */
  25842. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25843. var _this = this;
  25844. return new Promise(function (resolve, reject) {
  25845. _this._loadFile(url, function (data) {
  25846. resolve(data);
  25847. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25848. reject(exception);
  25849. });
  25850. });
  25851. };
  25852. // Statics
  25853. Scene._FOGMODE_NONE = 0;
  25854. Scene._FOGMODE_EXP = 1;
  25855. Scene._FOGMODE_EXP2 = 2;
  25856. Scene._FOGMODE_LINEAR = 3;
  25857. Scene._uniqueIdCounter = 0;
  25858. Scene.MinDeltaTime = 1.0;
  25859. Scene.MaxDeltaTime = 1000.0;
  25860. /** The distance in pixel that you have to move to prevent some events */
  25861. Scene.DragMovementThreshold = 10; // in pixels
  25862. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25863. Scene.LongPressDelay = 500; // in milliseconds
  25864. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25865. Scene.DoubleClickDelay = 300; // in milliseconds
  25866. /** If you need to check double click without raising a single click at first click, enable this flag */
  25867. Scene.ExclusiveDoubleClickMode = false;
  25868. return Scene;
  25869. }());
  25870. BABYLON.Scene = Scene;
  25871. })(BABYLON || (BABYLON = {}));
  25872. //# sourceMappingURL=babylon.scene.js.map
  25873. var BABYLON;
  25874. (function (BABYLON) {
  25875. /**
  25876. * Set of assets to keep when moving a scene into an asset container.
  25877. */
  25878. var KeepAssets = /** @class */ (function () {
  25879. function KeepAssets() {
  25880. /**
  25881. * Cameras to keep.
  25882. */
  25883. this.cameras = new Array();
  25884. /**
  25885. * Lights to keep.
  25886. */
  25887. this.lights = new Array();
  25888. /**
  25889. * Meshes to keep.
  25890. */
  25891. this.meshes = new Array();
  25892. /**
  25893. * Skeletons to keep.
  25894. */
  25895. this.skeletons = new Array();
  25896. /**
  25897. * ParticleSystems to keep.
  25898. */
  25899. this.particleSystems = new Array();
  25900. /**
  25901. * Animations to keep.
  25902. */
  25903. this.animations = new Array();
  25904. /**
  25905. * MultiMaterials to keep.
  25906. */
  25907. this.multiMaterials = new Array();
  25908. /**
  25909. * Materials to keep.
  25910. */
  25911. this.materials = new Array();
  25912. /**
  25913. * MorphTargetManagers to keep.
  25914. */
  25915. this.morphTargetManagers = new Array();
  25916. /**
  25917. * Geometries to keep.
  25918. */
  25919. this.geometries = new Array();
  25920. /**
  25921. * TransformNodes to keep.
  25922. */
  25923. this.transformNodes = new Array();
  25924. /**
  25925. * LensFlareSystems to keep.
  25926. */
  25927. this.lensFlareSystems = new Array();
  25928. /**
  25929. * ShadowGenerators to keep.
  25930. */
  25931. this.shadowGenerators = new Array();
  25932. /**
  25933. * ActionManagers to keep.
  25934. */
  25935. this.actionManagers = new Array();
  25936. /**
  25937. * Sounds to keep.
  25938. */
  25939. this.sounds = new Array();
  25940. }
  25941. return KeepAssets;
  25942. }());
  25943. BABYLON.KeepAssets = KeepAssets;
  25944. /**
  25945. * Container with a set of assets that can be added or removed from a scene.
  25946. */
  25947. var AssetContainer = /** @class */ (function () {
  25948. /**
  25949. * Instantiates an AssetContainer.
  25950. * @param scene The scene the AssetContainer belongs to.
  25951. */
  25952. function AssetContainer(scene) {
  25953. // Objects
  25954. /**
  25955. * Cameras populated in the container.
  25956. */
  25957. this.cameras = new Array();
  25958. /**
  25959. * Lights populated in the container.
  25960. */
  25961. this.lights = new Array();
  25962. /**
  25963. * Meshes populated in the container.
  25964. */
  25965. this.meshes = new Array();
  25966. /**
  25967. * Skeletons populated in the container.
  25968. */
  25969. this.skeletons = new Array();
  25970. /**
  25971. * ParticleSystems populated in the container.
  25972. */
  25973. this.particleSystems = new Array();
  25974. /**
  25975. * Animations populated in the container.
  25976. */
  25977. this.animations = new Array();
  25978. /**
  25979. * MultiMaterials populated in the container.
  25980. */
  25981. this.multiMaterials = new Array();
  25982. /**
  25983. * Materials populated in the container.
  25984. */
  25985. this.materials = new Array();
  25986. /**
  25987. * MorphTargetManagers populated in the container.
  25988. */
  25989. this.morphTargetManagers = new Array();
  25990. /**
  25991. * Geometries populated in the container.
  25992. */
  25993. this.geometries = new Array();
  25994. /**
  25995. * TransformNodes populated in the container.
  25996. */
  25997. this.transformNodes = new Array();
  25998. /**
  25999. * LensFlareSystems populated in the container.
  26000. */
  26001. this.lensFlareSystems = new Array();
  26002. /**
  26003. * ShadowGenerators populated in the container.
  26004. */
  26005. this.shadowGenerators = new Array();
  26006. /**
  26007. * ActionManagers populated in the container.
  26008. */
  26009. this.actionManagers = new Array();
  26010. /**
  26011. * Sounds populated in the container.
  26012. */
  26013. this.sounds = new Array();
  26014. this.scene = scene;
  26015. }
  26016. /**
  26017. * Adds all the assets from the container to the scene.
  26018. */
  26019. AssetContainer.prototype.addAllToScene = function () {
  26020. var _this = this;
  26021. this.cameras.forEach(function (o) {
  26022. _this.scene.addCamera(o);
  26023. });
  26024. this.lights.forEach(function (o) {
  26025. _this.scene.addLight(o);
  26026. });
  26027. this.meshes.forEach(function (o) {
  26028. _this.scene.addMesh(o);
  26029. });
  26030. this.skeletons.forEach(function (o) {
  26031. _this.scene.addSkeleton(o);
  26032. });
  26033. this.particleSystems.forEach(function (o) {
  26034. _this.scene.addParticleSystem(o);
  26035. });
  26036. this.animations.forEach(function (o) {
  26037. _this.scene.addAnimation(o);
  26038. });
  26039. this.multiMaterials.forEach(function (o) {
  26040. _this.scene.addMultiMaterial(o);
  26041. });
  26042. this.materials.forEach(function (o) {
  26043. _this.scene.addMaterial(o);
  26044. });
  26045. this.morphTargetManagers.forEach(function (o) {
  26046. _this.scene.addMorphTargetManager(o);
  26047. });
  26048. this.geometries.forEach(function (o) {
  26049. _this.scene.addGeometry(o);
  26050. });
  26051. this.transformNodes.forEach(function (o) {
  26052. _this.scene.addTransformNode(o);
  26053. });
  26054. this.lensFlareSystems.forEach(function (o) {
  26055. _this.scene.addLensFlareSystem(o);
  26056. });
  26057. this.actionManagers.forEach(function (o) {
  26058. _this.scene.addActionManager(o);
  26059. });
  26060. this.sounds.forEach(function (o) {
  26061. o.play();
  26062. o.autoplay = true;
  26063. _this.scene.mainSoundTrack.AddSound(o);
  26064. });
  26065. };
  26066. /**
  26067. * Removes all the assets in the container from the scene
  26068. */
  26069. AssetContainer.prototype.removeAllFromScene = function () {
  26070. var _this = this;
  26071. this.cameras.forEach(function (o) {
  26072. _this.scene.removeCamera(o);
  26073. });
  26074. this.lights.forEach(function (o) {
  26075. _this.scene.removeLight(o);
  26076. });
  26077. this.meshes.forEach(function (o) {
  26078. _this.scene.removeMesh(o);
  26079. });
  26080. this.skeletons.forEach(function (o) {
  26081. _this.scene.removeSkeleton(o);
  26082. });
  26083. this.particleSystems.forEach(function (o) {
  26084. _this.scene.removeParticleSystem(o);
  26085. });
  26086. this.animations.forEach(function (o) {
  26087. _this.scene.removeAnimation(o);
  26088. });
  26089. this.multiMaterials.forEach(function (o) {
  26090. _this.scene.removeMultiMaterial(o);
  26091. });
  26092. this.materials.forEach(function (o) {
  26093. _this.scene.removeMaterial(o);
  26094. });
  26095. this.morphTargetManagers.forEach(function (o) {
  26096. _this.scene.removeMorphTargetManager(o);
  26097. });
  26098. this.geometries.forEach(function (o) {
  26099. _this.scene.removeGeometry(o);
  26100. });
  26101. this.transformNodes.forEach(function (o) {
  26102. _this.scene.removeTransformNode(o);
  26103. });
  26104. this.lensFlareSystems.forEach(function (o) {
  26105. _this.scene.removeLensFlareSystem(o);
  26106. });
  26107. this.actionManagers.forEach(function (o) {
  26108. _this.scene.removeActionManager(o);
  26109. });
  26110. this.sounds.forEach(function (o) {
  26111. o.stop();
  26112. o.autoplay = false;
  26113. _this.scene.mainSoundTrack.RemoveSound(o);
  26114. });
  26115. };
  26116. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26117. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26118. var asset = sourceAssets_1[_i];
  26119. var move = true;
  26120. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26121. var keepAsset = keepAssets_1[_a];
  26122. if (asset === keepAsset) {
  26123. move = false;
  26124. break;
  26125. }
  26126. }
  26127. if (move) {
  26128. targetAssets.push(asset);
  26129. }
  26130. }
  26131. };
  26132. /**
  26133. * Removes all the assets contained in the scene and adds them to the container.
  26134. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26135. */
  26136. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26137. if (keepAssets === undefined) {
  26138. keepAssets = new KeepAssets();
  26139. }
  26140. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26141. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26142. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26143. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26144. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26145. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26146. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26147. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26148. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26149. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26150. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26151. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26152. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26153. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26154. this.removeAllFromScene();
  26155. };
  26156. return AssetContainer;
  26157. }());
  26158. BABYLON.AssetContainer = AssetContainer;
  26159. })(BABYLON || (BABYLON = {}));
  26160. //# sourceMappingURL=babylon.assetContainer.js.map
  26161. var BABYLON;
  26162. (function (BABYLON) {
  26163. var Buffer = /** @class */ (function () {
  26164. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26165. if (instanced === void 0) { instanced = false; }
  26166. if (engine instanceof BABYLON.Mesh) {
  26167. this._engine = engine.getScene().getEngine();
  26168. }
  26169. else {
  26170. this._engine = engine;
  26171. }
  26172. this._updatable = updatable;
  26173. this._instanced = instanced;
  26174. this._data = data;
  26175. this._strideSize = stride;
  26176. if (!postponeInternalCreation) {
  26177. this.create();
  26178. }
  26179. }
  26180. /**
  26181. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26182. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26183. * @param offset defines offset in the buffer (0 by default)
  26184. * @param size defines the size in floats of attributes (position is 3 for instance)
  26185. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26186. * @param instanced defines if the vertex buffer contains indexed data
  26187. * @returns the new vertex buffer
  26188. */
  26189. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26190. // a lot of these parameters are ignored as they are overriden by the buffer
  26191. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26192. };
  26193. // Properties
  26194. Buffer.prototype.isUpdatable = function () {
  26195. return this._updatable;
  26196. };
  26197. Buffer.prototype.getData = function () {
  26198. return this._data;
  26199. };
  26200. Buffer.prototype.getBuffer = function () {
  26201. return this._buffer;
  26202. };
  26203. Buffer.prototype.getStrideSize = function () {
  26204. return this._strideSize;
  26205. };
  26206. // public getIsInstanced(): boolean {
  26207. // return this._instanced;
  26208. // }
  26209. // public get instanceDivisor(): number {
  26210. // return this._instanceDivisor;
  26211. // }
  26212. // public set instanceDivisor(value: number) {
  26213. // this._instanceDivisor = value;
  26214. // if (value == 0) {
  26215. // this._instanced = false;
  26216. // } else {
  26217. // this._instanced = true;
  26218. // }
  26219. // }
  26220. // Methods
  26221. Buffer.prototype.create = function (data) {
  26222. if (data === void 0) { data = null; }
  26223. if (!data && this._buffer) {
  26224. return; // nothing to do
  26225. }
  26226. data = data || this._data;
  26227. if (!data) {
  26228. return;
  26229. }
  26230. if (!this._buffer) {
  26231. if (this._updatable) {
  26232. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26233. this._data = data;
  26234. }
  26235. else {
  26236. this._buffer = this._engine.createVertexBuffer(data);
  26237. }
  26238. }
  26239. else if (this._updatable) {
  26240. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26241. this._data = data;
  26242. }
  26243. };
  26244. Buffer.prototype._rebuild = function () {
  26245. this._buffer = null;
  26246. this.create(this._data);
  26247. };
  26248. Buffer.prototype.update = function (data) {
  26249. this.create(data);
  26250. };
  26251. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26252. if (!this._buffer) {
  26253. return;
  26254. }
  26255. if (this._updatable) {
  26256. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26257. this._data = null;
  26258. }
  26259. };
  26260. Buffer.prototype.dispose = function () {
  26261. if (!this._buffer) {
  26262. return;
  26263. }
  26264. if (this._engine._releaseBuffer(this._buffer)) {
  26265. this._buffer = null;
  26266. }
  26267. };
  26268. return Buffer;
  26269. }());
  26270. BABYLON.Buffer = Buffer;
  26271. })(BABYLON || (BABYLON = {}));
  26272. //# sourceMappingURL=babylon.buffer.js.map
  26273. var BABYLON;
  26274. (function (BABYLON) {
  26275. var VertexBuffer = /** @class */ (function () {
  26276. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26277. if (data instanceof BABYLON.Buffer) {
  26278. if (!stride) {
  26279. stride = data.getStrideSize();
  26280. }
  26281. this._buffer = data;
  26282. this._ownsBuffer = false;
  26283. }
  26284. else {
  26285. if (!stride) {
  26286. stride = VertexBuffer.DeduceStride(kind);
  26287. }
  26288. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26289. this._ownsBuffer = true;
  26290. }
  26291. this._stride = stride;
  26292. this._instanced = instanced !== undefined ? instanced : false;
  26293. this._instanceDivisor = instanced ? 1 : 0;
  26294. this._offset = offset ? offset : 0;
  26295. this._size = size ? size : stride;
  26296. this._kind = kind;
  26297. }
  26298. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26299. /**
  26300. * Gets or sets the instance divisor when in instanced mode
  26301. */
  26302. get: function () {
  26303. return this._instanceDivisor;
  26304. },
  26305. set: function (value) {
  26306. this._instanceDivisor = value;
  26307. if (value == 0) {
  26308. this._instanced = false;
  26309. }
  26310. else {
  26311. this._instanced = true;
  26312. }
  26313. },
  26314. enumerable: true,
  26315. configurable: true
  26316. });
  26317. VertexBuffer.prototype._rebuild = function () {
  26318. if (!this._buffer) {
  26319. return;
  26320. }
  26321. this._buffer._rebuild();
  26322. };
  26323. /**
  26324. * Returns the kind of the VertexBuffer (string).
  26325. */
  26326. VertexBuffer.prototype.getKind = function () {
  26327. return this._kind;
  26328. };
  26329. // Properties
  26330. /**
  26331. * Boolean : is the VertexBuffer updatable ?
  26332. */
  26333. VertexBuffer.prototype.isUpdatable = function () {
  26334. return this._buffer.isUpdatable();
  26335. };
  26336. /**
  26337. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26338. */
  26339. VertexBuffer.prototype.getData = function () {
  26340. return this._buffer.getData();
  26341. };
  26342. /**
  26343. * Returns the WebGLBuffer associated to the VertexBuffer.
  26344. */
  26345. VertexBuffer.prototype.getBuffer = function () {
  26346. return this._buffer.getBuffer();
  26347. };
  26348. /**
  26349. * Returns the stride of the VertexBuffer (integer).
  26350. */
  26351. VertexBuffer.prototype.getStrideSize = function () {
  26352. return this._stride;
  26353. };
  26354. /**
  26355. * Returns the offset (integer).
  26356. */
  26357. VertexBuffer.prototype.getOffset = function () {
  26358. return this._offset;
  26359. };
  26360. /**
  26361. * Returns the VertexBuffer total size (integer).
  26362. */
  26363. VertexBuffer.prototype.getSize = function () {
  26364. return this._size;
  26365. };
  26366. /**
  26367. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26368. */
  26369. VertexBuffer.prototype.getIsInstanced = function () {
  26370. return this._instanced;
  26371. };
  26372. /**
  26373. * Returns the instancing divisor, zero for non-instanced (integer).
  26374. */
  26375. VertexBuffer.prototype.getInstanceDivisor = function () {
  26376. return this._instanceDivisor;
  26377. };
  26378. // Methods
  26379. /**
  26380. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26381. * Returns the created WebGLBuffer.
  26382. */
  26383. VertexBuffer.prototype.create = function (data) {
  26384. return this._buffer.create(data);
  26385. };
  26386. /**
  26387. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26388. * This function will create a new buffer if the current one is not updatable
  26389. * Returns the updated WebGLBuffer.
  26390. */
  26391. VertexBuffer.prototype.update = function (data) {
  26392. return this._buffer.update(data);
  26393. };
  26394. /**
  26395. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26396. * Returns the directly updated WebGLBuffer.
  26397. */
  26398. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26399. return this._buffer.updateDirectly(data, offset);
  26400. };
  26401. /**
  26402. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26403. */
  26404. VertexBuffer.prototype.dispose = function () {
  26405. if (this._ownsBuffer) {
  26406. this._buffer.dispose();
  26407. }
  26408. };
  26409. Object.defineProperty(VertexBuffer, "PositionKind", {
  26410. get: function () {
  26411. return VertexBuffer._PositionKind;
  26412. },
  26413. enumerable: true,
  26414. configurable: true
  26415. });
  26416. Object.defineProperty(VertexBuffer, "NormalKind", {
  26417. get: function () {
  26418. return VertexBuffer._NormalKind;
  26419. },
  26420. enumerable: true,
  26421. configurable: true
  26422. });
  26423. Object.defineProperty(VertexBuffer, "TangentKind", {
  26424. get: function () {
  26425. return VertexBuffer._TangentKind;
  26426. },
  26427. enumerable: true,
  26428. configurable: true
  26429. });
  26430. Object.defineProperty(VertexBuffer, "UVKind", {
  26431. get: function () {
  26432. return VertexBuffer._UVKind;
  26433. },
  26434. enumerable: true,
  26435. configurable: true
  26436. });
  26437. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26438. get: function () {
  26439. return VertexBuffer._UV2Kind;
  26440. },
  26441. enumerable: true,
  26442. configurable: true
  26443. });
  26444. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26445. get: function () {
  26446. return VertexBuffer._UV3Kind;
  26447. },
  26448. enumerable: true,
  26449. configurable: true
  26450. });
  26451. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26452. get: function () {
  26453. return VertexBuffer._UV4Kind;
  26454. },
  26455. enumerable: true,
  26456. configurable: true
  26457. });
  26458. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26459. get: function () {
  26460. return VertexBuffer._UV5Kind;
  26461. },
  26462. enumerable: true,
  26463. configurable: true
  26464. });
  26465. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26466. get: function () {
  26467. return VertexBuffer._UV6Kind;
  26468. },
  26469. enumerable: true,
  26470. configurable: true
  26471. });
  26472. Object.defineProperty(VertexBuffer, "ColorKind", {
  26473. get: function () {
  26474. return VertexBuffer._ColorKind;
  26475. },
  26476. enumerable: true,
  26477. configurable: true
  26478. });
  26479. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26480. get: function () {
  26481. return VertexBuffer._MatricesIndicesKind;
  26482. },
  26483. enumerable: true,
  26484. configurable: true
  26485. });
  26486. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26487. get: function () {
  26488. return VertexBuffer._MatricesWeightsKind;
  26489. },
  26490. enumerable: true,
  26491. configurable: true
  26492. });
  26493. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26494. get: function () {
  26495. return VertexBuffer._MatricesIndicesExtraKind;
  26496. },
  26497. enumerable: true,
  26498. configurable: true
  26499. });
  26500. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26501. get: function () {
  26502. return VertexBuffer._MatricesWeightsExtraKind;
  26503. },
  26504. enumerable: true,
  26505. configurable: true
  26506. });
  26507. /**
  26508. * Deduces the stride given a kind.
  26509. * @param kind The kind string to deduce
  26510. * @returns The deduced stride
  26511. */
  26512. VertexBuffer.DeduceStride = function (kind) {
  26513. switch (kind) {
  26514. case VertexBuffer.UVKind:
  26515. case VertexBuffer.UV2Kind:
  26516. case VertexBuffer.UV3Kind:
  26517. case VertexBuffer.UV4Kind:
  26518. case VertexBuffer.UV5Kind:
  26519. case VertexBuffer.UV6Kind:
  26520. return 2;
  26521. case VertexBuffer.NormalKind:
  26522. case VertexBuffer.PositionKind:
  26523. return 3;
  26524. case VertexBuffer.ColorKind:
  26525. case VertexBuffer.MatricesIndicesKind:
  26526. case VertexBuffer.MatricesIndicesExtraKind:
  26527. case VertexBuffer.MatricesWeightsKind:
  26528. case VertexBuffer.MatricesWeightsExtraKind:
  26529. case VertexBuffer.TangentKind:
  26530. return 4;
  26531. default:
  26532. throw new Error("Invalid kind '" + kind + "'");
  26533. }
  26534. };
  26535. // Enums
  26536. VertexBuffer._PositionKind = "position";
  26537. VertexBuffer._NormalKind = "normal";
  26538. VertexBuffer._TangentKind = "tangent";
  26539. VertexBuffer._UVKind = "uv";
  26540. VertexBuffer._UV2Kind = "uv2";
  26541. VertexBuffer._UV3Kind = "uv3";
  26542. VertexBuffer._UV4Kind = "uv4";
  26543. VertexBuffer._UV5Kind = "uv5";
  26544. VertexBuffer._UV6Kind = "uv6";
  26545. VertexBuffer._ColorKind = "color";
  26546. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26547. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26548. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26549. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26550. return VertexBuffer;
  26551. }());
  26552. BABYLON.VertexBuffer = VertexBuffer;
  26553. })(BABYLON || (BABYLON = {}));
  26554. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26555. var BABYLON;
  26556. (function (BABYLON) {
  26557. /**
  26558. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26559. */
  26560. var DummyInternalTextureTracker = /** @class */ (function () {
  26561. function DummyInternalTextureTracker() {
  26562. /**
  26563. * Gets or set the previous tracker in the list
  26564. */
  26565. this.previous = null;
  26566. /**
  26567. * Gets or set the next tracker in the list
  26568. */
  26569. this.next = null;
  26570. }
  26571. return DummyInternalTextureTracker;
  26572. }());
  26573. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26574. })(BABYLON || (BABYLON = {}));
  26575. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26576. var BABYLON;
  26577. (function (BABYLON) {
  26578. /**
  26579. * Class used to store data associated with WebGL texture data for the engine
  26580. * This class should not be used directly
  26581. */
  26582. var InternalTexture = /** @class */ (function () {
  26583. /**
  26584. * Creates a new InternalTexture
  26585. * @param engine defines the engine to use
  26586. * @param dataSource defines the type of data that will be used
  26587. */
  26588. function InternalTexture(engine, dataSource) {
  26589. /**
  26590. * Observable called when the texture is loaded
  26591. */
  26592. this.onLoadedObservable = new BABYLON.Observable();
  26593. /**
  26594. * Gets or set the previous tracker in the list
  26595. */
  26596. this.previous = null;
  26597. /**
  26598. * Gets or set the next tracker in the list
  26599. */
  26600. this.next = null;
  26601. // Private
  26602. /** @ignore */
  26603. this._initialSlot = -1;
  26604. /** @ignore */
  26605. this._designatedSlot = -1;
  26606. /** @ignore */
  26607. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26608. /** @ignore */
  26609. this._comparisonFunction = 0;
  26610. /** @ignore */
  26611. this._references = 1;
  26612. this._engine = engine;
  26613. this._dataSource = dataSource;
  26614. this._webGLTexture = engine._createTexture();
  26615. }
  26616. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26617. /**
  26618. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26619. */
  26620. get: function () {
  26621. return this._dataSource;
  26622. },
  26623. enumerable: true,
  26624. configurable: true
  26625. });
  26626. /**
  26627. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26628. */
  26629. InternalTexture.prototype.incrementReferences = function () {
  26630. this._references++;
  26631. };
  26632. /**
  26633. * Change the size of the texture (not the size of the content)
  26634. * @param width defines the new width
  26635. * @param height defines the new height
  26636. * @param depth defines the new depth (1 by default)
  26637. */
  26638. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26639. if (depth === void 0) { depth = 1; }
  26640. this.width = width;
  26641. this.height = height;
  26642. this.depth = depth;
  26643. this.baseWidth = width;
  26644. this.baseHeight = height;
  26645. this.baseDepth = depth;
  26646. this._size = width * height * depth;
  26647. };
  26648. /** @ignore */
  26649. InternalTexture.prototype._rebuild = function () {
  26650. var _this = this;
  26651. var proxy;
  26652. this.isReady = false;
  26653. this._cachedCoordinatesMode = null;
  26654. this._cachedWrapU = null;
  26655. this._cachedWrapV = null;
  26656. this._cachedAnisotropicFilteringLevel = null;
  26657. switch (this._dataSource) {
  26658. case InternalTexture.DATASOURCE_TEMP:
  26659. return;
  26660. case InternalTexture.DATASOURCE_URL:
  26661. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26662. _this.isReady = true;
  26663. }, null, this._buffer, undefined, this.format);
  26664. proxy._swapAndDie(this);
  26665. return;
  26666. case InternalTexture.DATASOURCE_RAW:
  26667. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26668. proxy._swapAndDie(this);
  26669. this.isReady = true;
  26670. return;
  26671. case InternalTexture.DATASOURCE_RAW3D:
  26672. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26673. proxy._swapAndDie(this);
  26674. this.isReady = true;
  26675. return;
  26676. case InternalTexture.DATASOURCE_DYNAMIC:
  26677. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26678. proxy._swapAndDie(this);
  26679. // The engine will make sure to update content so no need to flag it as isReady = true
  26680. return;
  26681. case InternalTexture.DATASOURCE_RENDERTARGET:
  26682. var options = new BABYLON.RenderTargetCreationOptions();
  26683. options.generateDepthBuffer = this._generateDepthBuffer;
  26684. options.generateMipMaps = this.generateMipMaps;
  26685. options.generateStencilBuffer = this._generateStencilBuffer;
  26686. options.samplingMode = this.samplingMode;
  26687. options.type = this.type;
  26688. if (this.isCube) {
  26689. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26690. }
  26691. else {
  26692. var size = {
  26693. width: this.width,
  26694. height: this.height
  26695. };
  26696. proxy = this._engine.createRenderTargetTexture(size, options);
  26697. }
  26698. proxy._swapAndDie(this);
  26699. this.isReady = true;
  26700. return;
  26701. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26702. var depthTextureOptions = {
  26703. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26704. comparisonFunction: this._comparisonFunction,
  26705. generateStencil: this._generateStencilBuffer,
  26706. isCube: this.isCube
  26707. };
  26708. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26709. proxy._swapAndDie(this);
  26710. this.isReady = true;
  26711. return;
  26712. case InternalTexture.DATASOURCE_CUBE:
  26713. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26714. _this.isReady = true;
  26715. }, null, this.format, this._extension);
  26716. proxy._swapAndDie(this);
  26717. return;
  26718. case InternalTexture.DATASOURCE_CUBERAW:
  26719. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26720. proxy._swapAndDie(this);
  26721. this.isReady = true;
  26722. return;
  26723. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26724. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26725. if (proxy) {
  26726. proxy._swapAndDie(_this);
  26727. }
  26728. _this.isReady = true;
  26729. }, null, this.format, this._extension);
  26730. return;
  26731. }
  26732. };
  26733. InternalTexture.prototype._swapAndDie = function (target) {
  26734. target._webGLTexture = this._webGLTexture;
  26735. if (this._framebuffer) {
  26736. target._framebuffer = this._framebuffer;
  26737. }
  26738. if (this._depthStencilBuffer) {
  26739. target._depthStencilBuffer = this._depthStencilBuffer;
  26740. }
  26741. if (this._lodTextureHigh) {
  26742. if (target._lodTextureHigh) {
  26743. target._lodTextureHigh.dispose();
  26744. }
  26745. target._lodTextureHigh = this._lodTextureHigh;
  26746. }
  26747. if (this._lodTextureMid) {
  26748. if (target._lodTextureMid) {
  26749. target._lodTextureMid.dispose();
  26750. }
  26751. target._lodTextureMid = this._lodTextureMid;
  26752. }
  26753. if (this._lodTextureLow) {
  26754. if (target._lodTextureLow) {
  26755. target._lodTextureLow.dispose();
  26756. }
  26757. target._lodTextureLow = this._lodTextureLow;
  26758. }
  26759. var cache = this._engine.getLoadedTexturesCache();
  26760. var index = cache.indexOf(this);
  26761. if (index !== -1) {
  26762. cache.splice(index, 1);
  26763. }
  26764. };
  26765. /**
  26766. * Dispose the current allocated resources
  26767. */
  26768. InternalTexture.prototype.dispose = function () {
  26769. if (!this._webGLTexture) {
  26770. return;
  26771. }
  26772. this._references--;
  26773. if (this._references === 0) {
  26774. this._engine._releaseTexture(this);
  26775. this._webGLTexture = null;
  26776. this.previous = null;
  26777. this.next = null;
  26778. }
  26779. };
  26780. /**
  26781. * The source of the texture data is unknown
  26782. */
  26783. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26784. /**
  26785. * Texture data comes from an URL
  26786. */
  26787. InternalTexture.DATASOURCE_URL = 1;
  26788. /**
  26789. * Texture data is only used for temporary storage
  26790. */
  26791. InternalTexture.DATASOURCE_TEMP = 2;
  26792. /**
  26793. * Texture data comes from raw data (ArrayBuffer)
  26794. */
  26795. InternalTexture.DATASOURCE_RAW = 3;
  26796. /**
  26797. * Texture content is dynamic (video or dynamic texture)
  26798. */
  26799. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26800. /**
  26801. * Texture content is generated by rendering to it
  26802. */
  26803. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26804. /**
  26805. * Texture content is part of a multi render target process
  26806. */
  26807. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26808. /**
  26809. * Texture data comes from a cube data file
  26810. */
  26811. InternalTexture.DATASOURCE_CUBE = 7;
  26812. /**
  26813. * Texture data comes from a raw cube data
  26814. */
  26815. InternalTexture.DATASOURCE_CUBERAW = 8;
  26816. /**
  26817. * Texture data come from a prefiltered cube data file
  26818. */
  26819. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26820. /**
  26821. * Texture content is raw 3D data
  26822. */
  26823. InternalTexture.DATASOURCE_RAW3D = 10;
  26824. /**
  26825. * Texture content is a depth texture
  26826. */
  26827. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26828. return InternalTexture;
  26829. }());
  26830. BABYLON.InternalTexture = InternalTexture;
  26831. })(BABYLON || (BABYLON = {}));
  26832. //# sourceMappingURL=babylon.internalTexture.js.map
  26833. var BABYLON;
  26834. (function (BABYLON) {
  26835. var BaseTexture = /** @class */ (function () {
  26836. function BaseTexture(scene) {
  26837. this._hasAlpha = false;
  26838. this.getAlphaFromRGB = false;
  26839. this.level = 1;
  26840. this.coordinatesIndex = 0;
  26841. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26842. /**
  26843. * | Value | Type | Description |
  26844. * | ----- | ------------------ | ----------- |
  26845. * | 0 | CLAMP_ADDRESSMODE | |
  26846. * | 1 | WRAP_ADDRESSMODE | |
  26847. * | 2 | MIRROR_ADDRESSMODE | |
  26848. */
  26849. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26850. /**
  26851. * | Value | Type | Description |
  26852. * | ----- | ------------------ | ----------- |
  26853. * | 0 | CLAMP_ADDRESSMODE | |
  26854. * | 1 | WRAP_ADDRESSMODE | |
  26855. * | 2 | MIRROR_ADDRESSMODE | |
  26856. */
  26857. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26858. /**
  26859. * | Value | Type | Description |
  26860. * | ----- | ------------------ | ----------- |
  26861. * | 0 | CLAMP_ADDRESSMODE | |
  26862. * | 1 | WRAP_ADDRESSMODE | |
  26863. * | 2 | MIRROR_ADDRESSMODE | |
  26864. */
  26865. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26866. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26867. this.isCube = false;
  26868. this.is3D = false;
  26869. this.gammaSpace = true;
  26870. this.invertZ = false;
  26871. this.lodLevelInAlpha = false;
  26872. this.lodGenerationOffset = 0.0;
  26873. this.lodGenerationScale = 0.8;
  26874. this.isRenderTarget = false;
  26875. this.animations = new Array();
  26876. /**
  26877. * An event triggered when the texture is disposed.
  26878. * @type {BABYLON.Observable}
  26879. */
  26880. this.onDisposeObservable = new BABYLON.Observable();
  26881. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26882. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26883. if (this._scene) {
  26884. this._scene.textures.push(this);
  26885. }
  26886. this._uid = null;
  26887. }
  26888. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26889. get: function () {
  26890. return this._hasAlpha;
  26891. },
  26892. set: function (value) {
  26893. if (this._hasAlpha === value) {
  26894. return;
  26895. }
  26896. this._hasAlpha = value;
  26897. if (this._scene) {
  26898. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26899. }
  26900. },
  26901. enumerable: true,
  26902. configurable: true
  26903. });
  26904. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26905. get: function () {
  26906. return this._coordinatesMode;
  26907. },
  26908. /**
  26909. * How a texture is mapped.
  26910. *
  26911. * | Value | Type | Description |
  26912. * | ----- | ----------------------------------- | ----------- |
  26913. * | 0 | EXPLICIT_MODE | |
  26914. * | 1 | SPHERICAL_MODE | |
  26915. * | 2 | PLANAR_MODE | |
  26916. * | 3 | CUBIC_MODE | |
  26917. * | 4 | PROJECTION_MODE | |
  26918. * | 5 | SKYBOX_MODE | |
  26919. * | 6 | INVCUBIC_MODE | |
  26920. * | 7 | EQUIRECTANGULAR_MODE | |
  26921. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26922. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26923. */
  26924. set: function (value) {
  26925. if (this._coordinatesMode === value) {
  26926. return;
  26927. }
  26928. this._coordinatesMode = value;
  26929. if (this._scene) {
  26930. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26931. }
  26932. },
  26933. enumerable: true,
  26934. configurable: true
  26935. });
  26936. Object.defineProperty(BaseTexture.prototype, "uid", {
  26937. get: function () {
  26938. if (!this._uid) {
  26939. this._uid = BABYLON.Tools.RandomId();
  26940. }
  26941. return this._uid;
  26942. },
  26943. enumerable: true,
  26944. configurable: true
  26945. });
  26946. BaseTexture.prototype.toString = function () {
  26947. return this.name;
  26948. };
  26949. BaseTexture.prototype.getClassName = function () {
  26950. return "BaseTexture";
  26951. };
  26952. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26953. set: function (callback) {
  26954. if (this._onDisposeObserver) {
  26955. this.onDisposeObservable.remove(this._onDisposeObserver);
  26956. }
  26957. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26958. },
  26959. enumerable: true,
  26960. configurable: true
  26961. });
  26962. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26963. get: function () {
  26964. return true;
  26965. },
  26966. enumerable: true,
  26967. configurable: true
  26968. });
  26969. BaseTexture.prototype.getScene = function () {
  26970. return this._scene;
  26971. };
  26972. BaseTexture.prototype.getTextureMatrix = function () {
  26973. return BABYLON.Matrix.IdentityReadOnly;
  26974. };
  26975. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26976. return BABYLON.Matrix.IdentityReadOnly;
  26977. };
  26978. BaseTexture.prototype.getInternalTexture = function () {
  26979. return this._texture;
  26980. };
  26981. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26982. return !this.isBlocking || this.isReady();
  26983. };
  26984. BaseTexture.prototype.isReady = function () {
  26985. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26986. this.delayLoad();
  26987. return false;
  26988. }
  26989. if (this._texture) {
  26990. return this._texture.isReady;
  26991. }
  26992. return false;
  26993. };
  26994. BaseTexture.prototype.getSize = function () {
  26995. if (this._texture && this._texture.width) {
  26996. return new BABYLON.Size(this._texture.width, this._texture.height);
  26997. }
  26998. if (this._texture && this._texture._size) {
  26999. return new BABYLON.Size(this._texture._size, this._texture._size);
  27000. }
  27001. return BABYLON.Size.Zero();
  27002. };
  27003. BaseTexture.prototype.getBaseSize = function () {
  27004. if (!this.isReady() || !this._texture)
  27005. return BABYLON.Size.Zero();
  27006. if (this._texture._size) {
  27007. return new BABYLON.Size(this._texture._size, this._texture._size);
  27008. }
  27009. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27010. };
  27011. BaseTexture.prototype.scale = function (ratio) {
  27012. };
  27013. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27014. get: function () {
  27015. return false;
  27016. },
  27017. enumerable: true,
  27018. configurable: true
  27019. });
  27020. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27021. if (!this._scene) {
  27022. return null;
  27023. }
  27024. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27025. for (var index = 0; index < texturesCache.length; index++) {
  27026. var texturesCacheEntry = texturesCache[index];
  27027. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27028. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27029. texturesCacheEntry.incrementReferences();
  27030. return texturesCacheEntry;
  27031. }
  27032. }
  27033. }
  27034. return null;
  27035. };
  27036. BaseTexture.prototype._rebuild = function () {
  27037. };
  27038. BaseTexture.prototype.delayLoad = function () {
  27039. };
  27040. BaseTexture.prototype.clone = function () {
  27041. return null;
  27042. };
  27043. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27044. get: function () {
  27045. if (!this._texture) {
  27046. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27047. }
  27048. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27049. },
  27050. enumerable: true,
  27051. configurable: true
  27052. });
  27053. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27054. get: function () {
  27055. if (!this._texture) {
  27056. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27057. }
  27058. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27059. },
  27060. enumerable: true,
  27061. configurable: true
  27062. });
  27063. BaseTexture.prototype.readPixels = function (faceIndex) {
  27064. if (faceIndex === void 0) { faceIndex = 0; }
  27065. if (!this._texture) {
  27066. return null;
  27067. }
  27068. var size = this.getSize();
  27069. var scene = this.getScene();
  27070. if (!scene) {
  27071. return null;
  27072. }
  27073. var engine = scene.getEngine();
  27074. if (this._texture.isCube) {
  27075. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27076. }
  27077. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27078. };
  27079. BaseTexture.prototype.releaseInternalTexture = function () {
  27080. if (this._texture) {
  27081. this._texture.dispose();
  27082. this._texture = null;
  27083. }
  27084. };
  27085. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27086. get: function () {
  27087. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27088. return null;
  27089. }
  27090. if (!this._texture._sphericalPolynomial) {
  27091. this._texture._sphericalPolynomial =
  27092. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27093. }
  27094. return this._texture._sphericalPolynomial;
  27095. },
  27096. set: function (value) {
  27097. if (this._texture) {
  27098. this._texture._sphericalPolynomial = value;
  27099. }
  27100. },
  27101. enumerable: true,
  27102. configurable: true
  27103. });
  27104. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27105. get: function () {
  27106. if (this._texture) {
  27107. return this._texture._lodTextureHigh;
  27108. }
  27109. return null;
  27110. },
  27111. enumerable: true,
  27112. configurable: true
  27113. });
  27114. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27115. get: function () {
  27116. if (this._texture) {
  27117. return this._texture._lodTextureMid;
  27118. }
  27119. return null;
  27120. },
  27121. enumerable: true,
  27122. configurable: true
  27123. });
  27124. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27125. get: function () {
  27126. if (this._texture) {
  27127. return this._texture._lodTextureLow;
  27128. }
  27129. return null;
  27130. },
  27131. enumerable: true,
  27132. configurable: true
  27133. });
  27134. BaseTexture.prototype.dispose = function () {
  27135. if (!this._scene) {
  27136. return;
  27137. }
  27138. // Animations
  27139. this._scene.stopAnimation(this);
  27140. // Remove from scene
  27141. this._scene._removePendingData(this);
  27142. var index = this._scene.textures.indexOf(this);
  27143. if (index >= 0) {
  27144. this._scene.textures.splice(index, 1);
  27145. }
  27146. if (this._texture === undefined) {
  27147. return;
  27148. }
  27149. // Release
  27150. this.releaseInternalTexture();
  27151. // Callback
  27152. this.onDisposeObservable.notifyObservers(this);
  27153. this.onDisposeObservable.clear();
  27154. };
  27155. BaseTexture.prototype.serialize = function () {
  27156. if (!this.name) {
  27157. return null;
  27158. }
  27159. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27160. // Animations
  27161. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27162. return serializationObject;
  27163. };
  27164. BaseTexture.WhenAllReady = function (textures, callback) {
  27165. var numRemaining = textures.length;
  27166. if (numRemaining === 0) {
  27167. callback();
  27168. return;
  27169. }
  27170. var _loop_1 = function () {
  27171. texture = textures[i];
  27172. if (texture.isReady()) {
  27173. if (--numRemaining === 0) {
  27174. callback();
  27175. }
  27176. }
  27177. else {
  27178. onLoadObservable = texture.onLoadObservable;
  27179. var onLoadCallback_1 = function () {
  27180. onLoadObservable.removeCallback(onLoadCallback_1);
  27181. if (--numRemaining === 0) {
  27182. callback();
  27183. }
  27184. };
  27185. onLoadObservable.add(onLoadCallback_1);
  27186. }
  27187. };
  27188. var texture, onLoadObservable;
  27189. for (var i = 0; i < textures.length; i++) {
  27190. _loop_1();
  27191. }
  27192. };
  27193. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27194. __decorate([
  27195. BABYLON.serialize()
  27196. ], BaseTexture.prototype, "name", void 0);
  27197. __decorate([
  27198. BABYLON.serialize("hasAlpha")
  27199. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27200. __decorate([
  27201. BABYLON.serialize()
  27202. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27203. __decorate([
  27204. BABYLON.serialize()
  27205. ], BaseTexture.prototype, "level", void 0);
  27206. __decorate([
  27207. BABYLON.serialize()
  27208. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27209. __decorate([
  27210. BABYLON.serialize("coordinatesMode")
  27211. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27212. __decorate([
  27213. BABYLON.serialize()
  27214. ], BaseTexture.prototype, "wrapU", void 0);
  27215. __decorate([
  27216. BABYLON.serialize()
  27217. ], BaseTexture.prototype, "wrapV", void 0);
  27218. __decorate([
  27219. BABYLON.serialize()
  27220. ], BaseTexture.prototype, "wrapR", void 0);
  27221. __decorate([
  27222. BABYLON.serialize()
  27223. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27224. __decorate([
  27225. BABYLON.serialize()
  27226. ], BaseTexture.prototype, "isCube", void 0);
  27227. __decorate([
  27228. BABYLON.serialize()
  27229. ], BaseTexture.prototype, "is3D", void 0);
  27230. __decorate([
  27231. BABYLON.serialize()
  27232. ], BaseTexture.prototype, "gammaSpace", void 0);
  27233. __decorate([
  27234. BABYLON.serialize()
  27235. ], BaseTexture.prototype, "invertZ", void 0);
  27236. __decorate([
  27237. BABYLON.serialize()
  27238. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27239. __decorate([
  27240. BABYLON.serialize()
  27241. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27242. __decorate([
  27243. BABYLON.serialize()
  27244. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27245. __decorate([
  27246. BABYLON.serialize()
  27247. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27248. return BaseTexture;
  27249. }());
  27250. BABYLON.BaseTexture = BaseTexture;
  27251. })(BABYLON || (BABYLON = {}));
  27252. //# sourceMappingURL=babylon.baseTexture.js.map
  27253. var BABYLON;
  27254. (function (BABYLON) {
  27255. var Texture = /** @class */ (function (_super) {
  27256. __extends(Texture, _super);
  27257. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27258. if (noMipmap === void 0) { noMipmap = false; }
  27259. if (invertY === void 0) { invertY = true; }
  27260. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27261. if (onLoad === void 0) { onLoad = null; }
  27262. if (onError === void 0) { onError = null; }
  27263. if (buffer === void 0) { buffer = null; }
  27264. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27265. var _this = _super.call(this, scene) || this;
  27266. _this.uOffset = 0;
  27267. _this.vOffset = 0;
  27268. _this.uScale = 1.0;
  27269. _this.vScale = 1.0;
  27270. _this.uAng = 0;
  27271. _this.vAng = 0;
  27272. _this.wAng = 0;
  27273. _this._isBlocking = true;
  27274. _this.name = url || "";
  27275. _this.url = url;
  27276. _this._noMipmap = noMipmap;
  27277. _this._invertY = invertY;
  27278. _this._samplingMode = samplingMode;
  27279. _this._buffer = buffer;
  27280. _this._deleteBuffer = deleteBuffer;
  27281. if (format) {
  27282. _this._format = format;
  27283. }
  27284. scene = _this.getScene();
  27285. if (!scene) {
  27286. return _this;
  27287. }
  27288. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27289. var load = function () {
  27290. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27291. _this.onLoadObservable.notifyObservers(_this);
  27292. }
  27293. if (onLoad) {
  27294. onLoad();
  27295. }
  27296. if (!_this.isBlocking && scene) {
  27297. scene.resetCachedMaterial();
  27298. }
  27299. };
  27300. if (!_this.url) {
  27301. _this._delayedOnLoad = load;
  27302. _this._delayedOnError = onError;
  27303. return _this;
  27304. }
  27305. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27306. if (!_this._texture) {
  27307. if (!scene.useDelayedTextureLoading) {
  27308. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27309. if (deleteBuffer) {
  27310. delete _this._buffer;
  27311. }
  27312. }
  27313. else {
  27314. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27315. _this._delayedOnLoad = load;
  27316. _this._delayedOnError = onError;
  27317. }
  27318. }
  27319. else {
  27320. if (_this._texture.isReady) {
  27321. BABYLON.Tools.SetImmediate(function () { return load(); });
  27322. }
  27323. else {
  27324. _this._texture.onLoadedObservable.add(load);
  27325. }
  27326. }
  27327. return _this;
  27328. }
  27329. Object.defineProperty(Texture.prototype, "noMipmap", {
  27330. get: function () {
  27331. return this._noMipmap;
  27332. },
  27333. enumerable: true,
  27334. configurable: true
  27335. });
  27336. Object.defineProperty(Texture.prototype, "isBlocking", {
  27337. get: function () {
  27338. return this._isBlocking;
  27339. },
  27340. set: function (value) {
  27341. this._isBlocking = value;
  27342. },
  27343. enumerable: true,
  27344. configurable: true
  27345. });
  27346. Object.defineProperty(Texture.prototype, "samplingMode", {
  27347. get: function () {
  27348. return this._samplingMode;
  27349. },
  27350. enumerable: true,
  27351. configurable: true
  27352. });
  27353. Texture.prototype.updateURL = function (url) {
  27354. this.url = url;
  27355. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27356. this.delayLoad();
  27357. };
  27358. Texture.prototype.delayLoad = function () {
  27359. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27360. return;
  27361. }
  27362. var scene = this.getScene();
  27363. if (!scene) {
  27364. return;
  27365. }
  27366. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27367. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27368. if (!this._texture) {
  27369. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27370. if (this._deleteBuffer) {
  27371. delete this._buffer;
  27372. }
  27373. }
  27374. else {
  27375. if (this._delayedOnLoad) {
  27376. if (this._texture.isReady) {
  27377. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27378. }
  27379. else {
  27380. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27381. }
  27382. }
  27383. }
  27384. this._delayedOnLoad = null;
  27385. this._delayedOnError = null;
  27386. };
  27387. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27388. if (!this._texture) {
  27389. return;
  27390. }
  27391. var scene = this.getScene();
  27392. if (!scene) {
  27393. return;
  27394. }
  27395. this._samplingMode = samplingMode;
  27396. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27397. };
  27398. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27399. x *= this.uScale;
  27400. y *= this.vScale;
  27401. x -= 0.5 * this.uScale;
  27402. y -= 0.5 * this.vScale;
  27403. z -= 0.5;
  27404. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27405. t.x += 0.5 * this.uScale + this.uOffset;
  27406. t.y += 0.5 * this.vScale + this.vOffset;
  27407. t.z += 0.5;
  27408. };
  27409. Texture.prototype.getTextureMatrix = function () {
  27410. var _this = this;
  27411. if (this.uOffset === this._cachedUOffset &&
  27412. this.vOffset === this._cachedVOffset &&
  27413. this.uScale === this._cachedUScale &&
  27414. this.vScale === this._cachedVScale &&
  27415. this.uAng === this._cachedUAng &&
  27416. this.vAng === this._cachedVAng &&
  27417. this.wAng === this._cachedWAng) {
  27418. return this._cachedTextureMatrix;
  27419. }
  27420. this._cachedUOffset = this.uOffset;
  27421. this._cachedVOffset = this.vOffset;
  27422. this._cachedUScale = this.uScale;
  27423. this._cachedVScale = this.vScale;
  27424. this._cachedUAng = this.uAng;
  27425. this._cachedVAng = this.vAng;
  27426. this._cachedWAng = this.wAng;
  27427. if (!this._cachedTextureMatrix) {
  27428. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27429. this._rowGenerationMatrix = new BABYLON.Matrix();
  27430. this._t0 = BABYLON.Vector3.Zero();
  27431. this._t1 = BABYLON.Vector3.Zero();
  27432. this._t2 = BABYLON.Vector3.Zero();
  27433. }
  27434. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27435. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27436. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27437. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27438. this._t1.subtractInPlace(this._t0);
  27439. this._t2.subtractInPlace(this._t0);
  27440. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27441. this._cachedTextureMatrix.m[0] = this._t1.x;
  27442. this._cachedTextureMatrix.m[1] = this._t1.y;
  27443. this._cachedTextureMatrix.m[2] = this._t1.z;
  27444. this._cachedTextureMatrix.m[4] = this._t2.x;
  27445. this._cachedTextureMatrix.m[5] = this._t2.y;
  27446. this._cachedTextureMatrix.m[6] = this._t2.z;
  27447. this._cachedTextureMatrix.m[8] = this._t0.x;
  27448. this._cachedTextureMatrix.m[9] = this._t0.y;
  27449. this._cachedTextureMatrix.m[10] = this._t0.z;
  27450. var scene = this.getScene();
  27451. if (!scene) {
  27452. return this._cachedTextureMatrix;
  27453. }
  27454. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27455. return mat.hasTexture(_this);
  27456. });
  27457. return this._cachedTextureMatrix;
  27458. };
  27459. Texture.prototype.getReflectionTextureMatrix = function () {
  27460. var _this = this;
  27461. var scene = this.getScene();
  27462. if (!scene) {
  27463. return this._cachedTextureMatrix;
  27464. }
  27465. if (this.uOffset === this._cachedUOffset &&
  27466. this.vOffset === this._cachedVOffset &&
  27467. this.uScale === this._cachedUScale &&
  27468. this.vScale === this._cachedVScale &&
  27469. this.coordinatesMode === this._cachedCoordinatesMode) {
  27470. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27471. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27472. return this._cachedTextureMatrix;
  27473. }
  27474. }
  27475. else {
  27476. return this._cachedTextureMatrix;
  27477. }
  27478. }
  27479. if (!this._cachedTextureMatrix) {
  27480. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27481. }
  27482. if (!this._projectionModeMatrix) {
  27483. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27484. }
  27485. this._cachedUOffset = this.uOffset;
  27486. this._cachedVOffset = this.vOffset;
  27487. this._cachedUScale = this.uScale;
  27488. this._cachedVScale = this.vScale;
  27489. this._cachedCoordinatesMode = this.coordinatesMode;
  27490. switch (this.coordinatesMode) {
  27491. case Texture.PLANAR_MODE:
  27492. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27493. this._cachedTextureMatrix[0] = this.uScale;
  27494. this._cachedTextureMatrix[5] = this.vScale;
  27495. this._cachedTextureMatrix[12] = this.uOffset;
  27496. this._cachedTextureMatrix[13] = this.vOffset;
  27497. break;
  27498. case Texture.PROJECTION_MODE:
  27499. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27500. this._projectionModeMatrix.m[0] = 0.5;
  27501. this._projectionModeMatrix.m[5] = -0.5;
  27502. this._projectionModeMatrix.m[10] = 0.0;
  27503. this._projectionModeMatrix.m[12] = 0.5;
  27504. this._projectionModeMatrix.m[13] = 0.5;
  27505. this._projectionModeMatrix.m[14] = 1.0;
  27506. this._projectionModeMatrix.m[15] = 1.0;
  27507. var projectionMatrix = scene.getProjectionMatrix();
  27508. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27509. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27510. break;
  27511. default:
  27512. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27513. break;
  27514. }
  27515. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27516. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27517. });
  27518. return this._cachedTextureMatrix;
  27519. };
  27520. Texture.prototype.clone = function () {
  27521. var _this = this;
  27522. return BABYLON.SerializationHelper.Clone(function () {
  27523. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27524. }, this);
  27525. };
  27526. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27527. get: function () {
  27528. if (!this._onLoadObservable) {
  27529. this._onLoadObservable = new BABYLON.Observable();
  27530. }
  27531. return this._onLoadObservable;
  27532. },
  27533. enumerable: true,
  27534. configurable: true
  27535. });
  27536. Texture.prototype.serialize = function () {
  27537. var serializationObject = _super.prototype.serialize.call(this);
  27538. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27539. serializationObject.base64String = this._buffer;
  27540. serializationObject.name = serializationObject.name.replace("data:", "");
  27541. }
  27542. return serializationObject;
  27543. };
  27544. Texture.prototype.getClassName = function () {
  27545. return "Texture";
  27546. };
  27547. Texture.prototype.dispose = function () {
  27548. _super.prototype.dispose.call(this);
  27549. if (this.onLoadObservable) {
  27550. this.onLoadObservable.clear();
  27551. this._onLoadObservable = null;
  27552. }
  27553. this._delayedOnLoad = null;
  27554. this._delayedOnError = null;
  27555. };
  27556. // Statics
  27557. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27558. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27559. if (onLoad === void 0) { onLoad = null; }
  27560. if (onError === void 0) { onError = null; }
  27561. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27562. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27563. };
  27564. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27565. if (parsedTexture.customType) {
  27566. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27567. // Update Sampling Mode
  27568. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27569. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27570. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27571. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27572. }
  27573. }
  27574. return parsedCustomTexture;
  27575. }
  27576. if (parsedTexture.isCube) {
  27577. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27578. }
  27579. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27580. return null;
  27581. }
  27582. var texture = BABYLON.SerializationHelper.Parse(function () {
  27583. var generateMipMaps = true;
  27584. if (parsedTexture.noMipmap) {
  27585. generateMipMaps = false;
  27586. }
  27587. if (parsedTexture.mirrorPlane) {
  27588. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27589. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27590. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27591. return mirrorTexture;
  27592. }
  27593. else if (parsedTexture.isRenderTarget) {
  27594. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27595. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27596. return renderTargetTexture;
  27597. }
  27598. else {
  27599. var texture;
  27600. if (parsedTexture.base64String) {
  27601. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27602. }
  27603. else {
  27604. var url = rootUrl + parsedTexture.name;
  27605. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27606. url = parsedTexture.url;
  27607. }
  27608. texture = new Texture(url, scene, !generateMipMaps);
  27609. }
  27610. return texture;
  27611. }
  27612. }, parsedTexture, scene);
  27613. // Update Sampling Mode
  27614. if (parsedTexture.samplingMode) {
  27615. var sampling = parsedTexture.samplingMode;
  27616. if (texture._samplingMode !== sampling) {
  27617. texture.updateSamplingMode(sampling);
  27618. }
  27619. }
  27620. // Animations
  27621. if (parsedTexture.animations) {
  27622. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27623. var parsedAnimation = parsedTexture.animations[animationIndex];
  27624. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27625. }
  27626. }
  27627. return texture;
  27628. };
  27629. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27630. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27631. if (noMipmap === void 0) { noMipmap = false; }
  27632. if (invertY === void 0) { invertY = true; }
  27633. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27634. if (onLoad === void 0) { onLoad = null; }
  27635. if (onError === void 0) { onError = null; }
  27636. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27637. if (name.substr(0, 5) !== "data:") {
  27638. name = "data:" + name;
  27639. }
  27640. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27641. };
  27642. // Constants
  27643. Texture.NEAREST_SAMPLINGMODE = 1;
  27644. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27645. Texture.BILINEAR_SAMPLINGMODE = 2;
  27646. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27647. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27648. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27649. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27650. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27651. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27652. Texture.NEAREST_LINEAR = 7;
  27653. Texture.NEAREST_NEAREST = 8;
  27654. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27655. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27656. Texture.LINEAR_LINEAR = 11;
  27657. Texture.LINEAR_NEAREST = 12;
  27658. Texture.EXPLICIT_MODE = 0;
  27659. Texture.SPHERICAL_MODE = 1;
  27660. Texture.PLANAR_MODE = 2;
  27661. Texture.CUBIC_MODE = 3;
  27662. Texture.PROJECTION_MODE = 4;
  27663. Texture.SKYBOX_MODE = 5;
  27664. Texture.INVCUBIC_MODE = 6;
  27665. Texture.EQUIRECTANGULAR_MODE = 7;
  27666. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27667. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27668. Texture.CLAMP_ADDRESSMODE = 0;
  27669. Texture.WRAP_ADDRESSMODE = 1;
  27670. Texture.MIRROR_ADDRESSMODE = 2;
  27671. /**
  27672. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27673. */
  27674. Texture.UseSerializedUrlIfAny = false;
  27675. __decorate([
  27676. BABYLON.serialize()
  27677. ], Texture.prototype, "url", void 0);
  27678. __decorate([
  27679. BABYLON.serialize()
  27680. ], Texture.prototype, "uOffset", void 0);
  27681. __decorate([
  27682. BABYLON.serialize()
  27683. ], Texture.prototype, "vOffset", void 0);
  27684. __decorate([
  27685. BABYLON.serialize()
  27686. ], Texture.prototype, "uScale", void 0);
  27687. __decorate([
  27688. BABYLON.serialize()
  27689. ], Texture.prototype, "vScale", void 0);
  27690. __decorate([
  27691. BABYLON.serialize()
  27692. ], Texture.prototype, "uAng", void 0);
  27693. __decorate([
  27694. BABYLON.serialize()
  27695. ], Texture.prototype, "vAng", void 0);
  27696. __decorate([
  27697. BABYLON.serialize()
  27698. ], Texture.prototype, "wAng", void 0);
  27699. __decorate([
  27700. BABYLON.serialize()
  27701. ], Texture.prototype, "isBlocking", null);
  27702. return Texture;
  27703. }(BABYLON.BaseTexture));
  27704. BABYLON.Texture = Texture;
  27705. })(BABYLON || (BABYLON = {}));
  27706. //# sourceMappingURL=babylon.texture.js.map
  27707. var BABYLON;
  27708. (function (BABYLON) {
  27709. var _InstancesBatch = /** @class */ (function () {
  27710. function _InstancesBatch() {
  27711. this.mustReturn = false;
  27712. this.visibleInstances = new Array();
  27713. this.renderSelf = new Array();
  27714. }
  27715. return _InstancesBatch;
  27716. }());
  27717. BABYLON._InstancesBatch = _InstancesBatch;
  27718. var Mesh = /** @class */ (function (_super) {
  27719. __extends(Mesh, _super);
  27720. /**
  27721. * @constructor
  27722. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27723. * @param {Scene} scene The scene to add this mesh to.
  27724. * @param {Node} parent The parent of this mesh, if it has one
  27725. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27726. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27727. * When false, achieved by calling a clone(), also passing False.
  27728. * This will make creation of children, recursive.
  27729. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27730. */
  27731. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27732. if (scene === void 0) { scene = null; }
  27733. if (parent === void 0) { parent = null; }
  27734. if (source === void 0) { source = null; }
  27735. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27736. var _this = _super.call(this, name, scene) || this;
  27737. // Events
  27738. /**
  27739. * An event triggered before rendering the mesh
  27740. * @type {BABYLON.Observable}
  27741. */
  27742. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27743. /**
  27744. * An event triggered after rendering the mesh
  27745. * @type {BABYLON.Observable}
  27746. */
  27747. _this.onAfterRenderObservable = new BABYLON.Observable();
  27748. /**
  27749. * An event triggered before drawing the mesh
  27750. * @type {BABYLON.Observable}
  27751. */
  27752. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27753. // Members
  27754. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27755. _this.instances = new Array();
  27756. _this._LODLevels = new Array();
  27757. _this._visibleInstances = {};
  27758. _this._renderIdForInstances = new Array();
  27759. _this._batchCache = new _InstancesBatch();
  27760. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27761. // Use by builder only to know what orientation were the mesh build in.
  27762. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27763. _this.overrideMaterialSideOrientation = null;
  27764. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27765. // Will be used to save a source mesh reference, If any
  27766. _this._source = null;
  27767. scene = _this.getScene();
  27768. if (source) {
  27769. // Source mesh
  27770. _this._source = source;
  27771. // Geometry
  27772. if (source._geometry) {
  27773. source._geometry.applyToMesh(_this);
  27774. }
  27775. // Deep copy
  27776. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27777. // Metadata
  27778. if (source.metadata && source.metadata.clone) {
  27779. _this.metadata = source.metadata.clone();
  27780. }
  27781. else {
  27782. _this.metadata = source.metadata;
  27783. }
  27784. // Tags
  27785. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27786. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27787. }
  27788. // Parent
  27789. _this.parent = source.parent;
  27790. // Pivot
  27791. _this.setPivotMatrix(source.getPivotMatrix());
  27792. _this.id = name + "." + source.id;
  27793. // Material
  27794. _this.material = source.material;
  27795. var index;
  27796. if (!doNotCloneChildren) {
  27797. // Children
  27798. var directDescendants = source.getDescendants(true);
  27799. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27800. var child = directDescendants[index_1];
  27801. if (child.clone) {
  27802. child.clone(name + "." + child.name, _this);
  27803. }
  27804. }
  27805. }
  27806. // Physics clone
  27807. var physicsEngine = _this.getScene().getPhysicsEngine();
  27808. if (clonePhysicsImpostor && physicsEngine) {
  27809. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27810. if (impostor) {
  27811. _this.physicsImpostor = impostor.clone(_this);
  27812. }
  27813. }
  27814. // Particles
  27815. for (index = 0; index < scene.particleSystems.length; index++) {
  27816. var system = scene.particleSystems[index];
  27817. if (system.emitter === source) {
  27818. system.clone(system.name, _this);
  27819. }
  27820. }
  27821. _this.computeWorldMatrix(true);
  27822. }
  27823. // Parent
  27824. if (parent !== null) {
  27825. _this.parent = parent;
  27826. }
  27827. return _this;
  27828. }
  27829. Object.defineProperty(Mesh, "FRONTSIDE", {
  27830. /**
  27831. * Mesh side orientation : usually the external or front surface
  27832. */
  27833. get: function () {
  27834. return Mesh._FRONTSIDE;
  27835. },
  27836. enumerable: true,
  27837. configurable: true
  27838. });
  27839. Object.defineProperty(Mesh, "BACKSIDE", {
  27840. /**
  27841. * Mesh side orientation : usually the internal or back surface
  27842. */
  27843. get: function () {
  27844. return Mesh._BACKSIDE;
  27845. },
  27846. enumerable: true,
  27847. configurable: true
  27848. });
  27849. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27850. /**
  27851. * Mesh side orientation : both internal and external or front and back surfaces
  27852. */
  27853. get: function () {
  27854. return Mesh._DOUBLESIDE;
  27855. },
  27856. enumerable: true,
  27857. configurable: true
  27858. });
  27859. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27860. /**
  27861. * Mesh side orientation : by default, `FRONTSIDE`
  27862. */
  27863. get: function () {
  27864. return Mesh._DEFAULTSIDE;
  27865. },
  27866. enumerable: true,
  27867. configurable: true
  27868. });
  27869. Object.defineProperty(Mesh, "NO_CAP", {
  27870. /**
  27871. * Mesh cap setting : no cap
  27872. */
  27873. get: function () {
  27874. return Mesh._NO_CAP;
  27875. },
  27876. enumerable: true,
  27877. configurable: true
  27878. });
  27879. Object.defineProperty(Mesh, "CAP_START", {
  27880. /**
  27881. * Mesh cap setting : one cap at the beginning of the mesh
  27882. */
  27883. get: function () {
  27884. return Mesh._CAP_START;
  27885. },
  27886. enumerable: true,
  27887. configurable: true
  27888. });
  27889. Object.defineProperty(Mesh, "CAP_END", {
  27890. /**
  27891. * Mesh cap setting : one cap at the end of the mesh
  27892. */
  27893. get: function () {
  27894. return Mesh._CAP_END;
  27895. },
  27896. enumerable: true,
  27897. configurable: true
  27898. });
  27899. Object.defineProperty(Mesh, "CAP_ALL", {
  27900. /**
  27901. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27902. */
  27903. get: function () {
  27904. return Mesh._CAP_ALL;
  27905. },
  27906. enumerable: true,
  27907. configurable: true
  27908. });
  27909. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27910. set: function (callback) {
  27911. if (this._onBeforeDrawObserver) {
  27912. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27913. }
  27914. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27915. },
  27916. enumerable: true,
  27917. configurable: true
  27918. });
  27919. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27920. get: function () {
  27921. return this._morphTargetManager;
  27922. },
  27923. set: function (value) {
  27924. if (this._morphTargetManager === value) {
  27925. return;
  27926. }
  27927. this._morphTargetManager = value;
  27928. this._syncGeometryWithMorphTargetManager();
  27929. },
  27930. enumerable: true,
  27931. configurable: true
  27932. });
  27933. Object.defineProperty(Mesh.prototype, "source", {
  27934. get: function () {
  27935. return this._source;
  27936. },
  27937. enumerable: true,
  27938. configurable: true
  27939. });
  27940. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27941. get: function () {
  27942. return this._unIndexed;
  27943. },
  27944. set: function (value) {
  27945. if (this._unIndexed !== value) {
  27946. this._unIndexed = value;
  27947. this._markSubMeshesAsAttributesDirty();
  27948. }
  27949. },
  27950. enumerable: true,
  27951. configurable: true
  27952. });
  27953. // Methods
  27954. /**
  27955. * Returns the string "Mesh".
  27956. */
  27957. Mesh.prototype.getClassName = function () {
  27958. return "Mesh";
  27959. };
  27960. /**
  27961. * Returns a string.
  27962. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27963. */
  27964. Mesh.prototype.toString = function (fullDetails) {
  27965. var ret = _super.prototype.toString.call(this, fullDetails);
  27966. ret += ", n vertices: " + this.getTotalVertices();
  27967. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27968. if (this.animations) {
  27969. for (var i = 0; i < this.animations.length; i++) {
  27970. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27971. }
  27972. }
  27973. if (fullDetails) {
  27974. if (this._geometry) {
  27975. var ib = this.getIndices();
  27976. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27977. if (vb && ib) {
  27978. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27979. }
  27980. }
  27981. else {
  27982. ret += ", flat shading: UNKNOWN";
  27983. }
  27984. }
  27985. return ret;
  27986. };
  27987. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27988. /**
  27989. * True if the mesh has some Levels Of Details (LOD).
  27990. * Returns a boolean.
  27991. */
  27992. get: function () {
  27993. return this._LODLevels.length > 0;
  27994. },
  27995. enumerable: true,
  27996. configurable: true
  27997. });
  27998. /**
  27999. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28000. * @returns an array of {BABYLON.MeshLODLevel}
  28001. */
  28002. Mesh.prototype.getLODLevels = function () {
  28003. return this._LODLevels;
  28004. };
  28005. Mesh.prototype._sortLODLevels = function () {
  28006. this._LODLevels.sort(function (a, b) {
  28007. if (a.distance < b.distance) {
  28008. return 1;
  28009. }
  28010. if (a.distance > b.distance) {
  28011. return -1;
  28012. }
  28013. return 0;
  28014. });
  28015. };
  28016. /**
  28017. * Add a mesh as LOD level triggered at the given distance.
  28018. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28019. * @param {number} distance The distance from the center of the object to show this level
  28020. * @param {Mesh} mesh The mesh to be added as LOD level
  28021. * @return {Mesh} This mesh (for chaining)
  28022. */
  28023. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28024. if (mesh && mesh._masterMesh) {
  28025. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28026. return this;
  28027. }
  28028. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28029. this._LODLevels.push(level);
  28030. if (mesh) {
  28031. mesh._masterMesh = this;
  28032. }
  28033. this._sortLODLevels();
  28034. return this;
  28035. };
  28036. /**
  28037. * Returns the LOD level mesh at the passed distance or null if not found.
  28038. * It is related to the method `addLODLevel(distance, mesh)`.
  28039. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28040. * Returns an object Mesh or `null`.
  28041. */
  28042. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28043. for (var index = 0; index < this._LODLevels.length; index++) {
  28044. var level = this._LODLevels[index];
  28045. if (level.distance === distance) {
  28046. return level.mesh;
  28047. }
  28048. }
  28049. return null;
  28050. };
  28051. /**
  28052. * Remove a mesh from the LOD array
  28053. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28054. * @param {Mesh} mesh The mesh to be removed.
  28055. * @return {Mesh} This mesh (for chaining)
  28056. */
  28057. Mesh.prototype.removeLODLevel = function (mesh) {
  28058. for (var index = 0; index < this._LODLevels.length; index++) {
  28059. if (this._LODLevels[index].mesh === mesh) {
  28060. this._LODLevels.splice(index, 1);
  28061. if (mesh) {
  28062. mesh._masterMesh = null;
  28063. }
  28064. }
  28065. }
  28066. this._sortLODLevels();
  28067. return this;
  28068. };
  28069. /**
  28070. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28071. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28072. */
  28073. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28074. if (!this._LODLevels || this._LODLevels.length === 0) {
  28075. return this;
  28076. }
  28077. var bSphere;
  28078. if (boundingSphere) {
  28079. bSphere = boundingSphere;
  28080. }
  28081. else {
  28082. var boundingInfo = this.getBoundingInfo();
  28083. bSphere = boundingInfo.boundingSphere;
  28084. }
  28085. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28086. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28087. if (this.onLODLevelSelection) {
  28088. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28089. }
  28090. return this;
  28091. }
  28092. for (var index = 0; index < this._LODLevels.length; index++) {
  28093. var level = this._LODLevels[index];
  28094. if (level.distance < distanceToCamera) {
  28095. if (level.mesh) {
  28096. level.mesh._preActivate();
  28097. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28098. }
  28099. if (this.onLODLevelSelection) {
  28100. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28101. }
  28102. return level.mesh;
  28103. }
  28104. }
  28105. if (this.onLODLevelSelection) {
  28106. this.onLODLevelSelection(distanceToCamera, this, this);
  28107. }
  28108. return this;
  28109. };
  28110. Object.defineProperty(Mesh.prototype, "geometry", {
  28111. /**
  28112. * Returns the mesh internal Geometry object.
  28113. */
  28114. get: function () {
  28115. return this._geometry;
  28116. },
  28117. enumerable: true,
  28118. configurable: true
  28119. });
  28120. /**
  28121. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28122. */
  28123. Mesh.prototype.getTotalVertices = function () {
  28124. if (this._geometry === null || this._geometry === undefined) {
  28125. return 0;
  28126. }
  28127. return this._geometry.getTotalVertices();
  28128. };
  28129. /**
  28130. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28131. * 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.
  28132. * You can force the copy with forceCopy === true
  28133. * Returns null if the mesh has no geometry or no vertex buffer.
  28134. * Possible `kind` values :
  28135. * - BABYLON.VertexBuffer.PositionKind
  28136. * - BABYLON.VertexBuffer.UVKind
  28137. * - BABYLON.VertexBuffer.UV2Kind
  28138. * - BABYLON.VertexBuffer.UV3Kind
  28139. * - BABYLON.VertexBuffer.UV4Kind
  28140. * - BABYLON.VertexBuffer.UV5Kind
  28141. * - BABYLON.VertexBuffer.UV6Kind
  28142. * - BABYLON.VertexBuffer.ColorKind
  28143. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28144. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28145. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28146. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28147. */
  28148. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28149. if (!this._geometry) {
  28150. return null;
  28151. }
  28152. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28153. };
  28154. /**
  28155. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28156. * Returns `null` if the mesh has no geometry.
  28157. * Possible `kind` values :
  28158. * - BABYLON.VertexBuffer.PositionKind
  28159. * - BABYLON.VertexBuffer.UVKind
  28160. * - BABYLON.VertexBuffer.UV2Kind
  28161. * - BABYLON.VertexBuffer.UV3Kind
  28162. * - BABYLON.VertexBuffer.UV4Kind
  28163. * - BABYLON.VertexBuffer.UV5Kind
  28164. * - BABYLON.VertexBuffer.UV6Kind
  28165. * - BABYLON.VertexBuffer.ColorKind
  28166. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28167. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28168. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28169. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28170. */
  28171. Mesh.prototype.getVertexBuffer = function (kind) {
  28172. if (!this._geometry) {
  28173. return null;
  28174. }
  28175. return this._geometry.getVertexBuffer(kind);
  28176. };
  28177. /**
  28178. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28179. * Possible `kind` values :
  28180. * - BABYLON.VertexBuffer.PositionKind
  28181. * - BABYLON.VertexBuffer.UVKind
  28182. * - BABYLON.VertexBuffer.UV2Kind
  28183. * - BABYLON.VertexBuffer.UV3Kind
  28184. * - BABYLON.VertexBuffer.UV4Kind
  28185. * - BABYLON.VertexBuffer.UV5Kind
  28186. * - BABYLON.VertexBuffer.UV6Kind
  28187. * - BABYLON.VertexBuffer.ColorKind
  28188. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28189. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28190. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28191. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28192. */
  28193. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28194. if (!this._geometry) {
  28195. if (this._delayInfo) {
  28196. return this._delayInfo.indexOf(kind) !== -1;
  28197. }
  28198. return false;
  28199. }
  28200. return this._geometry.isVerticesDataPresent(kind);
  28201. };
  28202. /**
  28203. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28204. * Possible `kind` values :
  28205. * - BABYLON.VertexBuffer.PositionKind
  28206. * - BABYLON.VertexBuffer.UVKind
  28207. * - BABYLON.VertexBuffer.UV2Kind
  28208. * - BABYLON.VertexBuffer.UV3Kind
  28209. * - BABYLON.VertexBuffer.UV4Kind
  28210. * - BABYLON.VertexBuffer.UV5Kind
  28211. * - BABYLON.VertexBuffer.UV6Kind
  28212. * - BABYLON.VertexBuffer.ColorKind
  28213. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28214. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28215. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28216. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28217. */
  28218. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28219. if (!this._geometry) {
  28220. if (this._delayInfo) {
  28221. return this._delayInfo.indexOf(kind) !== -1;
  28222. }
  28223. return false;
  28224. }
  28225. return this._geometry.isVertexBufferUpdatable(kind);
  28226. };
  28227. /**
  28228. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28229. * Possible `kind` values :
  28230. * - BABYLON.VertexBuffer.PositionKind
  28231. * - BABYLON.VertexBuffer.UVKind
  28232. * - BABYLON.VertexBuffer.UV2Kind
  28233. * - BABYLON.VertexBuffer.UV3Kind
  28234. * - BABYLON.VertexBuffer.UV4Kind
  28235. * - BABYLON.VertexBuffer.UV5Kind
  28236. * - BABYLON.VertexBuffer.UV6Kind
  28237. * - BABYLON.VertexBuffer.ColorKind
  28238. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28239. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28240. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28241. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28242. */
  28243. Mesh.prototype.getVerticesDataKinds = function () {
  28244. if (!this._geometry) {
  28245. var result = new Array();
  28246. if (this._delayInfo) {
  28247. this._delayInfo.forEach(function (kind, index, array) {
  28248. result.push(kind);
  28249. });
  28250. }
  28251. return result;
  28252. }
  28253. return this._geometry.getVerticesDataKinds();
  28254. };
  28255. /**
  28256. * Returns a positive integer : the total number of indices in this mesh geometry.
  28257. * Returns zero if the mesh has no geometry.
  28258. */
  28259. Mesh.prototype.getTotalIndices = function () {
  28260. if (!this._geometry) {
  28261. return 0;
  28262. }
  28263. return this._geometry.getTotalIndices();
  28264. };
  28265. /**
  28266. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28267. * 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.
  28268. * Returns an empty array if the mesh has no geometry.
  28269. */
  28270. Mesh.prototype.getIndices = function (copyWhenShared) {
  28271. if (!this._geometry) {
  28272. return [];
  28273. }
  28274. return this._geometry.getIndices(copyWhenShared);
  28275. };
  28276. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28277. get: function () {
  28278. return this._masterMesh !== null && this._masterMesh !== undefined;
  28279. },
  28280. enumerable: true,
  28281. configurable: true
  28282. });
  28283. /**
  28284. * Determine if the current mesh is ready to be rendered
  28285. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28286. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28287. * @returns true if all associated assets are ready (material, textures, shaders)
  28288. */
  28289. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28290. if (completeCheck === void 0) { completeCheck = false; }
  28291. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28292. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28293. return false;
  28294. }
  28295. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28296. return false;
  28297. }
  28298. if (!this.subMeshes || this.subMeshes.length === 0) {
  28299. return true;
  28300. }
  28301. if (!completeCheck) {
  28302. return true;
  28303. }
  28304. var engine = this.getEngine();
  28305. var scene = this.getScene();
  28306. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28307. this.computeWorldMatrix();
  28308. var mat = this.material || scene.defaultMaterial;
  28309. if (mat) {
  28310. if (mat.storeEffectOnSubMeshes) {
  28311. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28312. var subMesh = _a[_i];
  28313. var effectiveMaterial = subMesh.getMaterial();
  28314. if (effectiveMaterial) {
  28315. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28316. return false;
  28317. }
  28318. }
  28319. }
  28320. }
  28321. else {
  28322. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28323. return false;
  28324. }
  28325. }
  28326. }
  28327. // Shadows
  28328. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28329. var light = _c[_b];
  28330. var generator = light.getShadowGenerator();
  28331. if (generator) {
  28332. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28333. var subMesh = _e[_d];
  28334. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28335. return false;
  28336. }
  28337. }
  28338. }
  28339. }
  28340. // LOD
  28341. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28342. var lod = _g[_f];
  28343. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28344. return false;
  28345. }
  28346. }
  28347. return true;
  28348. };
  28349. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28350. /**
  28351. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28352. * This property is pertinent only for updatable parametric shapes.
  28353. */
  28354. get: function () {
  28355. return this._areNormalsFrozen;
  28356. },
  28357. enumerable: true,
  28358. configurable: true
  28359. });
  28360. /**
  28361. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28362. * It has no effect at all on other shapes.
  28363. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28364. * Returns the Mesh.
  28365. */
  28366. Mesh.prototype.freezeNormals = function () {
  28367. this._areNormalsFrozen = true;
  28368. return this;
  28369. };
  28370. /**
  28371. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28372. * It has no effect at all on other shapes.
  28373. * It reactivates the mesh normals computation if it was previously frozen.
  28374. * Returns the Mesh.
  28375. */
  28376. Mesh.prototype.unfreezeNormals = function () {
  28377. this._areNormalsFrozen = false;
  28378. return this;
  28379. };
  28380. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28381. /**
  28382. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28383. */
  28384. set: function (count) {
  28385. this._overridenInstanceCount = count;
  28386. },
  28387. enumerable: true,
  28388. configurable: true
  28389. });
  28390. // Methods
  28391. Mesh.prototype._preActivate = function () {
  28392. var sceneRenderId = this.getScene().getRenderId();
  28393. if (this._preActivateId === sceneRenderId) {
  28394. return this;
  28395. }
  28396. this._preActivateId = sceneRenderId;
  28397. this._visibleInstances = null;
  28398. return this;
  28399. };
  28400. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28401. if (this._visibleInstances) {
  28402. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28403. }
  28404. return this;
  28405. };
  28406. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28407. if (!this._visibleInstances) {
  28408. this._visibleInstances = {};
  28409. this._visibleInstances.defaultRenderId = renderId;
  28410. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28411. }
  28412. if (!this._visibleInstances[renderId]) {
  28413. this._visibleInstances[renderId] = new Array();
  28414. }
  28415. this._visibleInstances[renderId].push(instance);
  28416. return this;
  28417. };
  28418. /**
  28419. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28420. * This means the mesh underlying bounding box and sphere are recomputed.
  28421. * Returns the Mesh.
  28422. */
  28423. Mesh.prototype.refreshBoundingInfo = function () {
  28424. return this._refreshBoundingInfo(false);
  28425. };
  28426. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28427. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28428. return this;
  28429. }
  28430. var data = this._getPositionData(applySkeleton);
  28431. if (data) {
  28432. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28433. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28434. }
  28435. if (this.subMeshes) {
  28436. for (var index = 0; index < this.subMeshes.length; index++) {
  28437. this.subMeshes[index].refreshBoundingInfo();
  28438. }
  28439. }
  28440. this._updateBoundingInfo();
  28441. return this;
  28442. };
  28443. Mesh.prototype._getPositionData = function (applySkeleton) {
  28444. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28445. if (data && applySkeleton && this.skeleton) {
  28446. data = BABYLON.Tools.Slice(data);
  28447. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28448. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28449. if (matricesWeightsData && matricesIndicesData) {
  28450. var needExtras = this.numBoneInfluencers > 4;
  28451. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28452. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28453. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28454. var tempVector = BABYLON.Tmp.Vector3[0];
  28455. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28456. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28457. var matWeightIdx = 0;
  28458. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28459. finalMatrix.reset();
  28460. var inf;
  28461. var weight;
  28462. for (inf = 0; inf < 4; inf++) {
  28463. weight = matricesWeightsData[matWeightIdx + inf];
  28464. if (weight <= 0)
  28465. break;
  28466. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28467. finalMatrix.addToSelf(tempMatrix);
  28468. }
  28469. if (needExtras) {
  28470. for (inf = 0; inf < 4; inf++) {
  28471. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28472. if (weight <= 0)
  28473. break;
  28474. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28475. finalMatrix.addToSelf(tempMatrix);
  28476. }
  28477. }
  28478. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28479. tempVector.toArray(data, index);
  28480. }
  28481. }
  28482. }
  28483. return data;
  28484. };
  28485. Mesh.prototype._createGlobalSubMesh = function (force) {
  28486. var totalVertices = this.getTotalVertices();
  28487. if (!totalVertices || !this.getIndices()) {
  28488. return null;
  28489. }
  28490. // Check if we need to recreate the submeshes
  28491. if (this.subMeshes && this.subMeshes.length > 0) {
  28492. var ib = this.getIndices();
  28493. if (!ib) {
  28494. return null;
  28495. }
  28496. var totalIndices = ib.length;
  28497. var needToRecreate = false;
  28498. if (force) {
  28499. needToRecreate = true;
  28500. }
  28501. else {
  28502. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28503. var submesh = _a[_i];
  28504. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28505. needToRecreate = true;
  28506. break;
  28507. }
  28508. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28509. needToRecreate = true;
  28510. break;
  28511. }
  28512. }
  28513. }
  28514. if (!needToRecreate) {
  28515. return this.subMeshes[0];
  28516. }
  28517. }
  28518. this.releaseSubMeshes();
  28519. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28520. };
  28521. Mesh.prototype.subdivide = function (count) {
  28522. if (count < 1) {
  28523. return;
  28524. }
  28525. var totalIndices = this.getTotalIndices();
  28526. var subdivisionSize = (totalIndices / count) | 0;
  28527. var offset = 0;
  28528. // Ensure that subdivisionSize is a multiple of 3
  28529. while (subdivisionSize % 3 !== 0) {
  28530. subdivisionSize++;
  28531. }
  28532. this.releaseSubMeshes();
  28533. for (var index = 0; index < count; index++) {
  28534. if (offset >= totalIndices) {
  28535. break;
  28536. }
  28537. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28538. offset += subdivisionSize;
  28539. }
  28540. this.synchronizeInstances();
  28541. };
  28542. /**
  28543. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28544. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28545. * The `data` are either a numeric array either a Float32Array.
  28546. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28547. * 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).
  28548. * Note that a new underlying VertexBuffer object is created each call.
  28549. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28550. *
  28551. * Possible `kind` values :
  28552. * - BABYLON.VertexBuffer.PositionKind
  28553. * - BABYLON.VertexBuffer.UVKind
  28554. * - BABYLON.VertexBuffer.UV2Kind
  28555. * - BABYLON.VertexBuffer.UV3Kind
  28556. * - BABYLON.VertexBuffer.UV4Kind
  28557. * - BABYLON.VertexBuffer.UV5Kind
  28558. * - BABYLON.VertexBuffer.UV6Kind
  28559. * - BABYLON.VertexBuffer.ColorKind
  28560. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28561. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28562. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28563. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28564. *
  28565. * Returns the Mesh.
  28566. */
  28567. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28568. if (updatable === void 0) { updatable = false; }
  28569. if (!this._geometry) {
  28570. var vertexData = new BABYLON.VertexData();
  28571. vertexData.set(data, kind);
  28572. var scene = this.getScene();
  28573. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28574. }
  28575. else {
  28576. this._geometry.setVerticesData(kind, data, updatable, stride);
  28577. }
  28578. return this;
  28579. };
  28580. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28581. if (updatable === void 0) { updatable = true; }
  28582. var vb = this.getVertexBuffer(kind);
  28583. if (!vb || vb.isUpdatable() === updatable) {
  28584. return;
  28585. }
  28586. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28587. };
  28588. /**
  28589. * Sets the mesh VertexBuffer.
  28590. * Returns the Mesh.
  28591. */
  28592. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28593. if (!this._geometry) {
  28594. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28595. }
  28596. this._geometry.setVerticesBuffer(buffer);
  28597. return this;
  28598. };
  28599. /**
  28600. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28601. * If the mesh has no geometry, it is simply returned as it is.
  28602. * The `data` are either a numeric array either a Float32Array.
  28603. * No new underlying VertexBuffer object is created.
  28604. * 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.
  28605. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28606. *
  28607. * Possible `kind` values :
  28608. * - BABYLON.VertexBuffer.PositionKind
  28609. * - BABYLON.VertexBuffer.UVKind
  28610. * - BABYLON.VertexBuffer.UV2Kind
  28611. * - BABYLON.VertexBuffer.UV3Kind
  28612. * - BABYLON.VertexBuffer.UV4Kind
  28613. * - BABYLON.VertexBuffer.UV5Kind
  28614. * - BABYLON.VertexBuffer.UV6Kind
  28615. * - BABYLON.VertexBuffer.ColorKind
  28616. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28617. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28618. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28619. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28620. *
  28621. * Returns the Mesh.
  28622. */
  28623. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28624. if (!this._geometry) {
  28625. return this;
  28626. }
  28627. if (!makeItUnique) {
  28628. this._geometry.updateVerticesData(kind, data, updateExtends);
  28629. }
  28630. else {
  28631. this.makeGeometryUnique();
  28632. this.updateVerticesData(kind, data, updateExtends, false);
  28633. }
  28634. return this;
  28635. };
  28636. /**
  28637. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28638. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28639. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28640. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28641. * Returns the Mesh.
  28642. */
  28643. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28644. if (computeNormals === void 0) { computeNormals = true; }
  28645. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28646. if (!positions) {
  28647. return this;
  28648. }
  28649. positionFunction(positions);
  28650. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28651. if (computeNormals) {
  28652. var indices = this.getIndices();
  28653. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28654. if (!normals) {
  28655. return this;
  28656. }
  28657. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28658. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28659. }
  28660. return this;
  28661. };
  28662. /**
  28663. * Creates a un-shared specific occurence of the geometry for the mesh.
  28664. * Returns the Mesh.
  28665. */
  28666. Mesh.prototype.makeGeometryUnique = function () {
  28667. if (!this._geometry) {
  28668. return this;
  28669. }
  28670. var oldGeometry = this._geometry;
  28671. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28672. oldGeometry.releaseForMesh(this, true);
  28673. geometry.applyToMesh(this);
  28674. return this;
  28675. };
  28676. /**
  28677. * Sets the mesh indices.
  28678. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28679. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28680. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28681. * This method creates a new index buffer each call.
  28682. * Returns the Mesh.
  28683. */
  28684. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28685. if (totalVertices === void 0) { totalVertices = null; }
  28686. if (updatable === void 0) { updatable = false; }
  28687. if (!this._geometry) {
  28688. var vertexData = new BABYLON.VertexData();
  28689. vertexData.indices = indices;
  28690. var scene = this.getScene();
  28691. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28692. }
  28693. else {
  28694. this._geometry.setIndices(indices, totalVertices, updatable);
  28695. }
  28696. return this;
  28697. };
  28698. /**
  28699. * Update the current index buffer
  28700. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28701. * Returns the Mesh.
  28702. */
  28703. Mesh.prototype.updateIndices = function (indices, offset) {
  28704. if (!this._geometry) {
  28705. return this;
  28706. }
  28707. this._geometry.updateIndices(indices, offset);
  28708. return this;
  28709. };
  28710. /**
  28711. * Invert the geometry to move from a right handed system to a left handed one.
  28712. * Returns the Mesh.
  28713. */
  28714. Mesh.prototype.toLeftHanded = function () {
  28715. if (!this._geometry) {
  28716. return this;
  28717. }
  28718. this._geometry.toLeftHanded();
  28719. return this;
  28720. };
  28721. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28722. if (!this._geometry) {
  28723. return this;
  28724. }
  28725. var engine = this.getScene().getEngine();
  28726. // Wireframe
  28727. var indexToBind;
  28728. if (this._unIndexed) {
  28729. indexToBind = null;
  28730. }
  28731. else {
  28732. switch (fillMode) {
  28733. case BABYLON.Material.PointFillMode:
  28734. indexToBind = null;
  28735. break;
  28736. case BABYLON.Material.WireFrameFillMode:
  28737. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28738. break;
  28739. default:
  28740. case BABYLON.Material.TriangleFillMode:
  28741. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28742. break;
  28743. }
  28744. }
  28745. // VBOs
  28746. this._geometry._bind(effect, indexToBind);
  28747. return this;
  28748. };
  28749. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28750. if (alternate === void 0) { alternate = false; }
  28751. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28752. return this;
  28753. }
  28754. this.onBeforeDrawObservable.notifyObservers(this);
  28755. var scene = this.getScene();
  28756. var engine = scene.getEngine();
  28757. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28758. // or triangles as points
  28759. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28760. }
  28761. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28762. // Triangles as wireframe
  28763. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28764. }
  28765. else {
  28766. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28767. }
  28768. if (scene._isAlternateRenderingEnabled && !alternate) {
  28769. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28770. if (!effect || !scene.activeCamera) {
  28771. return this;
  28772. }
  28773. scene._switchToAlternateCameraConfiguration(true);
  28774. this._effectiveMaterial.bindView(effect);
  28775. this._effectiveMaterial.bindViewProjection(effect);
  28776. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28777. this._draw(subMesh, fillMode, instancesCount, true);
  28778. engine.setViewport(scene.activeCamera.viewport);
  28779. scene._switchToAlternateCameraConfiguration(false);
  28780. this._effectiveMaterial.bindView(effect);
  28781. this._effectiveMaterial.bindViewProjection(effect);
  28782. }
  28783. return this;
  28784. };
  28785. /**
  28786. * Registers for this mesh a javascript function called just before the rendering process.
  28787. * This function is passed the current mesh.
  28788. * Return the Mesh.
  28789. */
  28790. Mesh.prototype.registerBeforeRender = function (func) {
  28791. this.onBeforeRenderObservable.add(func);
  28792. return this;
  28793. };
  28794. /**
  28795. * Disposes a previously registered javascript function called before the rendering.
  28796. * This function is passed the current mesh.
  28797. * Returns the Mesh.
  28798. */
  28799. Mesh.prototype.unregisterBeforeRender = function (func) {
  28800. this.onBeforeRenderObservable.removeCallback(func);
  28801. return this;
  28802. };
  28803. /**
  28804. * Registers for this mesh a javascript function called just after the rendering is complete.
  28805. * This function is passed the current mesh.
  28806. * Returns the Mesh.
  28807. */
  28808. Mesh.prototype.registerAfterRender = function (func) {
  28809. this.onAfterRenderObservable.add(func);
  28810. return this;
  28811. };
  28812. /**
  28813. * Disposes a previously registered javascript function called after the rendering.
  28814. * This function is passed the current mesh.
  28815. * Return the Mesh.
  28816. */
  28817. Mesh.prototype.unregisterAfterRender = function (func) {
  28818. this.onAfterRenderObservable.removeCallback(func);
  28819. return this;
  28820. };
  28821. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28822. var scene = this.getScene();
  28823. this._batchCache.mustReturn = false;
  28824. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28825. this._batchCache.visibleInstances[subMeshId] = null;
  28826. if (this._visibleInstances) {
  28827. var currentRenderId = scene.getRenderId();
  28828. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28829. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28830. var selfRenderId = this._renderId;
  28831. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28832. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28833. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28834. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28835. }
  28836. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28837. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28838. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28839. this._batchCache.mustReturn = true;
  28840. return this._batchCache;
  28841. }
  28842. if (currentRenderId !== selfRenderId) {
  28843. this._batchCache.renderSelf[subMeshId] = false;
  28844. }
  28845. }
  28846. this._renderIdForInstances[subMeshId] = currentRenderId;
  28847. }
  28848. return this._batchCache;
  28849. };
  28850. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28851. var visibleInstances = batch.visibleInstances[subMesh._id];
  28852. if (!visibleInstances) {
  28853. return this;
  28854. }
  28855. var matricesCount = visibleInstances.length + 1;
  28856. var bufferSize = matricesCount * 16 * 4;
  28857. var currentInstancesBufferSize = this._instancesBufferSize;
  28858. var instancesBuffer = this._instancesBuffer;
  28859. while (this._instancesBufferSize < bufferSize) {
  28860. this._instancesBufferSize *= 2;
  28861. }
  28862. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28863. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28864. }
  28865. var offset = 0;
  28866. var instancesCount = 0;
  28867. var world = this.getWorldMatrix();
  28868. if (batch.renderSelf[subMesh._id]) {
  28869. world.copyToArray(this._instancesData, offset);
  28870. offset += 16;
  28871. instancesCount++;
  28872. }
  28873. if (visibleInstances) {
  28874. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28875. var instance = visibleInstances[instanceIndex];
  28876. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28877. offset += 16;
  28878. instancesCount++;
  28879. }
  28880. }
  28881. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28882. if (instancesBuffer) {
  28883. instancesBuffer.dispose();
  28884. }
  28885. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28886. this._instancesBuffer = instancesBuffer;
  28887. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28888. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28889. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28890. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28891. }
  28892. else {
  28893. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28894. }
  28895. this._bind(subMesh, effect, fillMode);
  28896. this._draw(subMesh, fillMode, instancesCount);
  28897. engine.unbindInstanceAttributes();
  28898. return this;
  28899. };
  28900. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28901. var scene = this.getScene();
  28902. var engine = scene.getEngine();
  28903. if (hardwareInstancedRendering) {
  28904. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28905. }
  28906. else {
  28907. if (batch.renderSelf[subMesh._id]) {
  28908. // Draw
  28909. if (onBeforeDraw) {
  28910. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28911. }
  28912. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28913. }
  28914. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28915. if (visibleInstancesForSubMesh) {
  28916. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28917. var instance = visibleInstancesForSubMesh[instanceIndex];
  28918. // World
  28919. var world = instance.getWorldMatrix();
  28920. if (onBeforeDraw) {
  28921. onBeforeDraw(true, world, effectiveMaterial);
  28922. }
  28923. // Draw
  28924. this._draw(subMesh, fillMode);
  28925. }
  28926. }
  28927. }
  28928. return this;
  28929. };
  28930. /**
  28931. * Triggers the draw call for the mesh.
  28932. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28933. * Returns the Mesh.
  28934. */
  28935. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28936. this.checkOcclusionQuery();
  28937. if (this._isOccluded) {
  28938. return this;
  28939. }
  28940. var scene = this.getScene();
  28941. // Managing instances
  28942. var batch = this._getInstancesRenderList(subMesh._id);
  28943. if (batch.mustReturn) {
  28944. return this;
  28945. }
  28946. // Checking geometry state
  28947. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28948. return this;
  28949. }
  28950. this.onBeforeRenderObservable.notifyObservers(this);
  28951. var engine = scene.getEngine();
  28952. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28953. // Material
  28954. var material = subMesh.getMaterial();
  28955. if (!material) {
  28956. return this;
  28957. }
  28958. this._effectiveMaterial = material;
  28959. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28960. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28961. return this;
  28962. }
  28963. }
  28964. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28965. return this;
  28966. }
  28967. // Alpha mode
  28968. if (enableAlphaMode) {
  28969. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28970. }
  28971. // Outline - step 1
  28972. var savedDepthWrite = engine.getDepthWrite();
  28973. if (this.renderOutline) {
  28974. engine.setDepthWrite(false);
  28975. scene.getOutlineRenderer().render(subMesh, batch);
  28976. engine.setDepthWrite(savedDepthWrite);
  28977. }
  28978. var effect;
  28979. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28980. effect = subMesh.effect;
  28981. }
  28982. else {
  28983. effect = this._effectiveMaterial.getEffect();
  28984. }
  28985. if (!effect) {
  28986. return this;
  28987. }
  28988. var sideOrientation = this.overrideMaterialSideOrientation;
  28989. if (sideOrientation == null) {
  28990. sideOrientation = this._effectiveMaterial.sideOrientation;
  28991. if (this._getWorldMatrixDeterminant() < 0) {
  28992. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28993. }
  28994. }
  28995. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28996. if (this._effectiveMaterial.forceDepthWrite) {
  28997. engine.setDepthWrite(true);
  28998. }
  28999. // Bind
  29000. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29001. if (!hardwareInstancedRendering) {
  29002. this._bind(subMesh, effect, fillMode);
  29003. }
  29004. var world = this.getWorldMatrix();
  29005. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29006. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29007. }
  29008. else {
  29009. this._effectiveMaterial.bind(world, this);
  29010. }
  29011. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29012. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29013. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29014. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29015. }
  29016. // Draw
  29017. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29018. // Unbind
  29019. this._effectiveMaterial.unbind();
  29020. // Outline - step 2
  29021. if (this.renderOutline && savedDepthWrite) {
  29022. engine.setDepthWrite(true);
  29023. engine.setColorWrite(false);
  29024. scene.getOutlineRenderer().render(subMesh, batch);
  29025. engine.setColorWrite(true);
  29026. }
  29027. // Overlay
  29028. if (this.renderOverlay) {
  29029. var currentMode = engine.getAlphaMode();
  29030. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29031. scene.getOutlineRenderer().render(subMesh, batch, true);
  29032. engine.setAlphaMode(currentMode);
  29033. }
  29034. this.onAfterRenderObservable.notifyObservers(this);
  29035. return this;
  29036. };
  29037. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29038. if (isInstance && effectiveMaterial) {
  29039. effectiveMaterial.bindOnlyWorldMatrix(world);
  29040. }
  29041. };
  29042. /**
  29043. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29044. */
  29045. Mesh.prototype.getEmittedParticleSystems = function () {
  29046. var results = new Array();
  29047. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29048. var particleSystem = this.getScene().particleSystems[index];
  29049. if (particleSystem.emitter === this) {
  29050. results.push(particleSystem);
  29051. }
  29052. }
  29053. return results;
  29054. };
  29055. /**
  29056. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29057. */
  29058. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29059. var results = new Array();
  29060. var descendants = this.getDescendants();
  29061. descendants.push(this);
  29062. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29063. var particleSystem = this.getScene().particleSystems[index];
  29064. var emitter = particleSystem.emitter;
  29065. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29066. results.push(particleSystem);
  29067. }
  29068. }
  29069. return results;
  29070. };
  29071. Mesh.prototype._checkDelayState = function () {
  29072. var scene = this.getScene();
  29073. if (this._geometry) {
  29074. this._geometry.load(scene);
  29075. }
  29076. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29077. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29078. this._queueLoad(scene);
  29079. }
  29080. return this;
  29081. };
  29082. Mesh.prototype._queueLoad = function (scene) {
  29083. var _this = this;
  29084. scene._addPendingData(this);
  29085. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29086. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29087. if (data instanceof ArrayBuffer) {
  29088. _this._delayLoadingFunction(data, _this);
  29089. }
  29090. else {
  29091. _this._delayLoadingFunction(JSON.parse(data), _this);
  29092. }
  29093. _this.instances.forEach(function (instance) {
  29094. instance._syncSubMeshes();
  29095. });
  29096. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29097. scene._removePendingData(_this);
  29098. }, function () { }, scene.database, getBinaryData);
  29099. return this;
  29100. };
  29101. /**
  29102. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29103. */
  29104. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29105. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29106. return false;
  29107. }
  29108. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29109. return false;
  29110. }
  29111. this._checkDelayState();
  29112. return true;
  29113. };
  29114. /**
  29115. * Sets the mesh material by the material or multiMaterial `id` property.
  29116. * The material `id` is a string identifying the material or the multiMaterial.
  29117. * This method returns the Mesh.
  29118. */
  29119. Mesh.prototype.setMaterialByID = function (id) {
  29120. var materials = this.getScene().materials;
  29121. var index;
  29122. for (index = materials.length - 1; index > -1; index--) {
  29123. if (materials[index].id === id) {
  29124. this.material = materials[index];
  29125. return this;
  29126. }
  29127. }
  29128. // Multi
  29129. var multiMaterials = this.getScene().multiMaterials;
  29130. for (index = multiMaterials.length - 1; index > -1; index--) {
  29131. if (multiMaterials[index].id === id) {
  29132. this.material = multiMaterials[index];
  29133. return this;
  29134. }
  29135. }
  29136. return this;
  29137. };
  29138. /**
  29139. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29140. */
  29141. Mesh.prototype.getAnimatables = function () {
  29142. var results = new Array();
  29143. if (this.material) {
  29144. results.push(this.material);
  29145. }
  29146. if (this.skeleton) {
  29147. results.push(this.skeleton);
  29148. }
  29149. return results;
  29150. };
  29151. /**
  29152. * Modifies the mesh geometry according to the passed transformation matrix.
  29153. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29154. * The mesh normals are modified accordingly the same transformation.
  29155. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29156. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29157. * Returns the Mesh.
  29158. */
  29159. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29160. // Position
  29161. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29162. return this;
  29163. }
  29164. var submeshes = this.subMeshes.splice(0);
  29165. this._resetPointsArrayCache();
  29166. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29167. var temp = new Array();
  29168. var index;
  29169. for (index = 0; index < data.length; index += 3) {
  29170. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29171. }
  29172. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29173. // Normals
  29174. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29175. return this;
  29176. }
  29177. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29178. temp = [];
  29179. for (index = 0; index < data.length; index += 3) {
  29180. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29181. }
  29182. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29183. // flip faces?
  29184. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29185. this.flipFaces();
  29186. }
  29187. // Restore submeshes
  29188. this.releaseSubMeshes();
  29189. this.subMeshes = submeshes;
  29190. return this;
  29191. };
  29192. /**
  29193. * Modifies the mesh geometry according to its own current World Matrix.
  29194. * The mesh World Matrix is then reset.
  29195. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29196. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29197. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29198. * Returns the Mesh.
  29199. */
  29200. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29201. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29202. this.scaling.copyFromFloats(1, 1, 1);
  29203. this.position.copyFromFloats(0, 0, 0);
  29204. this.rotation.copyFromFloats(0, 0, 0);
  29205. //only if quaternion is already set
  29206. if (this.rotationQuaternion) {
  29207. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29208. }
  29209. this._worldMatrix = BABYLON.Matrix.Identity();
  29210. return this;
  29211. };
  29212. Object.defineProperty(Mesh.prototype, "_positions", {
  29213. // Cache
  29214. get: function () {
  29215. if (this._geometry) {
  29216. return this._geometry._positions;
  29217. }
  29218. return null;
  29219. },
  29220. enumerable: true,
  29221. configurable: true
  29222. });
  29223. Mesh.prototype._resetPointsArrayCache = function () {
  29224. if (this._geometry) {
  29225. this._geometry._resetPointsArrayCache();
  29226. }
  29227. return this;
  29228. };
  29229. Mesh.prototype._generatePointsArray = function () {
  29230. if (this._geometry) {
  29231. return this._geometry._generatePointsArray();
  29232. }
  29233. return false;
  29234. };
  29235. /**
  29236. * Returns a new Mesh object generated from the current mesh properties.
  29237. * This method must not get confused with createInstance().
  29238. * The parameter `name` is a string, the name given to the new mesh.
  29239. * The optional parameter `newParent` can be any Node object (default `null`).
  29240. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29241. * 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.
  29242. */
  29243. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29244. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29245. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29246. };
  29247. /**
  29248. * Releases resources associated with this mesh.
  29249. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29250. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29251. */
  29252. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29253. var _this = this;
  29254. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29255. this.morphTargetManager = null;
  29256. if (this._geometry) {
  29257. this._geometry.releaseForMesh(this, true);
  29258. }
  29259. // Sources
  29260. var meshes = this.getScene().meshes;
  29261. meshes.forEach(function (abstractMesh) {
  29262. var mesh = abstractMesh;
  29263. if (mesh._source && mesh._source === _this) {
  29264. mesh._source = null;
  29265. }
  29266. });
  29267. this._source = null;
  29268. // Instances
  29269. if (this._instancesBuffer) {
  29270. this._instancesBuffer.dispose();
  29271. this._instancesBuffer = null;
  29272. }
  29273. while (this.instances.length) {
  29274. this.instances[0].dispose();
  29275. }
  29276. // Effect layers.
  29277. var effectLayers = this.getScene().effectLayers;
  29278. for (var i = 0; i < effectLayers.length; i++) {
  29279. var effectLayer = effectLayers[i];
  29280. if (effectLayer) {
  29281. effectLayer._disposeMesh(this);
  29282. }
  29283. }
  29284. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29285. };
  29286. /**
  29287. * Modifies the mesh geometry according to a displacement map.
  29288. * 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.
  29289. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29290. * This method returns nothing.
  29291. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29292. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29293. * 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.
  29294. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29295. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29296. *
  29297. * Returns the Mesh.
  29298. */
  29299. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29300. var _this = this;
  29301. var scene = this.getScene();
  29302. var onload = function (img) {
  29303. // Getting height map data
  29304. var canvas = document.createElement("canvas");
  29305. var context = canvas.getContext("2d");
  29306. var heightMapWidth = img.width;
  29307. var heightMapHeight = img.height;
  29308. canvas.width = heightMapWidth;
  29309. canvas.height = heightMapHeight;
  29310. context.drawImage(img, 0, 0);
  29311. // Create VertexData from map data
  29312. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29313. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29314. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29315. //execute success callback, if set
  29316. if (onSuccess) {
  29317. onSuccess(_this);
  29318. }
  29319. };
  29320. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29321. return this;
  29322. };
  29323. /**
  29324. * Modifies the mesh geometry according to a displacementMap buffer.
  29325. * 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.
  29326. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29327. * This method returns nothing.
  29328. * 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.
  29329. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29330. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29331. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29332. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29333. *
  29334. * Returns the Mesh.
  29335. */
  29336. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29337. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29338. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29339. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29340. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29341. return this;
  29342. }
  29343. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29344. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29345. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29346. var position = BABYLON.Vector3.Zero();
  29347. var normal = BABYLON.Vector3.Zero();
  29348. var uv = BABYLON.Vector2.Zero();
  29349. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29350. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29351. for (var index = 0; index < positions.length; index += 3) {
  29352. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29353. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29354. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29355. // Compute height
  29356. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29357. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29358. var pos = (u + v * heightMapWidth) * 4;
  29359. var r = buffer[pos] / 255.0;
  29360. var g = buffer[pos + 1] / 255.0;
  29361. var b = buffer[pos + 2] / 255.0;
  29362. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29363. normal.normalize();
  29364. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29365. position = position.add(normal);
  29366. position.toArray(positions, index);
  29367. }
  29368. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29369. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29370. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29371. return this;
  29372. };
  29373. /**
  29374. * Modify the mesh to get a flat shading rendering.
  29375. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29376. * This method returns the Mesh.
  29377. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29378. */
  29379. Mesh.prototype.convertToFlatShadedMesh = function () {
  29380. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29381. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29382. var kinds = this.getVerticesDataKinds();
  29383. var vbs = {};
  29384. var data = {};
  29385. var newdata = {};
  29386. var updatableNormals = false;
  29387. var kindIndex;
  29388. var kind;
  29389. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29390. kind = kinds[kindIndex];
  29391. var vertexBuffer = this.getVertexBuffer(kind);
  29392. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29393. updatableNormals = vertexBuffer.isUpdatable();
  29394. kinds.splice(kindIndex, 1);
  29395. kindIndex--;
  29396. continue;
  29397. }
  29398. vbs[kind] = vertexBuffer;
  29399. data[kind] = vbs[kind].getData();
  29400. newdata[kind] = [];
  29401. }
  29402. // Save previous submeshes
  29403. var previousSubmeshes = this.subMeshes.slice(0);
  29404. var indices = this.getIndices();
  29405. var totalIndices = this.getTotalIndices();
  29406. // Generating unique vertices per face
  29407. var index;
  29408. for (index = 0; index < totalIndices; index++) {
  29409. var vertexIndex = indices[index];
  29410. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29411. kind = kinds[kindIndex];
  29412. var stride = vbs[kind].getStrideSize();
  29413. for (var offset = 0; offset < stride; offset++) {
  29414. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29415. }
  29416. }
  29417. }
  29418. // Updating faces & normal
  29419. var normals = [];
  29420. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29421. for (index = 0; index < totalIndices; index += 3) {
  29422. indices[index] = index;
  29423. indices[index + 1] = index + 1;
  29424. indices[index + 2] = index + 2;
  29425. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29426. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29427. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29428. var p1p2 = p1.subtract(p2);
  29429. var p3p2 = p3.subtract(p2);
  29430. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29431. // Store same normals for every vertex
  29432. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29433. normals.push(normal.x);
  29434. normals.push(normal.y);
  29435. normals.push(normal.z);
  29436. }
  29437. }
  29438. this.setIndices(indices);
  29439. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29440. // Updating vertex buffers
  29441. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29442. kind = kinds[kindIndex];
  29443. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29444. }
  29445. // Updating submeshes
  29446. this.releaseSubMeshes();
  29447. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29448. var previousOne = previousSubmeshes[submeshIndex];
  29449. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29450. }
  29451. this.synchronizeInstances();
  29452. return this;
  29453. };
  29454. /**
  29455. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29456. * In other words, more vertices, no more indices and a single bigger VBO.
  29457. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29458. * Returns the Mesh.
  29459. */
  29460. Mesh.prototype.convertToUnIndexedMesh = function () {
  29461. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29462. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29463. var kinds = this.getVerticesDataKinds();
  29464. var vbs = {};
  29465. var data = {};
  29466. var newdata = {};
  29467. var kindIndex;
  29468. var kind;
  29469. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29470. kind = kinds[kindIndex];
  29471. var vertexBuffer = this.getVertexBuffer(kind);
  29472. vbs[kind] = vertexBuffer;
  29473. data[kind] = vbs[kind].getData();
  29474. newdata[kind] = [];
  29475. }
  29476. // Save previous submeshes
  29477. var previousSubmeshes = this.subMeshes.slice(0);
  29478. var indices = this.getIndices();
  29479. var totalIndices = this.getTotalIndices();
  29480. // Generating unique vertices per face
  29481. var index;
  29482. for (index = 0; index < totalIndices; index++) {
  29483. var vertexIndex = indices[index];
  29484. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29485. kind = kinds[kindIndex];
  29486. var stride = vbs[kind].getStrideSize();
  29487. for (var offset = 0; offset < stride; offset++) {
  29488. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29489. }
  29490. }
  29491. }
  29492. // Updating indices
  29493. for (index = 0; index < totalIndices; index += 3) {
  29494. indices[index] = index;
  29495. indices[index + 1] = index + 1;
  29496. indices[index + 2] = index + 2;
  29497. }
  29498. this.setIndices(indices);
  29499. // Updating vertex buffers
  29500. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29501. kind = kinds[kindIndex];
  29502. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29503. }
  29504. // Updating submeshes
  29505. this.releaseSubMeshes();
  29506. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29507. var previousOne = previousSubmeshes[submeshIndex];
  29508. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29509. }
  29510. this._unIndexed = true;
  29511. this.synchronizeInstances();
  29512. return this;
  29513. };
  29514. /**
  29515. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29516. * This method returns the Mesh.
  29517. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29518. */
  29519. Mesh.prototype.flipFaces = function (flipNormals) {
  29520. if (flipNormals === void 0) { flipNormals = false; }
  29521. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29522. var i;
  29523. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29524. for (i = 0; i < vertex_data.normals.length; i++) {
  29525. vertex_data.normals[i] *= -1;
  29526. }
  29527. }
  29528. if (vertex_data.indices) {
  29529. var temp;
  29530. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29531. // reassign indices
  29532. temp = vertex_data.indices[i + 1];
  29533. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29534. vertex_data.indices[i + 2] = temp;
  29535. }
  29536. }
  29537. vertex_data.applyToMesh(this);
  29538. return this;
  29539. };
  29540. // Instances
  29541. /**
  29542. * Creates a new InstancedMesh object from the mesh model.
  29543. * An instance shares the same properties and the same material than its model.
  29544. * Only these properties of each instance can then be set individually :
  29545. * - position
  29546. * - rotation
  29547. * - rotationQuaternion
  29548. * - setPivotMatrix
  29549. * - scaling
  29550. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29551. * Warning : this method is not supported for Line mesh and LineSystem
  29552. */
  29553. Mesh.prototype.createInstance = function (name) {
  29554. return new BABYLON.InstancedMesh(name, this);
  29555. };
  29556. /**
  29557. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29558. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29559. * This method returns the Mesh.
  29560. */
  29561. Mesh.prototype.synchronizeInstances = function () {
  29562. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29563. var instance = this.instances[instanceIndex];
  29564. instance._syncSubMeshes();
  29565. }
  29566. return this;
  29567. };
  29568. /**
  29569. * Simplify the mesh according to the given array of settings.
  29570. * Function will return immediately and will simplify async. It returns the Mesh.
  29571. * @param settings a collection of simplification settings.
  29572. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29573. * @param type the type of simplification to run.
  29574. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29575. */
  29576. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29577. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29578. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29579. this.getScene().simplificationQueue.addTask({
  29580. settings: settings,
  29581. parallelProcessing: parallelProcessing,
  29582. mesh: this,
  29583. simplificationType: simplificationType,
  29584. successCallback: successCallback
  29585. });
  29586. return this;
  29587. };
  29588. /**
  29589. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29590. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29591. * This should be used together with the simplification to avoid disappearing triangles.
  29592. * Returns the Mesh.
  29593. * @param successCallback an optional success callback to be called after the optimization finished.
  29594. */
  29595. Mesh.prototype.optimizeIndices = function (successCallback) {
  29596. var _this = this;
  29597. var indices = this.getIndices();
  29598. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29599. if (!positions || !indices) {
  29600. return this;
  29601. }
  29602. var vectorPositions = new Array();
  29603. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29604. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29605. }
  29606. var dupes = new Array();
  29607. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29608. var realPos = vectorPositions.length - 1 - iteration;
  29609. var testedPosition = vectorPositions[realPos];
  29610. for (var j = 0; j < realPos; ++j) {
  29611. var againstPosition = vectorPositions[j];
  29612. if (testedPosition.equals(againstPosition)) {
  29613. dupes[realPos] = j;
  29614. break;
  29615. }
  29616. }
  29617. }, function () {
  29618. for (var i = 0; i < indices.length; ++i) {
  29619. indices[i] = dupes[indices[i]] || indices[i];
  29620. }
  29621. //indices are now reordered
  29622. var originalSubMeshes = _this.subMeshes.slice(0);
  29623. _this.setIndices(indices);
  29624. _this.subMeshes = originalSubMeshes;
  29625. if (successCallback) {
  29626. successCallback(_this);
  29627. }
  29628. });
  29629. return this;
  29630. };
  29631. Mesh.prototype.serialize = function (serializationObject) {
  29632. serializationObject.name = this.name;
  29633. serializationObject.id = this.id;
  29634. serializationObject.type = this.getClassName();
  29635. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29636. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29637. }
  29638. serializationObject.position = this.position.asArray();
  29639. if (this.rotationQuaternion) {
  29640. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29641. }
  29642. else if (this.rotation) {
  29643. serializationObject.rotation = this.rotation.asArray();
  29644. }
  29645. serializationObject.scaling = this.scaling.asArray();
  29646. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29647. serializationObject.isEnabled = this.isEnabled(false);
  29648. serializationObject.isVisible = this.isVisible;
  29649. serializationObject.infiniteDistance = this.infiniteDistance;
  29650. serializationObject.pickable = this.isPickable;
  29651. serializationObject.receiveShadows = this.receiveShadows;
  29652. serializationObject.billboardMode = this.billboardMode;
  29653. serializationObject.visibility = this.visibility;
  29654. serializationObject.checkCollisions = this.checkCollisions;
  29655. serializationObject.isBlocker = this.isBlocker;
  29656. // Parent
  29657. if (this.parent) {
  29658. serializationObject.parentId = this.parent.id;
  29659. }
  29660. // Geometry
  29661. serializationObject.isUnIndexed = this.isUnIndexed;
  29662. var geometry = this._geometry;
  29663. if (geometry) {
  29664. var geometryId = geometry.id;
  29665. serializationObject.geometryId = geometryId;
  29666. // SubMeshes
  29667. serializationObject.subMeshes = [];
  29668. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29669. var subMesh = this.subMeshes[subIndex];
  29670. serializationObject.subMeshes.push({
  29671. materialIndex: subMesh.materialIndex,
  29672. verticesStart: subMesh.verticesStart,
  29673. verticesCount: subMesh.verticesCount,
  29674. indexStart: subMesh.indexStart,
  29675. indexCount: subMesh.indexCount
  29676. });
  29677. }
  29678. }
  29679. // Material
  29680. if (this.material) {
  29681. serializationObject.materialId = this.material.id;
  29682. }
  29683. else {
  29684. this.material = null;
  29685. }
  29686. // Morph targets
  29687. if (this.morphTargetManager) {
  29688. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29689. }
  29690. // Skeleton
  29691. if (this.skeleton) {
  29692. serializationObject.skeletonId = this.skeleton.id;
  29693. }
  29694. // Physics
  29695. //TODO implement correct serialization for physics impostors.
  29696. var impostor = this.getPhysicsImpostor();
  29697. if (impostor) {
  29698. serializationObject.physicsMass = impostor.getParam("mass");
  29699. serializationObject.physicsFriction = impostor.getParam("friction");
  29700. serializationObject.physicsRestitution = impostor.getParam("mass");
  29701. serializationObject.physicsImpostor = impostor.type;
  29702. }
  29703. // Metadata
  29704. if (this.metadata) {
  29705. serializationObject.metadata = this.metadata;
  29706. }
  29707. // Instances
  29708. serializationObject.instances = [];
  29709. for (var index = 0; index < this.instances.length; index++) {
  29710. var instance = this.instances[index];
  29711. var serializationInstance = {
  29712. name: instance.name,
  29713. id: instance.id,
  29714. position: instance.position.asArray(),
  29715. scaling: instance.scaling.asArray()
  29716. };
  29717. if (instance.rotationQuaternion) {
  29718. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29719. }
  29720. else if (instance.rotation) {
  29721. serializationInstance.rotation = instance.rotation.asArray();
  29722. }
  29723. serializationObject.instances.push(serializationInstance);
  29724. // Animations
  29725. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29726. serializationInstance.ranges = instance.serializeAnimationRanges();
  29727. }
  29728. //
  29729. // Animations
  29730. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29731. serializationObject.ranges = this.serializeAnimationRanges();
  29732. // Layer mask
  29733. serializationObject.layerMask = this.layerMask;
  29734. // Alpha
  29735. serializationObject.alphaIndex = this.alphaIndex;
  29736. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29737. // Overlay
  29738. serializationObject.overlayAlpha = this.overlayAlpha;
  29739. serializationObject.overlayColor = this.overlayColor.asArray();
  29740. serializationObject.renderOverlay = this.renderOverlay;
  29741. // Fog
  29742. serializationObject.applyFog = this.applyFog;
  29743. // Action Manager
  29744. if (this.actionManager) {
  29745. serializationObject.actions = this.actionManager.serialize(this.name);
  29746. }
  29747. };
  29748. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29749. if (!this.geometry) {
  29750. return;
  29751. }
  29752. this._markSubMeshesAsAttributesDirty();
  29753. var morphTargetManager = this._morphTargetManager;
  29754. if (morphTargetManager && morphTargetManager.vertexCount) {
  29755. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29756. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29757. this.morphTargetManager = null;
  29758. return;
  29759. }
  29760. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29761. var morphTarget = morphTargetManager.getActiveTarget(index);
  29762. var positions = morphTarget.getPositions();
  29763. if (!positions) {
  29764. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29765. return;
  29766. }
  29767. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29768. var normals = morphTarget.getNormals();
  29769. if (normals) {
  29770. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29771. }
  29772. var tangents = morphTarget.getTangents();
  29773. if (tangents) {
  29774. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29775. }
  29776. }
  29777. }
  29778. else {
  29779. var index = 0;
  29780. // Positions
  29781. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29782. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29783. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29784. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29785. }
  29786. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29787. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29788. }
  29789. index++;
  29790. }
  29791. }
  29792. };
  29793. // Statics
  29794. /**
  29795. * Returns a new Mesh object parsed from the source provided.
  29796. * The parameter `parsedMesh` is the source.
  29797. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29798. */
  29799. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29800. var mesh;
  29801. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29802. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29803. }
  29804. else {
  29805. mesh = new Mesh(parsedMesh.name, scene);
  29806. }
  29807. mesh.id = parsedMesh.id;
  29808. if (BABYLON.Tags) {
  29809. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29810. }
  29811. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29812. if (parsedMesh.metadata !== undefined) {
  29813. mesh.metadata = parsedMesh.metadata;
  29814. }
  29815. if (parsedMesh.rotationQuaternion) {
  29816. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29817. }
  29818. else if (parsedMesh.rotation) {
  29819. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29820. }
  29821. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29822. if (parsedMesh.localMatrix) {
  29823. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29824. }
  29825. else if (parsedMesh.pivotMatrix) {
  29826. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29827. }
  29828. mesh.setEnabled(parsedMesh.isEnabled);
  29829. mesh.isVisible = parsedMesh.isVisible;
  29830. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29831. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29832. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29833. if (parsedMesh.applyFog !== undefined) {
  29834. mesh.applyFog = parsedMesh.applyFog;
  29835. }
  29836. if (parsedMesh.pickable !== undefined) {
  29837. mesh.isPickable = parsedMesh.pickable;
  29838. }
  29839. if (parsedMesh.alphaIndex !== undefined) {
  29840. mesh.alphaIndex = parsedMesh.alphaIndex;
  29841. }
  29842. mesh.receiveShadows = parsedMesh.receiveShadows;
  29843. mesh.billboardMode = parsedMesh.billboardMode;
  29844. if (parsedMesh.visibility !== undefined) {
  29845. mesh.visibility = parsedMesh.visibility;
  29846. }
  29847. mesh.checkCollisions = parsedMesh.checkCollisions;
  29848. if (parsedMesh.isBlocker !== undefined) {
  29849. mesh.isBlocker = parsedMesh.isBlocker;
  29850. }
  29851. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29852. // freezeWorldMatrix
  29853. if (parsedMesh.freezeWorldMatrix) {
  29854. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29855. }
  29856. // Parent
  29857. if (parsedMesh.parentId) {
  29858. mesh._waitingParentId = parsedMesh.parentId;
  29859. }
  29860. // Actions
  29861. if (parsedMesh.actions !== undefined) {
  29862. mesh._waitingActions = parsedMesh.actions;
  29863. }
  29864. // Overlay
  29865. if (parsedMesh.overlayAlpha !== undefined) {
  29866. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29867. }
  29868. if (parsedMesh.overlayColor !== undefined) {
  29869. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29870. }
  29871. if (parsedMesh.renderOverlay !== undefined) {
  29872. mesh.renderOverlay = parsedMesh.renderOverlay;
  29873. }
  29874. // Geometry
  29875. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29876. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29877. if (parsedMesh.delayLoadingFile) {
  29878. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29879. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29880. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29881. if (parsedMesh._binaryInfo) {
  29882. mesh._binaryInfo = parsedMesh._binaryInfo;
  29883. }
  29884. mesh._delayInfo = [];
  29885. if (parsedMesh.hasUVs) {
  29886. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29887. }
  29888. if (parsedMesh.hasUVs2) {
  29889. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29890. }
  29891. if (parsedMesh.hasUVs3) {
  29892. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29893. }
  29894. if (parsedMesh.hasUVs4) {
  29895. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29896. }
  29897. if (parsedMesh.hasUVs5) {
  29898. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29899. }
  29900. if (parsedMesh.hasUVs6) {
  29901. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29902. }
  29903. if (parsedMesh.hasColors) {
  29904. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29905. }
  29906. if (parsedMesh.hasMatricesIndices) {
  29907. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29908. }
  29909. if (parsedMesh.hasMatricesWeights) {
  29910. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29911. }
  29912. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29913. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29914. mesh._checkDelayState();
  29915. }
  29916. }
  29917. else {
  29918. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29919. }
  29920. // Material
  29921. if (parsedMesh.materialId) {
  29922. mesh.setMaterialByID(parsedMesh.materialId);
  29923. }
  29924. else {
  29925. mesh.material = null;
  29926. }
  29927. // Morph targets
  29928. if (parsedMesh.morphTargetManagerId > -1) {
  29929. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29930. }
  29931. // Skeleton
  29932. if (parsedMesh.skeletonId > -1) {
  29933. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29934. if (parsedMesh.numBoneInfluencers) {
  29935. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29936. }
  29937. }
  29938. // Animations
  29939. if (parsedMesh.animations) {
  29940. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29941. var parsedAnimation = parsedMesh.animations[animationIndex];
  29942. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29943. }
  29944. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29945. }
  29946. if (parsedMesh.autoAnimate) {
  29947. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29948. }
  29949. // Layer Mask
  29950. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29951. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29952. }
  29953. else {
  29954. mesh.layerMask = 0x0FFFFFFF;
  29955. }
  29956. // Physics
  29957. if (parsedMesh.physicsImpostor) {
  29958. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29959. mass: parsedMesh.physicsMass,
  29960. friction: parsedMesh.physicsFriction,
  29961. restitution: parsedMesh.physicsRestitution
  29962. }, scene);
  29963. }
  29964. // Instances
  29965. if (parsedMesh.instances) {
  29966. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29967. var parsedInstance = parsedMesh.instances[index];
  29968. var instance = mesh.createInstance(parsedInstance.name);
  29969. if (parsedInstance.id) {
  29970. instance.id = parsedInstance.id;
  29971. }
  29972. if (BABYLON.Tags) {
  29973. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29974. }
  29975. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29976. if (parsedInstance.parentId) {
  29977. instance._waitingParentId = parsedInstance.parentId;
  29978. }
  29979. if (parsedInstance.rotationQuaternion) {
  29980. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29981. }
  29982. else if (parsedInstance.rotation) {
  29983. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29984. }
  29985. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29986. instance.checkCollisions = mesh.checkCollisions;
  29987. if (parsedMesh.animations) {
  29988. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29989. parsedAnimation = parsedMesh.animations[animationIndex];
  29990. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29991. }
  29992. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29993. }
  29994. }
  29995. }
  29996. return mesh;
  29997. };
  29998. /**
  29999. * Creates a ribbon mesh.
  30000. * Please consider using the same method from the MeshBuilder class instead.
  30001. * 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.
  30002. *
  30003. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30004. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30005. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30006. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30007. * 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.
  30008. * 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.
  30009. * 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
  30010. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30011. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30012. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30013. */
  30014. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30015. if (closeArray === void 0) { closeArray = false; }
  30016. if (updatable === void 0) { updatable = false; }
  30017. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30018. pathArray: pathArray,
  30019. closeArray: closeArray,
  30020. closePath: closePath,
  30021. offset: offset,
  30022. updatable: updatable,
  30023. sideOrientation: sideOrientation,
  30024. instance: instance
  30025. }, scene);
  30026. };
  30027. /**
  30028. * Creates a plane polygonal mesh. By default, this is a disc.
  30029. * Please consider using the same method from the MeshBuilder class instead.
  30030. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30031. * 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.
  30032. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30033. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30035. */
  30036. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30037. if (scene === void 0) { scene = null; }
  30038. var options = {
  30039. radius: radius,
  30040. tessellation: tessellation,
  30041. sideOrientation: sideOrientation,
  30042. updatable: updatable
  30043. };
  30044. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30045. };
  30046. /**
  30047. * Creates a box mesh.
  30048. * Please consider using the same method from the MeshBuilder class instead.
  30049. * The parameter `size` sets the size (float) of each box side (default 1).
  30050. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30051. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30053. */
  30054. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30055. if (scene === void 0) { scene = null; }
  30056. var options = {
  30057. size: size,
  30058. sideOrientation: sideOrientation,
  30059. updatable: updatable
  30060. };
  30061. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30062. };
  30063. /**
  30064. * Creates a sphere mesh.
  30065. * Please consider using the same method from the MeshBuilder class instead.
  30066. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30067. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30068. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30069. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30070. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30071. */
  30072. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30073. var options = {
  30074. segments: segments,
  30075. diameterX: diameter,
  30076. diameterY: diameter,
  30077. diameterZ: diameter,
  30078. sideOrientation: sideOrientation,
  30079. updatable: updatable
  30080. };
  30081. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30082. };
  30083. /**
  30084. * Creates a cylinder or a cone mesh.
  30085. * Please consider using the same method from the MeshBuilder class instead.
  30086. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30087. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30088. * 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.
  30089. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30090. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30091. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30092. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30093. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30094. */
  30095. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30096. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30097. if (scene !== undefined) {
  30098. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30099. updatable = scene;
  30100. }
  30101. scene = subdivisions;
  30102. subdivisions = 1;
  30103. }
  30104. var options = {
  30105. height: height,
  30106. diameterTop: diameterTop,
  30107. diameterBottom: diameterBottom,
  30108. tessellation: tessellation,
  30109. subdivisions: subdivisions,
  30110. sideOrientation: sideOrientation,
  30111. updatable: updatable
  30112. };
  30113. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30114. };
  30115. // Torus (Code from SharpDX.org)
  30116. /**
  30117. * Creates a torus mesh.
  30118. * Please consider using the same method from the MeshBuilder class instead.
  30119. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30120. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30121. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30122. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30123. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30125. */
  30126. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30127. var options = {
  30128. diameter: diameter,
  30129. thickness: thickness,
  30130. tessellation: tessellation,
  30131. sideOrientation: sideOrientation,
  30132. updatable: updatable
  30133. };
  30134. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30135. };
  30136. /**
  30137. * Creates a torus knot mesh.
  30138. * Please consider using the same method from the MeshBuilder class instead.
  30139. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30140. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30141. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30142. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30143. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30144. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30145. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30146. */
  30147. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30148. var options = {
  30149. radius: radius,
  30150. tube: tube,
  30151. radialSegments: radialSegments,
  30152. tubularSegments: tubularSegments,
  30153. p: p,
  30154. q: q,
  30155. sideOrientation: sideOrientation,
  30156. updatable: updatable
  30157. };
  30158. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30159. };
  30160. /**
  30161. * Creates a line mesh.
  30162. * Please consider using the same method from the MeshBuilder class instead.
  30163. * 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.
  30164. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30165. * The parameter `points` is an array successive Vector3.
  30166. * 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
  30167. * When updating an instance, remember that only point positions can change, not the number of points.
  30168. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30169. */
  30170. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30171. if (scene === void 0) { scene = null; }
  30172. if (updatable === void 0) { updatable = false; }
  30173. if (instance === void 0) { instance = null; }
  30174. var options = {
  30175. points: points,
  30176. updatable: updatable,
  30177. instance: instance
  30178. };
  30179. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30180. };
  30181. /**
  30182. * Creates a dashed line mesh.
  30183. * Please consider using the same method from the MeshBuilder class instead.
  30184. * 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.
  30185. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30186. * The parameter `points` is an array successive Vector3.
  30187. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30188. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30189. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30190. * 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
  30191. * When updating an instance, remember that only point positions can change, not the number of points.
  30192. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30193. */
  30194. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30195. if (scene === void 0) { scene = null; }
  30196. var options = {
  30197. points: points,
  30198. dashSize: dashSize,
  30199. gapSize: gapSize,
  30200. dashNb: dashNb,
  30201. updatable: updatable,
  30202. instance: instance
  30203. };
  30204. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30205. };
  30206. /**
  30207. * Creates a polygon mesh.
  30208. * Please consider using the same method from the MeshBuilder class instead.
  30209. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30210. * 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.
  30211. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30213. * Remember you can only change the shape positions, not their number when updating a polygon.
  30214. */
  30215. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30216. var options = {
  30217. shape: shape,
  30218. holes: holes,
  30219. updatable: updatable,
  30220. sideOrientation: sideOrientation
  30221. };
  30222. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30223. };
  30224. /**
  30225. * Creates an extruded polygon mesh, with depth in the Y direction.
  30226. * Please consider using the same method from the MeshBuilder class instead.
  30227. */
  30228. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30229. var options = {
  30230. shape: shape,
  30231. holes: holes,
  30232. depth: depth,
  30233. updatable: updatable,
  30234. sideOrientation: sideOrientation
  30235. };
  30236. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30237. };
  30238. /**
  30239. * Creates an extruded shape mesh.
  30240. * 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.
  30241. * Please consider using the same method from the MeshBuilder class instead.
  30242. *
  30243. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30244. * 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
  30245. * extruded along the Z axis.
  30246. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30247. * 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.
  30248. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30249. * 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
  30250. * 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
  30251. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30252. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30253. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30254. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30255. */
  30256. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30257. if (scene === void 0) { scene = null; }
  30258. var options = {
  30259. shape: shape,
  30260. path: path,
  30261. scale: scale,
  30262. rotation: rotation,
  30263. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30264. sideOrientation: sideOrientation,
  30265. instance: instance,
  30266. updatable: updatable
  30267. };
  30268. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30269. };
  30270. /**
  30271. * Creates an custom extruded shape mesh.
  30272. * 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.
  30273. * Please consider using the same method from the MeshBuilder class instead.
  30274. *
  30275. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30276. * 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
  30277. * extruded along the Z axis.
  30278. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30279. * 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
  30280. * and the distance of this point from the begining of the path :
  30281. * ```javascript
  30282. * var rotationFunction = function(i, distance) {
  30283. * // do things
  30284. * return rotationValue; }
  30285. * ```
  30286. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30287. * 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
  30288. * and the distance of this point from the begining of the path :
  30289. * ```javascript
  30290. * var scaleFunction = function(i, distance) {
  30291. * // do things
  30292. * return scaleValue;}
  30293. * ```
  30294. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30295. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30296. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30297. * 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
  30298. * 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
  30299. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30301. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30303. */
  30304. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30305. var options = {
  30306. shape: shape,
  30307. path: path,
  30308. scaleFunction: scaleFunction,
  30309. rotationFunction: rotationFunction,
  30310. ribbonCloseArray: ribbonCloseArray,
  30311. ribbonClosePath: ribbonClosePath,
  30312. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30313. sideOrientation: sideOrientation,
  30314. instance: instance,
  30315. updatable: updatable
  30316. };
  30317. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30318. };
  30319. /**
  30320. * Creates lathe mesh.
  30321. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30322. * Please consider using the same method from the MeshBuilder class instead.
  30323. * 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
  30324. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30325. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30326. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30327. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30328. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30329. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30330. */
  30331. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30332. var options = {
  30333. shape: shape,
  30334. radius: radius,
  30335. tessellation: tessellation,
  30336. sideOrientation: sideOrientation,
  30337. updatable: updatable
  30338. };
  30339. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30340. };
  30341. /**
  30342. * Creates a plane mesh.
  30343. * Please consider using the same method from the MeshBuilder class instead.
  30344. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30345. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30346. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30347. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30348. */
  30349. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30350. var options = {
  30351. size: size,
  30352. width: size,
  30353. height: size,
  30354. sideOrientation: sideOrientation,
  30355. updatable: updatable
  30356. };
  30357. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30358. };
  30359. /**
  30360. * Creates a ground mesh.
  30361. * Please consider using the same method from the MeshBuilder class instead.
  30362. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30363. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30365. */
  30366. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30367. var options = {
  30368. width: width,
  30369. height: height,
  30370. subdivisions: subdivisions,
  30371. updatable: updatable
  30372. };
  30373. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30374. };
  30375. /**
  30376. * Creates a tiled ground mesh.
  30377. * Please consider using the same method from the MeshBuilder class instead.
  30378. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30379. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30380. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30381. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30382. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30383. * numbers of subdivisions on the ground width and height of each tile.
  30384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30385. */
  30386. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30387. var options = {
  30388. xmin: xmin,
  30389. zmin: zmin,
  30390. xmax: xmax,
  30391. zmax: zmax,
  30392. subdivisions: subdivisions,
  30393. precision: precision,
  30394. updatable: updatable
  30395. };
  30396. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30397. };
  30398. /**
  30399. * Creates a ground mesh from a height map.
  30400. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30401. * Please consider using the same method from the MeshBuilder class instead.
  30402. * The parameter `url` sets the URL of the height map image resource.
  30403. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30404. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30405. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30406. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30407. * 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).
  30408. * This function is passed the newly built mesh :
  30409. * ```javascript
  30410. * function(mesh) { // do things
  30411. * return; }
  30412. * ```
  30413. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30414. */
  30415. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30416. var options = {
  30417. width: width,
  30418. height: height,
  30419. subdivisions: subdivisions,
  30420. minHeight: minHeight,
  30421. maxHeight: maxHeight,
  30422. updatable: updatable,
  30423. onReady: onReady
  30424. };
  30425. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30426. };
  30427. /**
  30428. * Creates a tube mesh.
  30429. * 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.
  30430. * Please consider using the same method from the MeshBuilder class instead.
  30431. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30432. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30433. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30434. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30435. * 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.
  30436. * It must return a radius value (positive float) :
  30437. * ```javascript
  30438. * var radiusFunction = function(i, distance) {
  30439. * // do things
  30440. * return radius; }
  30441. * ```
  30442. * 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
  30443. * 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
  30444. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30445. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30446. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30447. */
  30448. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30449. var options = {
  30450. path: path,
  30451. radius: radius,
  30452. tessellation: tessellation,
  30453. radiusFunction: radiusFunction,
  30454. arc: 1,
  30455. cap: cap,
  30456. updatable: updatable,
  30457. sideOrientation: sideOrientation,
  30458. instance: instance
  30459. };
  30460. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30461. };
  30462. /**
  30463. * Creates a polyhedron mesh.
  30464. * Please consider using the same method from the MeshBuilder class instead.
  30465. * 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
  30466. * to choose the wanted type.
  30467. * The parameter `size` (positive float, default 1) sets the polygon size.
  30468. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30469. * 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`.
  30470. * 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
  30471. * 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)`).
  30472. * 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
  30473. * 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.
  30474. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30475. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30476. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30477. */
  30478. Mesh.CreatePolyhedron = function (name, options, scene) {
  30479. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30480. };
  30481. /**
  30482. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30483. * Please consider using the same method from the MeshBuilder class instead.
  30484. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30485. * 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`).
  30486. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30487. * 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.
  30488. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30489. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30490. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30491. */
  30492. Mesh.CreateIcoSphere = function (name, options, scene) {
  30493. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30494. };
  30495. /**
  30496. * Creates a decal mesh.
  30497. * Please consider using the same method from the MeshBuilder class instead.
  30498. * 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.
  30499. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30500. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30501. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30502. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30503. */
  30504. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30505. var options = {
  30506. position: position,
  30507. normal: normal,
  30508. size: size,
  30509. angle: angle
  30510. };
  30511. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30512. };
  30513. // Skeletons
  30514. /**
  30515. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30516. */
  30517. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30518. if (!this._sourcePositions) {
  30519. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30520. if (!source) {
  30521. return this._sourcePositions;
  30522. }
  30523. this._sourcePositions = new Float32Array(source);
  30524. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30525. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30526. }
  30527. }
  30528. return this._sourcePositions;
  30529. };
  30530. /**
  30531. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30532. */
  30533. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30534. if (!this._sourceNormals) {
  30535. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30536. if (!source) {
  30537. return this._sourceNormals;
  30538. }
  30539. this._sourceNormals = new Float32Array(source);
  30540. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30541. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30542. }
  30543. }
  30544. return this._sourceNormals;
  30545. };
  30546. /**
  30547. * Updates the vertex buffer by applying transformation from the bones.
  30548. * Returns the Mesh.
  30549. *
  30550. * @param {skeleton} skeleton to apply
  30551. */
  30552. Mesh.prototype.applySkeleton = function (skeleton) {
  30553. if (!this.geometry) {
  30554. return this;
  30555. }
  30556. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30557. return this;
  30558. }
  30559. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30560. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30561. return this;
  30562. }
  30563. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30564. return this;
  30565. }
  30566. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30567. return this;
  30568. }
  30569. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30570. return this;
  30571. }
  30572. if (!this._sourcePositions) {
  30573. var submeshes = this.subMeshes.slice();
  30574. this.setPositionsForCPUSkinning();
  30575. this.subMeshes = submeshes;
  30576. }
  30577. if (!this._sourceNormals) {
  30578. this.setNormalsForCPUSkinning();
  30579. }
  30580. // positionsData checks for not being Float32Array will only pass at most once
  30581. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30582. if (!positionsData) {
  30583. return this;
  30584. }
  30585. if (!(positionsData instanceof Float32Array)) {
  30586. positionsData = new Float32Array(positionsData);
  30587. }
  30588. // normalsData checks for not being Float32Array will only pass at most once
  30589. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30590. if (!normalsData) {
  30591. return this;
  30592. }
  30593. if (!(normalsData instanceof Float32Array)) {
  30594. normalsData = new Float32Array(normalsData);
  30595. }
  30596. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30597. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30598. if (!matricesWeightsData || !matricesIndicesData) {
  30599. return this;
  30600. }
  30601. var needExtras = this.numBoneInfluencers > 4;
  30602. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30603. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30604. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30605. var tempVector3 = BABYLON.Vector3.Zero();
  30606. var finalMatrix = new BABYLON.Matrix();
  30607. var tempMatrix = new BABYLON.Matrix();
  30608. var matWeightIdx = 0;
  30609. var inf;
  30610. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30611. var weight;
  30612. for (inf = 0; inf < 4; inf++) {
  30613. weight = matricesWeightsData[matWeightIdx + inf];
  30614. if (weight > 0) {
  30615. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30616. finalMatrix.addToSelf(tempMatrix);
  30617. }
  30618. else
  30619. break;
  30620. }
  30621. if (needExtras) {
  30622. for (inf = 0; inf < 4; inf++) {
  30623. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30624. if (weight > 0) {
  30625. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30626. finalMatrix.addToSelf(tempMatrix);
  30627. }
  30628. else
  30629. break;
  30630. }
  30631. }
  30632. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30633. tempVector3.toArray(positionsData, index);
  30634. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30635. tempVector3.toArray(normalsData, index);
  30636. finalMatrix.reset();
  30637. }
  30638. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30639. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30640. return this;
  30641. };
  30642. // Tools
  30643. /**
  30644. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30645. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30646. */
  30647. Mesh.MinMax = function (meshes) {
  30648. var minVector = null;
  30649. var maxVector = null;
  30650. meshes.forEach(function (mesh, index, array) {
  30651. var boundingInfo = mesh.getBoundingInfo();
  30652. var boundingBox = boundingInfo.boundingBox;
  30653. if (!minVector || !maxVector) {
  30654. minVector = boundingBox.minimumWorld;
  30655. maxVector = boundingBox.maximumWorld;
  30656. }
  30657. else {
  30658. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30659. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30660. }
  30661. });
  30662. if (!minVector || !maxVector) {
  30663. return {
  30664. min: BABYLON.Vector3.Zero(),
  30665. max: BABYLON.Vector3.Zero()
  30666. };
  30667. }
  30668. return {
  30669. min: minVector,
  30670. max: maxVector
  30671. };
  30672. };
  30673. /**
  30674. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30675. */
  30676. Mesh.Center = function (meshesOrMinMaxVector) {
  30677. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30678. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30679. };
  30680. /**
  30681. * Merge the array of meshes into a single mesh for performance reasons.
  30682. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30683. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30684. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30685. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30686. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30687. */
  30688. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30689. if (disposeSource === void 0) { disposeSource = true; }
  30690. var index;
  30691. if (!allow32BitsIndices) {
  30692. var totalVertices = 0;
  30693. // Counting vertices
  30694. for (index = 0; index < meshes.length; index++) {
  30695. if (meshes[index]) {
  30696. totalVertices += meshes[index].getTotalVertices();
  30697. if (totalVertices > 65536) {
  30698. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30699. return null;
  30700. }
  30701. }
  30702. }
  30703. }
  30704. // Merge
  30705. var vertexData = null;
  30706. var otherVertexData;
  30707. var indiceArray = new Array();
  30708. var source = null;
  30709. for (index = 0; index < meshes.length; index++) {
  30710. if (meshes[index]) {
  30711. meshes[index].computeWorldMatrix(true);
  30712. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30713. otherVertexData.transform(meshes[index].getWorldMatrix());
  30714. if (vertexData) {
  30715. vertexData.merge(otherVertexData);
  30716. }
  30717. else {
  30718. vertexData = otherVertexData;
  30719. source = meshes[index];
  30720. }
  30721. if (subdivideWithSubMeshes) {
  30722. indiceArray.push(meshes[index].getTotalIndices());
  30723. }
  30724. }
  30725. }
  30726. source = source;
  30727. if (!meshSubclass) {
  30728. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30729. }
  30730. vertexData.applyToMesh(meshSubclass);
  30731. // Setting properties
  30732. meshSubclass.material = source.material;
  30733. meshSubclass.checkCollisions = source.checkCollisions;
  30734. // Cleaning
  30735. if (disposeSource) {
  30736. for (index = 0; index < meshes.length; index++) {
  30737. if (meshes[index]) {
  30738. meshes[index].dispose();
  30739. }
  30740. }
  30741. }
  30742. // Subdivide
  30743. if (subdivideWithSubMeshes) {
  30744. //-- Suppresions du submesh global
  30745. meshSubclass.releaseSubMeshes();
  30746. index = 0;
  30747. var offset = 0;
  30748. //-- aplique la subdivision en fonction du tableau d'indices
  30749. while (index < indiceArray.length) {
  30750. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30751. offset += indiceArray[index];
  30752. index++;
  30753. }
  30754. }
  30755. return meshSubclass;
  30756. };
  30757. // Consts
  30758. Mesh._FRONTSIDE = 0;
  30759. Mesh._BACKSIDE = 1;
  30760. Mesh._DOUBLESIDE = 2;
  30761. Mesh._DEFAULTSIDE = 0;
  30762. Mesh._NO_CAP = 0;
  30763. Mesh._CAP_START = 1;
  30764. Mesh._CAP_END = 2;
  30765. Mesh._CAP_ALL = 3;
  30766. return Mesh;
  30767. }(BABYLON.AbstractMesh));
  30768. BABYLON.Mesh = Mesh;
  30769. })(BABYLON || (BABYLON = {}));
  30770. //# sourceMappingURL=babylon.mesh.js.map
  30771. var BABYLON;
  30772. (function (BABYLON) {
  30773. var BaseSubMesh = /** @class */ (function () {
  30774. function BaseSubMesh() {
  30775. }
  30776. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30777. get: function () {
  30778. return this._materialEffect;
  30779. },
  30780. enumerable: true,
  30781. configurable: true
  30782. });
  30783. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30784. if (defines === void 0) { defines = null; }
  30785. if (this._materialEffect === effect) {
  30786. if (!effect) {
  30787. this._materialDefines = null;
  30788. }
  30789. return;
  30790. }
  30791. this._materialDefines = defines;
  30792. this._materialEffect = effect;
  30793. };
  30794. return BaseSubMesh;
  30795. }());
  30796. BABYLON.BaseSubMesh = BaseSubMesh;
  30797. var SubMesh = /** @class */ (function (_super) {
  30798. __extends(SubMesh, _super);
  30799. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30800. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30801. var _this = _super.call(this) || this;
  30802. _this.materialIndex = materialIndex;
  30803. _this.verticesStart = verticesStart;
  30804. _this.verticesCount = verticesCount;
  30805. _this.indexStart = indexStart;
  30806. _this.indexCount = indexCount;
  30807. _this._renderId = 0;
  30808. _this._mesh = mesh;
  30809. _this._renderingMesh = renderingMesh || mesh;
  30810. mesh.subMeshes.push(_this);
  30811. _this._trianglePlanes = [];
  30812. _this._id = mesh.subMeshes.length - 1;
  30813. if (createBoundingBox) {
  30814. _this.refreshBoundingInfo();
  30815. mesh.computeWorldMatrix(true);
  30816. }
  30817. return _this;
  30818. }
  30819. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30820. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30821. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30822. };
  30823. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30824. get: function () {
  30825. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30826. },
  30827. enumerable: true,
  30828. configurable: true
  30829. });
  30830. /**
  30831. * Returns the submesh BoudingInfo object.
  30832. */
  30833. SubMesh.prototype.getBoundingInfo = function () {
  30834. if (this.IsGlobal) {
  30835. return this._mesh.getBoundingInfo();
  30836. }
  30837. return this._boundingInfo;
  30838. };
  30839. /**
  30840. * Sets the submesh BoundingInfo.
  30841. * Return the SubMesh.
  30842. */
  30843. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30844. this._boundingInfo = boundingInfo;
  30845. return this;
  30846. };
  30847. /**
  30848. * Returns the mesh of the current submesh.
  30849. */
  30850. SubMesh.prototype.getMesh = function () {
  30851. return this._mesh;
  30852. };
  30853. /**
  30854. * Returns the rendering mesh of the submesh.
  30855. */
  30856. SubMesh.prototype.getRenderingMesh = function () {
  30857. return this._renderingMesh;
  30858. };
  30859. /**
  30860. * Returns the submesh material.
  30861. */
  30862. SubMesh.prototype.getMaterial = function () {
  30863. var rootMaterial = this._renderingMesh.material;
  30864. if (rootMaterial === null || rootMaterial === undefined) {
  30865. return this._mesh.getScene().defaultMaterial;
  30866. }
  30867. else if (rootMaterial.getSubMaterial) {
  30868. var multiMaterial = rootMaterial;
  30869. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30870. if (this._currentMaterial !== effectiveMaterial) {
  30871. this._currentMaterial = effectiveMaterial;
  30872. this._materialDefines = null;
  30873. }
  30874. return effectiveMaterial;
  30875. }
  30876. return rootMaterial;
  30877. };
  30878. // Methods
  30879. /**
  30880. * Sets a new updated BoundingInfo object to the submesh.
  30881. * Returns the SubMesh.
  30882. */
  30883. SubMesh.prototype.refreshBoundingInfo = function () {
  30884. this._lastColliderWorldVertices = null;
  30885. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30886. return this;
  30887. }
  30888. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30889. if (!data) {
  30890. this._boundingInfo = this._mesh.getBoundingInfo();
  30891. return this;
  30892. }
  30893. var indices = this._renderingMesh.getIndices();
  30894. var extend;
  30895. //is this the only submesh?
  30896. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30897. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30898. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30899. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30900. }
  30901. else {
  30902. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30903. }
  30904. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30905. return this;
  30906. };
  30907. SubMesh.prototype._checkCollision = function (collider) {
  30908. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30909. return boundingInfo._checkCollision(collider);
  30910. };
  30911. /**
  30912. * Updates the submesh BoundingInfo.
  30913. * Returns the Submesh.
  30914. */
  30915. SubMesh.prototype.updateBoundingInfo = function (world) {
  30916. var boundingInfo = this.getBoundingInfo();
  30917. if (!boundingInfo) {
  30918. this.refreshBoundingInfo();
  30919. boundingInfo = this.getBoundingInfo();
  30920. }
  30921. boundingInfo.update(world);
  30922. return this;
  30923. };
  30924. /**
  30925. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30926. * Boolean returned.
  30927. */
  30928. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30929. var boundingInfo = this.getBoundingInfo();
  30930. if (!boundingInfo) {
  30931. return false;
  30932. }
  30933. return boundingInfo.isInFrustum(frustumPlanes);
  30934. };
  30935. /**
  30936. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30937. * Boolean returned.
  30938. */
  30939. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30940. var boundingInfo = this.getBoundingInfo();
  30941. if (!boundingInfo) {
  30942. return false;
  30943. }
  30944. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30945. };
  30946. /**
  30947. * Renders the submesh.
  30948. * Returns it.
  30949. */
  30950. SubMesh.prototype.render = function (enableAlphaMode) {
  30951. this._renderingMesh.render(this, enableAlphaMode);
  30952. return this;
  30953. };
  30954. /**
  30955. * Returns a new Index Buffer.
  30956. * Type returned : WebGLBuffer.
  30957. */
  30958. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30959. if (!this._linesIndexBuffer) {
  30960. var linesIndices = [];
  30961. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30962. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30963. }
  30964. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30965. this.linesIndexCount = linesIndices.length;
  30966. }
  30967. return this._linesIndexBuffer;
  30968. };
  30969. /**
  30970. * True is the passed Ray intersects the submesh bounding box.
  30971. * Boolean returned.
  30972. */
  30973. SubMesh.prototype.canIntersects = function (ray) {
  30974. var boundingInfo = this.getBoundingInfo();
  30975. if (!boundingInfo) {
  30976. return false;
  30977. }
  30978. return ray.intersectsBox(boundingInfo.boundingBox);
  30979. };
  30980. /**
  30981. * Returns an object IntersectionInfo.
  30982. */
  30983. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30984. var intersectInfo = null;
  30985. // LineMesh first as it's also a Mesh...
  30986. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30987. var lineMesh = this._mesh;
  30988. // Line test
  30989. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30990. var p0 = positions[indices[index]];
  30991. var p1 = positions[indices[index + 1]];
  30992. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30993. if (length < 0) {
  30994. continue;
  30995. }
  30996. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30997. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30998. if (fastCheck) {
  30999. break;
  31000. }
  31001. }
  31002. }
  31003. }
  31004. else {
  31005. // Triangles test
  31006. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31007. var p0 = positions[indices[index]];
  31008. var p1 = positions[indices[index + 1]];
  31009. var p2 = positions[indices[index + 2]];
  31010. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31011. if (currentIntersectInfo) {
  31012. if (currentIntersectInfo.distance < 0) {
  31013. continue;
  31014. }
  31015. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31016. intersectInfo = currentIntersectInfo;
  31017. intersectInfo.faceId = index / 3;
  31018. if (fastCheck) {
  31019. break;
  31020. }
  31021. }
  31022. }
  31023. }
  31024. }
  31025. return intersectInfo;
  31026. };
  31027. SubMesh.prototype._rebuild = function () {
  31028. if (this._linesIndexBuffer) {
  31029. this._linesIndexBuffer = null;
  31030. }
  31031. };
  31032. // Clone
  31033. /**
  31034. * Creates a new Submesh from the passed Mesh.
  31035. */
  31036. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31037. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31038. if (!this.IsGlobal) {
  31039. var boundingInfo = this.getBoundingInfo();
  31040. if (!boundingInfo) {
  31041. return result;
  31042. }
  31043. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31044. }
  31045. return result;
  31046. };
  31047. // Dispose
  31048. /**
  31049. * Disposes the Submesh.
  31050. * Returns nothing.
  31051. */
  31052. SubMesh.prototype.dispose = function () {
  31053. if (this._linesIndexBuffer) {
  31054. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31055. this._linesIndexBuffer = null;
  31056. }
  31057. // Remove from mesh
  31058. var index = this._mesh.subMeshes.indexOf(this);
  31059. this._mesh.subMeshes.splice(index, 1);
  31060. };
  31061. // Statics
  31062. /**
  31063. * Creates a new Submesh from the passed parameters :
  31064. * - materialIndex (integer) : the index of the main mesh material.
  31065. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31066. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31067. * - mesh (Mesh) : the main mesh to create the submesh from.
  31068. * - renderingMesh (optional Mesh) : rendering mesh.
  31069. */
  31070. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31071. var minVertexIndex = Number.MAX_VALUE;
  31072. var maxVertexIndex = -Number.MAX_VALUE;
  31073. renderingMesh = (renderingMesh || mesh);
  31074. var indices = renderingMesh.getIndices();
  31075. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31076. var vertexIndex = indices[index];
  31077. if (vertexIndex < minVertexIndex)
  31078. minVertexIndex = vertexIndex;
  31079. if (vertexIndex > maxVertexIndex)
  31080. maxVertexIndex = vertexIndex;
  31081. }
  31082. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31083. };
  31084. return SubMesh;
  31085. }(BaseSubMesh));
  31086. BABYLON.SubMesh = SubMesh;
  31087. })(BABYLON || (BABYLON = {}));
  31088. //# sourceMappingURL=babylon.subMesh.js.map
  31089. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31090. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31091. s = arguments[i];
  31092. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31093. t[p] = s[p];
  31094. }
  31095. return t;
  31096. };
  31097. var BABYLON;
  31098. (function (BABYLON) {
  31099. /**
  31100. * Manages the defines for the Material.
  31101. */
  31102. var MaterialDefines = /** @class */ (function () {
  31103. function MaterialDefines() {
  31104. this._isDirty = true;
  31105. this._areLightsDirty = true;
  31106. this._areAttributesDirty = true;
  31107. this._areTexturesDirty = true;
  31108. this._areFresnelDirty = true;
  31109. this._areMiscDirty = true;
  31110. this._areImageProcessingDirty = true;
  31111. this._normals = false;
  31112. this._uvs = false;
  31113. this._needNormals = false;
  31114. this._needUVs = false;
  31115. }
  31116. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31117. /**
  31118. * Specifies if the material needs to be re-calculated.
  31119. */
  31120. get: function () {
  31121. return this._isDirty;
  31122. },
  31123. enumerable: true,
  31124. configurable: true
  31125. });
  31126. /**
  31127. * Marks the material to indicate that it has been re-calculated.
  31128. */
  31129. MaterialDefines.prototype.markAsProcessed = function () {
  31130. this._isDirty = false;
  31131. this._areAttributesDirty = false;
  31132. this._areTexturesDirty = false;
  31133. this._areFresnelDirty = false;
  31134. this._areLightsDirty = false;
  31135. this._areMiscDirty = false;
  31136. this._areImageProcessingDirty = false;
  31137. };
  31138. /**
  31139. * Marks the material to indicate that it needs to be re-calculated.
  31140. */
  31141. MaterialDefines.prototype.markAsUnprocessed = function () {
  31142. this._isDirty = true;
  31143. };
  31144. /**
  31145. * Marks the material to indicate all of its defines need to be re-calculated.
  31146. */
  31147. MaterialDefines.prototype.markAllAsDirty = function () {
  31148. this._areTexturesDirty = true;
  31149. this._areAttributesDirty = true;
  31150. this._areLightsDirty = true;
  31151. this._areFresnelDirty = true;
  31152. this._areMiscDirty = true;
  31153. this._areImageProcessingDirty = true;
  31154. this._isDirty = true;
  31155. };
  31156. /**
  31157. * Marks the material to indicate that image processing needs to be re-calculated.
  31158. */
  31159. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31160. this._areImageProcessingDirty = true;
  31161. this._isDirty = true;
  31162. };
  31163. /**
  31164. * Marks the material to indicate the lights need to be re-calculated.
  31165. */
  31166. MaterialDefines.prototype.markAsLightDirty = function () {
  31167. this._areLightsDirty = true;
  31168. this._isDirty = true;
  31169. };
  31170. /**
  31171. * Marks the attribute state as changed.
  31172. */
  31173. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31174. this._areAttributesDirty = true;
  31175. this._isDirty = true;
  31176. };
  31177. /**
  31178. * Marks the texture state as changed.
  31179. */
  31180. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31181. this._areTexturesDirty = true;
  31182. this._isDirty = true;
  31183. };
  31184. /**
  31185. * Marks the fresnel state as changed.
  31186. */
  31187. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31188. this._areFresnelDirty = true;
  31189. this._isDirty = true;
  31190. };
  31191. /**
  31192. * Marks the misc state as changed.
  31193. */
  31194. MaterialDefines.prototype.markAsMiscDirty = function () {
  31195. this._areMiscDirty = true;
  31196. this._isDirty = true;
  31197. };
  31198. /**
  31199. * Rebuilds the material defines.
  31200. */
  31201. MaterialDefines.prototype.rebuild = function () {
  31202. if (this._keys) {
  31203. delete this._keys;
  31204. }
  31205. this._keys = [];
  31206. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31207. var key = _a[_i];
  31208. if (key[0] === "_") {
  31209. continue;
  31210. }
  31211. this._keys.push(key);
  31212. }
  31213. };
  31214. /**
  31215. * Specifies if two material defines are equal.
  31216. * @param other - A material define instance to compare to.
  31217. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31218. */
  31219. MaterialDefines.prototype.isEqual = function (other) {
  31220. if (this._keys.length !== other._keys.length) {
  31221. return false;
  31222. }
  31223. for (var index = 0; index < this._keys.length; index++) {
  31224. var prop = this._keys[index];
  31225. if (this[prop] !== other[prop]) {
  31226. return false;
  31227. }
  31228. }
  31229. return true;
  31230. };
  31231. /**
  31232. * Clones this instance's defines to another instance.
  31233. * @param other - material defines to clone values to.
  31234. */
  31235. MaterialDefines.prototype.cloneTo = function (other) {
  31236. if (this._keys.length !== other._keys.length) {
  31237. other._keys = this._keys.slice(0);
  31238. }
  31239. for (var index = 0; index < this._keys.length; index++) {
  31240. var prop = this._keys[index];
  31241. other[prop] = this[prop];
  31242. }
  31243. };
  31244. /**
  31245. * Resets the material define values.
  31246. */
  31247. MaterialDefines.prototype.reset = function () {
  31248. for (var index = 0; index < this._keys.length; index++) {
  31249. var prop = this._keys[index];
  31250. if (typeof (this[prop]) === "number") {
  31251. this[prop] = 0;
  31252. }
  31253. else {
  31254. this[prop] = false;
  31255. }
  31256. }
  31257. };
  31258. /**
  31259. * Converts the material define values to a string.
  31260. * @returns - String of material define information.
  31261. */
  31262. MaterialDefines.prototype.toString = function () {
  31263. var result = "";
  31264. for (var index = 0; index < this._keys.length; index++) {
  31265. var prop = this._keys[index];
  31266. var value = this[prop];
  31267. if (typeof (value) === "number") {
  31268. result += "#define " + prop + " " + this[prop] + "\n";
  31269. }
  31270. else if (value) {
  31271. result += "#define " + prop + "\n";
  31272. }
  31273. }
  31274. return result;
  31275. };
  31276. return MaterialDefines;
  31277. }());
  31278. BABYLON.MaterialDefines = MaterialDefines;
  31279. /**
  31280. * This offers the main features of a material in BJS.
  31281. */
  31282. var Material = /** @class */ (function () {
  31283. /**
  31284. * Creates a material instance.
  31285. * @param name - The name of the material.
  31286. * @param scene - The BJS scene to reference.
  31287. * @param doNotAdd - Specifies if the material should be added to the scene.
  31288. */
  31289. function Material(name, scene, doNotAdd) {
  31290. /**
  31291. * Specifies if the ready state should be checked on each call.
  31292. */
  31293. this.checkReadyOnEveryCall = false;
  31294. /**
  31295. * Specifies if the ready state should be checked once.
  31296. */
  31297. this.checkReadyOnlyOnce = false;
  31298. /**
  31299. * The state of the material.
  31300. */
  31301. this.state = "";
  31302. /**
  31303. * The alpha value of the material.
  31304. */
  31305. this._alpha = 1.0;
  31306. /**
  31307. * Specifies if back face culling is enabled.
  31308. */
  31309. this._backFaceCulling = true;
  31310. /**
  31311. * Specifies if the material should be serialized.
  31312. */
  31313. this.doNotSerialize = false;
  31314. /**
  31315. * Specifies if the effect should be stored on sub meshes.
  31316. */
  31317. this.storeEffectOnSubMeshes = false;
  31318. /**
  31319. * An event triggered when the material is disposed.
  31320. * @type {BABYLON.Observable}
  31321. */
  31322. this.onDisposeObservable = new BABYLON.Observable();
  31323. /**
  31324. * An event triggered when the material is bound.
  31325. * @type {BABYLON.Observable}
  31326. */
  31327. this.onBindObservable = new BABYLON.Observable();
  31328. /**
  31329. * An event triggered when the material is unbound.
  31330. * @type {BABYLON.Observable}
  31331. */
  31332. this.onUnBindObservable = new BABYLON.Observable();
  31333. /**
  31334. * Stores the value of the alpha mode.
  31335. */
  31336. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31337. /**
  31338. * Stores the state of the need depth pre-pass value.
  31339. */
  31340. this._needDepthPrePass = false;
  31341. /**
  31342. * Specifies if depth writing should be disabled.
  31343. */
  31344. this.disableDepthWrite = false;
  31345. /**
  31346. * Specifies if depth writing should be forced.
  31347. */
  31348. this.forceDepthWrite = false;
  31349. /**
  31350. * Specifies if there should be a separate pass for culling.
  31351. */
  31352. this.separateCullingPass = false;
  31353. /**
  31354. * Stores the state specifing if fog should be enabled.
  31355. */
  31356. this._fogEnabled = true;
  31357. /**
  31358. * Stores the size of points.
  31359. */
  31360. this.pointSize = 1.0;
  31361. /**
  31362. * Stores the z offset value.
  31363. */
  31364. this.zOffset = 0;
  31365. /**
  31366. * Specifies if the material was previously ready.
  31367. */
  31368. this._wasPreviouslyReady = false;
  31369. /**
  31370. * Stores the fill mode state.
  31371. */
  31372. this._fillMode = Material.TriangleFillMode;
  31373. this.name = name;
  31374. this.id = name || BABYLON.Tools.RandomId();
  31375. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31376. if (this._scene.useRightHandedSystem) {
  31377. this.sideOrientation = Material.ClockWiseSideOrientation;
  31378. }
  31379. else {
  31380. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31381. }
  31382. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31383. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31384. if (!doNotAdd) {
  31385. this._scene.materials.push(this);
  31386. }
  31387. }
  31388. Object.defineProperty(Material, "TriangleFillMode", {
  31389. /**
  31390. * Returns the triangle fill mode.
  31391. */
  31392. get: function () {
  31393. return Material._TriangleFillMode;
  31394. },
  31395. enumerable: true,
  31396. configurable: true
  31397. });
  31398. Object.defineProperty(Material, "WireFrameFillMode", {
  31399. /**
  31400. * Returns the wireframe mode.
  31401. */
  31402. get: function () {
  31403. return Material._WireFrameFillMode;
  31404. },
  31405. enumerable: true,
  31406. configurable: true
  31407. });
  31408. Object.defineProperty(Material, "PointFillMode", {
  31409. /**
  31410. * Returns the point fill mode.
  31411. */
  31412. get: function () {
  31413. return Material._PointFillMode;
  31414. },
  31415. enumerable: true,
  31416. configurable: true
  31417. });
  31418. Object.defineProperty(Material, "PointListDrawMode", {
  31419. /**
  31420. * Returns the point list draw mode.
  31421. */
  31422. get: function () {
  31423. return Material._PointListDrawMode;
  31424. },
  31425. enumerable: true,
  31426. configurable: true
  31427. });
  31428. Object.defineProperty(Material, "LineListDrawMode", {
  31429. /**
  31430. * Returns the line list draw mode.
  31431. */
  31432. get: function () {
  31433. return Material._LineListDrawMode;
  31434. },
  31435. enumerable: true,
  31436. configurable: true
  31437. });
  31438. Object.defineProperty(Material, "LineLoopDrawMode", {
  31439. /**
  31440. * Returns the line loop draw mode.
  31441. */
  31442. get: function () {
  31443. return Material._LineLoopDrawMode;
  31444. },
  31445. enumerable: true,
  31446. configurable: true
  31447. });
  31448. Object.defineProperty(Material, "LineStripDrawMode", {
  31449. /**
  31450. * Returns the line strip draw mode.
  31451. */
  31452. get: function () {
  31453. return Material._LineStripDrawMode;
  31454. },
  31455. enumerable: true,
  31456. configurable: true
  31457. });
  31458. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31459. /**
  31460. * Returns the triangle strip draw mode.
  31461. */
  31462. get: function () {
  31463. return Material._TriangleStripDrawMode;
  31464. },
  31465. enumerable: true,
  31466. configurable: true
  31467. });
  31468. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31469. /**
  31470. * Returns the triangle fan draw mode.
  31471. */
  31472. get: function () {
  31473. return Material._TriangleFanDrawMode;
  31474. },
  31475. enumerable: true,
  31476. configurable: true
  31477. });
  31478. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31479. /**
  31480. * Returns the clock-wise side orientation.
  31481. */
  31482. get: function () {
  31483. return Material._ClockWiseSideOrientation;
  31484. },
  31485. enumerable: true,
  31486. configurable: true
  31487. });
  31488. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31489. /**
  31490. * Returns the counter clock-wise side orientation.
  31491. */
  31492. get: function () {
  31493. return Material._CounterClockWiseSideOrientation;
  31494. },
  31495. enumerable: true,
  31496. configurable: true
  31497. });
  31498. Object.defineProperty(Material, "TextureDirtyFlag", {
  31499. /**
  31500. * Returns the dirty texture flag value.
  31501. */
  31502. get: function () {
  31503. return Material._TextureDirtyFlag;
  31504. },
  31505. enumerable: true,
  31506. configurable: true
  31507. });
  31508. Object.defineProperty(Material, "LightDirtyFlag", {
  31509. /**
  31510. * Returns the dirty light flag value.
  31511. */
  31512. get: function () {
  31513. return Material._LightDirtyFlag;
  31514. },
  31515. enumerable: true,
  31516. configurable: true
  31517. });
  31518. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31519. /**
  31520. * Returns the dirty fresnel flag value.
  31521. */
  31522. get: function () {
  31523. return Material._FresnelDirtyFlag;
  31524. },
  31525. enumerable: true,
  31526. configurable: true
  31527. });
  31528. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31529. /**
  31530. * Returns the dirty attributes flag value.
  31531. */
  31532. get: function () {
  31533. return Material._AttributesDirtyFlag;
  31534. },
  31535. enumerable: true,
  31536. configurable: true
  31537. });
  31538. Object.defineProperty(Material, "MiscDirtyFlag", {
  31539. /**
  31540. * Returns the dirty misc flag value.
  31541. */
  31542. get: function () {
  31543. return Material._MiscDirtyFlag;
  31544. },
  31545. enumerable: true,
  31546. configurable: true
  31547. });
  31548. Object.defineProperty(Material.prototype, "alpha", {
  31549. /**
  31550. * Gets the alpha value of the material.
  31551. */
  31552. get: function () {
  31553. return this._alpha;
  31554. },
  31555. /**
  31556. * Sets the alpha value of the material.
  31557. */
  31558. set: function (value) {
  31559. if (this._alpha === value) {
  31560. return;
  31561. }
  31562. this._alpha = value;
  31563. this.markAsDirty(Material.MiscDirtyFlag);
  31564. },
  31565. enumerable: true,
  31566. configurable: true
  31567. });
  31568. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31569. /**
  31570. * Gets the back-face culling state.
  31571. */
  31572. get: function () {
  31573. return this._backFaceCulling;
  31574. },
  31575. /**
  31576. * Sets the back-face culling state.
  31577. */
  31578. set: function (value) {
  31579. if (this._backFaceCulling === value) {
  31580. return;
  31581. }
  31582. this._backFaceCulling = value;
  31583. this.markAsDirty(Material.TextureDirtyFlag);
  31584. },
  31585. enumerable: true,
  31586. configurable: true
  31587. });
  31588. Object.defineProperty(Material.prototype, "onDispose", {
  31589. /**
  31590. * Called during a dispose event.
  31591. */
  31592. set: function (callback) {
  31593. if (this._onDisposeObserver) {
  31594. this.onDisposeObservable.remove(this._onDisposeObserver);
  31595. }
  31596. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31597. },
  31598. enumerable: true,
  31599. configurable: true
  31600. });
  31601. Object.defineProperty(Material.prototype, "onBind", {
  31602. /**
  31603. * Called during a bind event.
  31604. */
  31605. set: function (callback) {
  31606. if (this._onBindObserver) {
  31607. this.onBindObservable.remove(this._onBindObserver);
  31608. }
  31609. this._onBindObserver = this.onBindObservable.add(callback);
  31610. },
  31611. enumerable: true,
  31612. configurable: true
  31613. });
  31614. Object.defineProperty(Material.prototype, "alphaMode", {
  31615. /**
  31616. * Gets the value of the alpha mode.
  31617. */
  31618. get: function () {
  31619. return this._alphaMode;
  31620. },
  31621. /**
  31622. * Sets the value of the alpha mode.
  31623. */
  31624. set: function (value) {
  31625. if (this._alphaMode === value) {
  31626. return;
  31627. }
  31628. this._alphaMode = value;
  31629. this.markAsDirty(Material.TextureDirtyFlag);
  31630. },
  31631. enumerable: true,
  31632. configurable: true
  31633. });
  31634. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31635. /**
  31636. * Gets the depth pre-pass value.
  31637. */
  31638. get: function () {
  31639. return this._needDepthPrePass;
  31640. },
  31641. /**
  31642. * Sets the need depth pre-pass value.
  31643. */
  31644. set: function (value) {
  31645. if (this._needDepthPrePass === value) {
  31646. return;
  31647. }
  31648. this._needDepthPrePass = value;
  31649. if (this._needDepthPrePass) {
  31650. this.checkReadyOnEveryCall = true;
  31651. }
  31652. },
  31653. enumerable: true,
  31654. configurable: true
  31655. });
  31656. Object.defineProperty(Material.prototype, "fogEnabled", {
  31657. /**
  31658. * Gets the value of the fog enabled state.
  31659. */
  31660. get: function () {
  31661. return this._fogEnabled;
  31662. },
  31663. /**
  31664. * Sets the state for enabling fog.
  31665. */
  31666. set: function (value) {
  31667. if (this._fogEnabled === value) {
  31668. return;
  31669. }
  31670. this._fogEnabled = value;
  31671. this.markAsDirty(Material.MiscDirtyFlag);
  31672. },
  31673. enumerable: true,
  31674. configurable: true
  31675. });
  31676. Object.defineProperty(Material.prototype, "wireframe", {
  31677. /**
  31678. * Gets a value specifying if wireframe mode is enabled.
  31679. */
  31680. get: function () {
  31681. return this._fillMode === Material.WireFrameFillMode;
  31682. },
  31683. /**
  31684. * Sets the state of wireframe mode.
  31685. */
  31686. set: function (value) {
  31687. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31688. },
  31689. enumerable: true,
  31690. configurable: true
  31691. });
  31692. Object.defineProperty(Material.prototype, "pointsCloud", {
  31693. /**
  31694. * Gets the value specifying if point clouds are enabled.
  31695. */
  31696. get: function () {
  31697. return this._fillMode === Material.PointFillMode;
  31698. },
  31699. /**
  31700. * Sets the state of point cloud mode.
  31701. */
  31702. set: function (value) {
  31703. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31704. },
  31705. enumerable: true,
  31706. configurable: true
  31707. });
  31708. Object.defineProperty(Material.prototype, "fillMode", {
  31709. /**
  31710. * Gets the material fill mode.
  31711. */
  31712. get: function () {
  31713. return this._fillMode;
  31714. },
  31715. /**
  31716. * Sets the material fill mode.
  31717. */
  31718. set: function (value) {
  31719. if (this._fillMode === value) {
  31720. return;
  31721. }
  31722. this._fillMode = value;
  31723. this.markAsDirty(Material.MiscDirtyFlag);
  31724. },
  31725. enumerable: true,
  31726. configurable: true
  31727. });
  31728. /**
  31729. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31730. * subclasses should override adding information pertainent to themselves.
  31731. * @returns - String with material information.
  31732. */
  31733. Material.prototype.toString = function (fullDetails) {
  31734. var ret = "Name: " + this.name;
  31735. if (fullDetails) {
  31736. }
  31737. return ret;
  31738. };
  31739. /**
  31740. * Gets the class name of the material.
  31741. * @returns - String with the class name of the material.
  31742. */
  31743. Material.prototype.getClassName = function () {
  31744. return "Material";
  31745. };
  31746. Object.defineProperty(Material.prototype, "isFrozen", {
  31747. /**
  31748. * Specifies if updates for the material been locked.
  31749. */
  31750. get: function () {
  31751. return this.checkReadyOnlyOnce;
  31752. },
  31753. enumerable: true,
  31754. configurable: true
  31755. });
  31756. /**
  31757. * Locks updates for the material.
  31758. */
  31759. Material.prototype.freeze = function () {
  31760. this.checkReadyOnlyOnce = true;
  31761. };
  31762. /**
  31763. * Unlocks updates for the material.
  31764. */
  31765. Material.prototype.unfreeze = function () {
  31766. this.checkReadyOnlyOnce = false;
  31767. };
  31768. /**
  31769. * Specifies if the material is ready to be used.
  31770. * @param mesh - BJS mesh.
  31771. * @param useInstances - Specifies if instances should be used.
  31772. * @returns - Boolean indicating if the material is ready to be used.
  31773. */
  31774. Material.prototype.isReady = function (mesh, useInstances) {
  31775. return true;
  31776. };
  31777. /**
  31778. * Specifies that the submesh is ready to be used.
  31779. * @param mesh - BJS mesh.
  31780. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31781. * @param useInstances - Specifies that instances should be used.
  31782. * @returns - boolean indicating that the submesh is ready or not.
  31783. */
  31784. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31785. return false;
  31786. };
  31787. /**
  31788. * Returns the material effect.
  31789. * @returns - Nullable material effect.
  31790. */
  31791. Material.prototype.getEffect = function () {
  31792. return this._effect;
  31793. };
  31794. /**
  31795. * Returns the BJS scene.
  31796. * @returns - BJS Scene.
  31797. */
  31798. Material.prototype.getScene = function () {
  31799. return this._scene;
  31800. };
  31801. /**
  31802. * Specifies if the material will require alpha blending
  31803. * @returns - Boolean specifying if alpha blending is needed.
  31804. */
  31805. Material.prototype.needAlphaBlending = function () {
  31806. return (this.alpha < 1.0);
  31807. };
  31808. /**
  31809. * Specifies if the mesh will require alpha blending.
  31810. * @param mesh - BJS mesh.
  31811. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31812. */
  31813. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31814. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31815. };
  31816. /**
  31817. * Specifies if this material should be rendered in alpha test mode.
  31818. * @returns - Boolean specifying if an alpha test is needed.
  31819. */
  31820. Material.prototype.needAlphaTesting = function () {
  31821. return false;
  31822. };
  31823. /**
  31824. * Gets the texture used for the alpha test.
  31825. * @returns - Nullable alpha test texture.
  31826. */
  31827. Material.prototype.getAlphaTestTexture = function () {
  31828. return null;
  31829. };
  31830. /**
  31831. * Marks the material to indicate that it needs to be re-calculated.
  31832. */
  31833. Material.prototype.markDirty = function () {
  31834. this._wasPreviouslyReady = false;
  31835. };
  31836. Material.prototype._preBind = function (effect, overrideOrientation) {
  31837. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31838. var engine = this._scene.getEngine();
  31839. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31840. var reverse = orientation === Material.ClockWiseSideOrientation;
  31841. engine.enableEffect(effect ? effect : this._effect);
  31842. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31843. return reverse;
  31844. };
  31845. /**
  31846. * Binds the material to the mesh.
  31847. * @param world - World transformation matrix.
  31848. * @param mesh - Mesh to bind the material to.
  31849. */
  31850. Material.prototype.bind = function (world, mesh) {
  31851. };
  31852. /**
  31853. * Binds the submesh to the material.
  31854. * @param world - World transformation matrix.
  31855. * @param mesh - Mesh containing the submesh.
  31856. * @param subMesh - Submesh to bind the material to.
  31857. */
  31858. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31859. };
  31860. /**
  31861. * Binds the world matrix to the material.
  31862. * @param world - World transformation matrix.
  31863. */
  31864. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31865. };
  31866. /**
  31867. * Binds the scene's uniform buffer to the effect.
  31868. * @param effect - Effect to bind to the scene uniform buffer.
  31869. * @param sceneUbo - Scene uniform buffer.
  31870. */
  31871. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31872. sceneUbo.bindToEffect(effect, "Scene");
  31873. };
  31874. /**
  31875. * Binds the view matrix to the effect.
  31876. * @param effect - Effect to bind the view matrix to.
  31877. */
  31878. Material.prototype.bindView = function (effect) {
  31879. if (!this._useUBO) {
  31880. effect.setMatrix("view", this.getScene().getViewMatrix());
  31881. }
  31882. else {
  31883. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31884. }
  31885. };
  31886. /**
  31887. * Binds the view projection matrix to the effect.
  31888. * @param effect - Effect to bind the view projection matrix to.
  31889. */
  31890. Material.prototype.bindViewProjection = function (effect) {
  31891. if (!this._useUBO) {
  31892. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31893. }
  31894. else {
  31895. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31896. }
  31897. };
  31898. /**
  31899. * Specifies if material alpha testing should be turned on for the mesh.
  31900. * @param mesh - BJS mesh.
  31901. */
  31902. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31903. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31904. };
  31905. /**
  31906. * Processes to execute after binding the material to a mesh.
  31907. * @param mesh - BJS mesh.
  31908. */
  31909. Material.prototype._afterBind = function (mesh) {
  31910. this._scene._cachedMaterial = this;
  31911. if (mesh) {
  31912. this._scene._cachedVisibility = mesh.visibility;
  31913. }
  31914. else {
  31915. this._scene._cachedVisibility = 1;
  31916. }
  31917. if (mesh) {
  31918. this.onBindObservable.notifyObservers(mesh);
  31919. }
  31920. if (this.disableDepthWrite) {
  31921. var engine = this._scene.getEngine();
  31922. this._cachedDepthWriteState = engine.getDepthWrite();
  31923. engine.setDepthWrite(false);
  31924. }
  31925. };
  31926. /**
  31927. * Unbinds the material from the mesh.
  31928. */
  31929. Material.prototype.unbind = function () {
  31930. this.onUnBindObservable.notifyObservers(this);
  31931. if (this.disableDepthWrite) {
  31932. var engine = this._scene.getEngine();
  31933. engine.setDepthWrite(this._cachedDepthWriteState);
  31934. }
  31935. };
  31936. /**
  31937. * Gets the active textures from the material.
  31938. * @returns - Array of textures.
  31939. */
  31940. Material.prototype.getActiveTextures = function () {
  31941. return [];
  31942. };
  31943. /**
  31944. * Specifies if the material uses a texture.
  31945. * @param texture - Texture to check against the material.
  31946. * @returns - Boolean specifying if the material uses the texture.
  31947. */
  31948. Material.prototype.hasTexture = function (texture) {
  31949. return false;
  31950. };
  31951. /**
  31952. * Makes a duplicate of the material, and gives it a new name.
  31953. * @param name - Name to call the duplicated material.
  31954. * @returns - Nullable cloned material
  31955. */
  31956. Material.prototype.clone = function (name) {
  31957. return null;
  31958. };
  31959. /**
  31960. * Gets the meshes bound to the material.
  31961. * @returns - Array of meshes bound to the material.
  31962. */
  31963. Material.prototype.getBindedMeshes = function () {
  31964. var result = new Array();
  31965. for (var index = 0; index < this._scene.meshes.length; index++) {
  31966. var mesh = this._scene.meshes[index];
  31967. if (mesh.material === this) {
  31968. result.push(mesh);
  31969. }
  31970. }
  31971. return result;
  31972. };
  31973. /**
  31974. * Force shader compilation
  31975. * @param mesh - BJS mesh.
  31976. * @param onCompiled - function to execute once the material is compiled.
  31977. * @param options - options to pass to this function.
  31978. */
  31979. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31980. var _this = this;
  31981. var localOptions = __assign({ clipPlane: false }, options);
  31982. var subMesh = new BABYLON.BaseSubMesh();
  31983. var scene = this.getScene();
  31984. var checkReady = function () {
  31985. if (!_this._scene || !_this._scene.getEngine()) {
  31986. return;
  31987. }
  31988. if (subMesh._materialDefines) {
  31989. subMesh._materialDefines._renderId = -1;
  31990. }
  31991. var clipPlaneState = scene.clipPlane;
  31992. if (localOptions.clipPlane) {
  31993. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31994. }
  31995. if (_this.storeEffectOnSubMeshes) {
  31996. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31997. if (onCompiled) {
  31998. onCompiled(_this);
  31999. }
  32000. }
  32001. else {
  32002. setTimeout(checkReady, 16);
  32003. }
  32004. }
  32005. else {
  32006. if (_this.isReady(mesh)) {
  32007. if (onCompiled) {
  32008. onCompiled(_this);
  32009. }
  32010. }
  32011. else {
  32012. setTimeout(checkReady, 16);
  32013. }
  32014. }
  32015. if (localOptions.clipPlane) {
  32016. scene.clipPlane = clipPlaneState;
  32017. }
  32018. };
  32019. checkReady();
  32020. };
  32021. /**
  32022. * Force shader compilation.
  32023. * @param mesh The mesh that will use this material
  32024. * @param options Additional options for compiling the shaders
  32025. * @returns A promise that resolves when the compilation completes
  32026. */
  32027. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32028. var _this = this;
  32029. return new Promise(function (resolve) {
  32030. _this.forceCompilation(mesh, function () {
  32031. resolve();
  32032. }, options);
  32033. });
  32034. };
  32035. /**
  32036. * Marks a define in the material to indicate that it needs to be re-computed.
  32037. * @param flag - Material define flag.
  32038. */
  32039. Material.prototype.markAsDirty = function (flag) {
  32040. if (flag & Material.TextureDirtyFlag) {
  32041. this._markAllSubMeshesAsTexturesDirty();
  32042. }
  32043. if (flag & Material.LightDirtyFlag) {
  32044. this._markAllSubMeshesAsLightsDirty();
  32045. }
  32046. if (flag & Material.FresnelDirtyFlag) {
  32047. this._markAllSubMeshesAsFresnelDirty();
  32048. }
  32049. if (flag & Material.AttributesDirtyFlag) {
  32050. this._markAllSubMeshesAsAttributesDirty();
  32051. }
  32052. if (flag & Material.MiscDirtyFlag) {
  32053. this._markAllSubMeshesAsMiscDirty();
  32054. }
  32055. this.getScene().resetCachedMaterial();
  32056. };
  32057. /**
  32058. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32059. * @param func - function which checks material defines against the submeshes.
  32060. */
  32061. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32062. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32063. var mesh = _a[_i];
  32064. if (!mesh.subMeshes) {
  32065. continue;
  32066. }
  32067. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32068. var subMesh = _c[_b];
  32069. if (subMesh.getMaterial() !== this) {
  32070. continue;
  32071. }
  32072. if (!subMesh._materialDefines) {
  32073. continue;
  32074. }
  32075. func(subMesh._materialDefines);
  32076. }
  32077. }
  32078. };
  32079. /**
  32080. * Indicates that image processing needs to be re-calculated for all submeshes.
  32081. */
  32082. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32083. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32084. };
  32085. /**
  32086. * Indicates that textures need to be re-calculated for all submeshes.
  32087. */
  32088. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32089. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32090. };
  32091. /**
  32092. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32093. */
  32094. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32095. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32096. };
  32097. /**
  32098. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32099. */
  32100. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32101. this._markAllSubMeshesAsDirty(function (defines) {
  32102. defines.markAsFresnelDirty();
  32103. defines.markAsMiscDirty();
  32104. });
  32105. };
  32106. /**
  32107. * Indicates that lights need to be re-calculated for all submeshes.
  32108. */
  32109. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32110. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32111. };
  32112. /**
  32113. * Indicates that attributes need to be re-calculated for all submeshes.
  32114. */
  32115. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32116. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32117. };
  32118. /**
  32119. * Indicates that misc needs to be re-calculated for all submeshes.
  32120. */
  32121. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32122. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32123. };
  32124. /**
  32125. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32126. */
  32127. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32128. this._markAllSubMeshesAsDirty(function (defines) {
  32129. defines.markAsTexturesDirty();
  32130. defines.markAsMiscDirty();
  32131. });
  32132. };
  32133. /**
  32134. * Disposes the material.
  32135. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32136. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32137. */
  32138. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32139. // Animations
  32140. this.getScene().stopAnimation(this);
  32141. this.getScene().freeProcessedMaterials();
  32142. // Remove from scene
  32143. var index = this._scene.materials.indexOf(this);
  32144. if (index >= 0) {
  32145. this._scene.materials.splice(index, 1);
  32146. }
  32147. // Remove from meshes
  32148. for (index = 0; index < this._scene.meshes.length; index++) {
  32149. var mesh = this._scene.meshes[index];
  32150. if (mesh.material === this) {
  32151. mesh.material = null;
  32152. if (mesh.geometry) {
  32153. var geometry = (mesh.geometry);
  32154. if (this.storeEffectOnSubMeshes) {
  32155. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32156. var subMesh = _a[_i];
  32157. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32158. if (forceDisposeEffect && subMesh._materialEffect) {
  32159. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32160. }
  32161. }
  32162. }
  32163. else {
  32164. geometry._releaseVertexArrayObject(this._effect);
  32165. }
  32166. }
  32167. }
  32168. }
  32169. this._uniformBuffer.dispose();
  32170. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32171. if (forceDisposeEffect && this._effect) {
  32172. if (!this.storeEffectOnSubMeshes) {
  32173. this._scene.getEngine()._releaseEffect(this._effect);
  32174. }
  32175. this._effect = null;
  32176. }
  32177. // Callback
  32178. this.onDisposeObservable.notifyObservers(this);
  32179. this.onDisposeObservable.clear();
  32180. this.onBindObservable.clear();
  32181. this.onUnBindObservable.clear();
  32182. };
  32183. /**
  32184. * Serializes this material.
  32185. * @returns - serialized material object.
  32186. */
  32187. Material.prototype.serialize = function () {
  32188. return BABYLON.SerializationHelper.Serialize(this);
  32189. };
  32190. /**
  32191. * Creates a MultiMaterial from parse MultiMaterial data.
  32192. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32193. * @param scene - BJS scene.
  32194. * @returns - MultiMaterial.
  32195. */
  32196. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32197. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32198. multiMaterial.id = parsedMultiMaterial.id;
  32199. if (BABYLON.Tags) {
  32200. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32201. }
  32202. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32203. var subMatId = parsedMultiMaterial.materials[matIndex];
  32204. if (subMatId) {
  32205. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32206. }
  32207. else {
  32208. multiMaterial.subMaterials.push(null);
  32209. }
  32210. }
  32211. return multiMaterial;
  32212. };
  32213. /**
  32214. * Creates a material from parsed material data.
  32215. * @param parsedMaterial - Parsed material data.
  32216. * @param scene - BJS scene.
  32217. * @param rootUrl - Root URL containing the material information.
  32218. * @returns - Parsed material.
  32219. */
  32220. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32221. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32222. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32223. }
  32224. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32225. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32226. if (!BABYLON.LegacyPBRMaterial) {
  32227. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32228. return;
  32229. }
  32230. }
  32231. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32232. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32233. ;
  32234. };
  32235. // Triangle views
  32236. Material._TriangleFillMode = 0;
  32237. Material._WireFrameFillMode = 1;
  32238. Material._PointFillMode = 2;
  32239. // Draw modes
  32240. Material._PointListDrawMode = 3;
  32241. Material._LineListDrawMode = 4;
  32242. Material._LineLoopDrawMode = 5;
  32243. Material._LineStripDrawMode = 6;
  32244. Material._TriangleStripDrawMode = 7;
  32245. Material._TriangleFanDrawMode = 8;
  32246. /**
  32247. * Stores the clock-wise side orientation.
  32248. */
  32249. Material._ClockWiseSideOrientation = 0;
  32250. /**
  32251. * Stores the counter clock-wise side orientation.
  32252. */
  32253. Material._CounterClockWiseSideOrientation = 1;
  32254. /**
  32255. * The dirty texture flag value.
  32256. */
  32257. Material._TextureDirtyFlag = 1;
  32258. /**
  32259. * The dirty light flag value.
  32260. */
  32261. Material._LightDirtyFlag = 2;
  32262. /**
  32263. * The dirty fresnel flag value.
  32264. */
  32265. Material._FresnelDirtyFlag = 4;
  32266. /**
  32267. * The dirty attribute flag value.
  32268. */
  32269. Material._AttributesDirtyFlag = 8;
  32270. /**
  32271. * The dirty misc flag value.
  32272. */
  32273. Material._MiscDirtyFlag = 16;
  32274. __decorate([
  32275. BABYLON.serialize()
  32276. ], Material.prototype, "id", void 0);
  32277. __decorate([
  32278. BABYLON.serialize()
  32279. ], Material.prototype, "name", void 0);
  32280. __decorate([
  32281. BABYLON.serialize()
  32282. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32283. __decorate([
  32284. BABYLON.serialize()
  32285. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32286. __decorate([
  32287. BABYLON.serialize()
  32288. ], Material.prototype, "state", void 0);
  32289. __decorate([
  32290. BABYLON.serialize("alpha")
  32291. ], Material.prototype, "_alpha", void 0);
  32292. __decorate([
  32293. BABYLON.serialize("backFaceCulling")
  32294. ], Material.prototype, "_backFaceCulling", void 0);
  32295. __decorate([
  32296. BABYLON.serialize()
  32297. ], Material.prototype, "sideOrientation", void 0);
  32298. __decorate([
  32299. BABYLON.serialize("alphaMode")
  32300. ], Material.prototype, "_alphaMode", void 0);
  32301. __decorate([
  32302. BABYLON.serialize()
  32303. ], Material.prototype, "_needDepthPrePass", void 0);
  32304. __decorate([
  32305. BABYLON.serialize()
  32306. ], Material.prototype, "disableDepthWrite", void 0);
  32307. __decorate([
  32308. BABYLON.serialize()
  32309. ], Material.prototype, "forceDepthWrite", void 0);
  32310. __decorate([
  32311. BABYLON.serialize()
  32312. ], Material.prototype, "separateCullingPass", void 0);
  32313. __decorate([
  32314. BABYLON.serialize("fogEnabled")
  32315. ], Material.prototype, "_fogEnabled", void 0);
  32316. __decorate([
  32317. BABYLON.serialize()
  32318. ], Material.prototype, "pointSize", void 0);
  32319. __decorate([
  32320. BABYLON.serialize()
  32321. ], Material.prototype, "zOffset", void 0);
  32322. __decorate([
  32323. BABYLON.serialize()
  32324. ], Material.prototype, "wireframe", null);
  32325. __decorate([
  32326. BABYLON.serialize()
  32327. ], Material.prototype, "pointsCloud", null);
  32328. __decorate([
  32329. BABYLON.serialize()
  32330. ], Material.prototype, "fillMode", null);
  32331. return Material;
  32332. }());
  32333. BABYLON.Material = Material;
  32334. })(BABYLON || (BABYLON = {}));
  32335. //# sourceMappingURL=babylon.material.js.map
  32336. var BABYLON;
  32337. (function (BABYLON) {
  32338. var UniformBuffer = /** @class */ (function () {
  32339. /**
  32340. * Uniform buffer objects.
  32341. *
  32342. * Handles blocks of uniform on the GPU.
  32343. *
  32344. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32345. *
  32346. * For more information, please refer to :
  32347. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32348. */
  32349. function UniformBuffer(engine, data, dynamic) {
  32350. this._engine = engine;
  32351. this._noUBO = !engine.supportsUniformBuffers;
  32352. this._dynamic = dynamic;
  32353. this._data = data || [];
  32354. this._uniformLocations = {};
  32355. this._uniformSizes = {};
  32356. this._uniformLocationPointer = 0;
  32357. this._needSync = false;
  32358. if (this._noUBO) {
  32359. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32360. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32361. this.updateFloat = this._updateFloatForEffect;
  32362. this.updateFloat2 = this._updateFloat2ForEffect;
  32363. this.updateFloat3 = this._updateFloat3ForEffect;
  32364. this.updateFloat4 = this._updateFloat4ForEffect;
  32365. this.updateMatrix = this._updateMatrixForEffect;
  32366. this.updateVector3 = this._updateVector3ForEffect;
  32367. this.updateVector4 = this._updateVector4ForEffect;
  32368. this.updateColor3 = this._updateColor3ForEffect;
  32369. this.updateColor4 = this._updateColor4ForEffect;
  32370. }
  32371. else {
  32372. this._engine._uniformBuffers.push(this);
  32373. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32374. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32375. this.updateFloat = this._updateFloatForUniform;
  32376. this.updateFloat2 = this._updateFloat2ForUniform;
  32377. this.updateFloat3 = this._updateFloat3ForUniform;
  32378. this.updateFloat4 = this._updateFloat4ForUniform;
  32379. this.updateMatrix = this._updateMatrixForUniform;
  32380. this.updateVector3 = this._updateVector3ForUniform;
  32381. this.updateVector4 = this._updateVector4ForUniform;
  32382. this.updateColor3 = this._updateColor3ForUniform;
  32383. this.updateColor4 = this._updateColor4ForUniform;
  32384. }
  32385. }
  32386. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32387. // Properties
  32388. /**
  32389. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32390. * or just falling back on setUniformXXX calls.
  32391. */
  32392. get: function () {
  32393. return !this._noUBO;
  32394. },
  32395. enumerable: true,
  32396. configurable: true
  32397. });
  32398. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32399. /**
  32400. * Indicates if the WebGL underlying uniform buffer is in sync
  32401. * with the javascript cache data.
  32402. */
  32403. get: function () {
  32404. return !this._needSync;
  32405. },
  32406. enumerable: true,
  32407. configurable: true
  32408. });
  32409. /**
  32410. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32411. * Also, a dynamic UniformBuffer will disable cache verification and always
  32412. * update the underlying WebGL uniform buffer to the GPU.
  32413. */
  32414. UniformBuffer.prototype.isDynamic = function () {
  32415. return this._dynamic !== undefined;
  32416. };
  32417. /**
  32418. * The data cache on JS side.
  32419. */
  32420. UniformBuffer.prototype.getData = function () {
  32421. return this._bufferData;
  32422. };
  32423. /**
  32424. * The underlying WebGL Uniform buffer.
  32425. */
  32426. UniformBuffer.prototype.getBuffer = function () {
  32427. return this._buffer;
  32428. };
  32429. /**
  32430. * std140 layout specifies how to align data within an UBO structure.
  32431. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32432. * for specs.
  32433. */
  32434. UniformBuffer.prototype._fillAlignment = function (size) {
  32435. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32436. // and 4x4 matrices
  32437. // TODO : change if other types are used
  32438. var alignment;
  32439. if (size <= 2) {
  32440. alignment = size;
  32441. }
  32442. else {
  32443. alignment = 4;
  32444. }
  32445. if ((this._uniformLocationPointer % alignment) !== 0) {
  32446. var oldPointer = this._uniformLocationPointer;
  32447. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32448. var diff = this._uniformLocationPointer - oldPointer;
  32449. for (var i = 0; i < diff; i++) {
  32450. this._data.push(0);
  32451. }
  32452. }
  32453. };
  32454. /**
  32455. * Adds an uniform in the buffer.
  32456. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32457. * for the layout to be correct !
  32458. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32459. * @param {number|number[]} size Data size, or data directly.
  32460. */
  32461. UniformBuffer.prototype.addUniform = function (name, size) {
  32462. if (this._noUBO) {
  32463. return;
  32464. }
  32465. if (this._uniformLocations[name] !== undefined) {
  32466. // Already existing uniform
  32467. return;
  32468. }
  32469. // This function must be called in the order of the shader layout !
  32470. // size can be the size of the uniform, or data directly
  32471. var data;
  32472. if (size instanceof Array) {
  32473. data = size;
  32474. size = data.length;
  32475. }
  32476. else {
  32477. size = size;
  32478. data = [];
  32479. // Fill with zeros
  32480. for (var i = 0; i < size; i++) {
  32481. data.push(0);
  32482. }
  32483. }
  32484. this._fillAlignment(size);
  32485. this._uniformSizes[name] = size;
  32486. this._uniformLocations[name] = this._uniformLocationPointer;
  32487. this._uniformLocationPointer += size;
  32488. for (var i = 0; i < size; i++) {
  32489. this._data.push(data[i]);
  32490. }
  32491. this._needSync = true;
  32492. };
  32493. /**
  32494. * Wrapper for addUniform.
  32495. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32496. * @param {Matrix} mat A 4x4 matrix.
  32497. */
  32498. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32499. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32500. };
  32501. /**
  32502. * Wrapper for addUniform.
  32503. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32504. * @param {number} x
  32505. * @param {number} y
  32506. */
  32507. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32508. var temp = [x, y];
  32509. this.addUniform(name, temp);
  32510. };
  32511. /**
  32512. * Wrapper for addUniform.
  32513. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32514. * @param {number} x
  32515. * @param {number} y
  32516. * @param {number} z
  32517. */
  32518. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32519. var temp = [x, y, z];
  32520. this.addUniform(name, temp);
  32521. };
  32522. /**
  32523. * Wrapper for addUniform.
  32524. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32525. * @param {Color3} color
  32526. */
  32527. UniformBuffer.prototype.addColor3 = function (name, color) {
  32528. var temp = new Array();
  32529. color.toArray(temp);
  32530. this.addUniform(name, temp);
  32531. };
  32532. /**
  32533. * Wrapper for addUniform.
  32534. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32535. * @param {Color3} color
  32536. * @param {number} alpha
  32537. */
  32538. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32539. var temp = new Array();
  32540. color.toArray(temp);
  32541. temp.push(alpha);
  32542. this.addUniform(name, temp);
  32543. };
  32544. /**
  32545. * Wrapper for addUniform.
  32546. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32547. * @param {Vector3} vector
  32548. */
  32549. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32550. var temp = new Array();
  32551. vector.toArray(temp);
  32552. this.addUniform(name, temp);
  32553. };
  32554. /**
  32555. * Wrapper for addUniform.
  32556. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32557. */
  32558. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32559. this.addUniform(name, 12);
  32560. };
  32561. /**
  32562. * Wrapper for addUniform.
  32563. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32564. */
  32565. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32566. this.addUniform(name, 8);
  32567. };
  32568. /**
  32569. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32570. */
  32571. UniformBuffer.prototype.create = function () {
  32572. if (this._noUBO) {
  32573. return;
  32574. }
  32575. if (this._buffer) {
  32576. return; // nothing to do
  32577. }
  32578. // See spec, alignment must be filled as a vec4
  32579. this._fillAlignment(4);
  32580. this._bufferData = new Float32Array(this._data);
  32581. this._rebuild();
  32582. this._needSync = true;
  32583. };
  32584. UniformBuffer.prototype._rebuild = function () {
  32585. if (this._noUBO) {
  32586. return;
  32587. }
  32588. if (this._dynamic) {
  32589. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32590. }
  32591. else {
  32592. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32593. }
  32594. };
  32595. /**
  32596. * Updates the WebGL Uniform Buffer on the GPU.
  32597. * If the `dynamic` flag is set to true, no cache comparison is done.
  32598. * Otherwise, the buffer will be updated only if the cache differs.
  32599. */
  32600. UniformBuffer.prototype.update = function () {
  32601. if (!this._buffer) {
  32602. this.create();
  32603. return;
  32604. }
  32605. if (!this._dynamic && !this._needSync) {
  32606. return;
  32607. }
  32608. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32609. this._needSync = false;
  32610. };
  32611. /**
  32612. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32613. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32614. * @param {number[]|Float32Array} data Flattened data
  32615. * @param {number} size Size of the data.
  32616. */
  32617. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32618. var location = this._uniformLocations[uniformName];
  32619. if (location === undefined) {
  32620. if (this._buffer) {
  32621. // Cannot add an uniform if the buffer is already created
  32622. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32623. return;
  32624. }
  32625. this.addUniform(uniformName, size);
  32626. location = this._uniformLocations[uniformName];
  32627. }
  32628. if (!this._buffer) {
  32629. this.create();
  32630. }
  32631. if (!this._dynamic) {
  32632. // Cache for static uniform buffers
  32633. var changed = false;
  32634. for (var i = 0; i < size; i++) {
  32635. if (this._bufferData[location + i] !== data[i]) {
  32636. changed = true;
  32637. this._bufferData[location + i] = data[i];
  32638. }
  32639. }
  32640. this._needSync = this._needSync || changed;
  32641. }
  32642. else {
  32643. // No cache for dynamic
  32644. for (var i = 0; i < size; i++) {
  32645. this._bufferData[location + i] = data[i];
  32646. }
  32647. }
  32648. };
  32649. // Update methods
  32650. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32651. // To match std140, matrix must be realigned
  32652. for (var i = 0; i < 3; i++) {
  32653. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32654. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32655. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32656. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32657. }
  32658. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32659. };
  32660. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32661. this._currentEffect.setMatrix3x3(name, matrix);
  32662. };
  32663. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32664. this._currentEffect.setMatrix2x2(name, matrix);
  32665. };
  32666. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32667. // To match std140, matrix must be realigned
  32668. for (var i = 0; i < 2; i++) {
  32669. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32670. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32671. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32672. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32673. }
  32674. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32675. };
  32676. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32677. this._currentEffect.setFloat(name, x);
  32678. };
  32679. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32680. UniformBuffer._tempBuffer[0] = x;
  32681. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32682. };
  32683. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32684. if (suffix === void 0) { suffix = ""; }
  32685. this._currentEffect.setFloat2(name + suffix, x, y);
  32686. };
  32687. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32688. if (suffix === void 0) { suffix = ""; }
  32689. UniformBuffer._tempBuffer[0] = x;
  32690. UniformBuffer._tempBuffer[1] = y;
  32691. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32692. };
  32693. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32694. if (suffix === void 0) { suffix = ""; }
  32695. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32696. };
  32697. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32698. if (suffix === void 0) { suffix = ""; }
  32699. UniformBuffer._tempBuffer[0] = x;
  32700. UniformBuffer._tempBuffer[1] = y;
  32701. UniformBuffer._tempBuffer[2] = z;
  32702. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32703. };
  32704. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32705. if (suffix === void 0) { suffix = ""; }
  32706. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32707. };
  32708. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32709. if (suffix === void 0) { suffix = ""; }
  32710. UniformBuffer._tempBuffer[0] = x;
  32711. UniformBuffer._tempBuffer[1] = y;
  32712. UniformBuffer._tempBuffer[2] = z;
  32713. UniformBuffer._tempBuffer[3] = w;
  32714. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32715. };
  32716. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32717. this._currentEffect.setMatrix(name, mat);
  32718. };
  32719. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32720. this.updateUniform(name, mat.toArray(), 16);
  32721. };
  32722. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32723. this._currentEffect.setVector3(name, vector);
  32724. };
  32725. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32726. vector.toArray(UniformBuffer._tempBuffer);
  32727. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32728. };
  32729. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32730. this._currentEffect.setVector4(name, vector);
  32731. };
  32732. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32733. vector.toArray(UniformBuffer._tempBuffer);
  32734. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32735. };
  32736. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32737. if (suffix === void 0) { suffix = ""; }
  32738. this._currentEffect.setColor3(name + suffix, color);
  32739. };
  32740. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32741. if (suffix === void 0) { suffix = ""; }
  32742. color.toArray(UniformBuffer._tempBuffer);
  32743. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32744. };
  32745. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32746. if (suffix === void 0) { suffix = ""; }
  32747. this._currentEffect.setColor4(name + suffix, color, alpha);
  32748. };
  32749. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32750. if (suffix === void 0) { suffix = ""; }
  32751. color.toArray(UniformBuffer._tempBuffer);
  32752. UniformBuffer._tempBuffer[3] = alpha;
  32753. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32754. };
  32755. /**
  32756. * Sets a sampler uniform on the effect.
  32757. * @param {string} name Name of the sampler.
  32758. * @param {Texture} texture
  32759. */
  32760. UniformBuffer.prototype.setTexture = function (name, texture) {
  32761. this._currentEffect.setTexture(name, texture);
  32762. };
  32763. /**
  32764. * Directly updates the value of the uniform in the cache AND on the GPU.
  32765. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32766. * @param {number[]|Float32Array} data Flattened data
  32767. */
  32768. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32769. this.updateUniform(uniformName, data, data.length);
  32770. this.update();
  32771. };
  32772. /**
  32773. * Binds this uniform buffer to an effect.
  32774. * @param {Effect} effect
  32775. * @param {string} name Name of the uniform block in the shader.
  32776. */
  32777. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32778. this._currentEffect = effect;
  32779. if (this._noUBO || !this._buffer) {
  32780. return;
  32781. }
  32782. effect.bindUniformBuffer(this._buffer, name);
  32783. };
  32784. /**
  32785. * Disposes the uniform buffer.
  32786. */
  32787. UniformBuffer.prototype.dispose = function () {
  32788. if (this._noUBO) {
  32789. return;
  32790. }
  32791. var index = this._engine._uniformBuffers.indexOf(this);
  32792. if (index !== -1) {
  32793. this._engine._uniformBuffers.splice(index, 1);
  32794. }
  32795. if (!this._buffer) {
  32796. return;
  32797. }
  32798. if (this._engine._releaseBuffer(this._buffer)) {
  32799. this._buffer = null;
  32800. }
  32801. };
  32802. // Pool for avoiding memory leaks
  32803. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32804. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32805. return UniformBuffer;
  32806. }());
  32807. BABYLON.UniformBuffer = UniformBuffer;
  32808. })(BABYLON || (BABYLON = {}));
  32809. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32810. var BABYLON;
  32811. (function (BABYLON) {
  32812. var VertexData = /** @class */ (function () {
  32813. function VertexData() {
  32814. }
  32815. VertexData.prototype.set = function (data, kind) {
  32816. switch (kind) {
  32817. case BABYLON.VertexBuffer.PositionKind:
  32818. this.positions = data;
  32819. break;
  32820. case BABYLON.VertexBuffer.NormalKind:
  32821. this.normals = data;
  32822. break;
  32823. case BABYLON.VertexBuffer.TangentKind:
  32824. this.tangents = data;
  32825. break;
  32826. case BABYLON.VertexBuffer.UVKind:
  32827. this.uvs = data;
  32828. break;
  32829. case BABYLON.VertexBuffer.UV2Kind:
  32830. this.uvs2 = data;
  32831. break;
  32832. case BABYLON.VertexBuffer.UV3Kind:
  32833. this.uvs3 = data;
  32834. break;
  32835. case BABYLON.VertexBuffer.UV4Kind:
  32836. this.uvs4 = data;
  32837. break;
  32838. case BABYLON.VertexBuffer.UV5Kind:
  32839. this.uvs5 = data;
  32840. break;
  32841. case BABYLON.VertexBuffer.UV6Kind:
  32842. this.uvs6 = data;
  32843. break;
  32844. case BABYLON.VertexBuffer.ColorKind:
  32845. this.colors = data;
  32846. break;
  32847. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32848. this.matricesIndices = data;
  32849. break;
  32850. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32851. this.matricesWeights = data;
  32852. break;
  32853. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32854. this.matricesIndicesExtra = data;
  32855. break;
  32856. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32857. this.matricesWeightsExtra = data;
  32858. break;
  32859. }
  32860. };
  32861. /**
  32862. * Associates the vertexData to the passed Mesh.
  32863. * Sets it as updatable or not (default `false`).
  32864. * Returns the VertexData.
  32865. */
  32866. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32867. this._applyTo(mesh, updatable);
  32868. return this;
  32869. };
  32870. /**
  32871. * Associates the vertexData to the passed Geometry.
  32872. * Sets it as updatable or not (default `false`).
  32873. * Returns the VertexData.
  32874. */
  32875. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32876. this._applyTo(geometry, updatable);
  32877. return this;
  32878. };
  32879. /**
  32880. * Updates the associated mesh.
  32881. * Returns the VertexData.
  32882. */
  32883. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32884. this._update(mesh);
  32885. return this;
  32886. };
  32887. /**
  32888. * Updates the associated geometry.
  32889. * Returns the VertexData.
  32890. */
  32891. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32892. this._update(geometry);
  32893. return this;
  32894. };
  32895. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32896. if (updatable === void 0) { updatable = false; }
  32897. if (this.positions) {
  32898. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32899. }
  32900. if (this.normals) {
  32901. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32902. }
  32903. if (this.tangents) {
  32904. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32905. }
  32906. if (this.uvs) {
  32907. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32908. }
  32909. if (this.uvs2) {
  32910. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32911. }
  32912. if (this.uvs3) {
  32913. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32914. }
  32915. if (this.uvs4) {
  32916. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32917. }
  32918. if (this.uvs5) {
  32919. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32920. }
  32921. if (this.uvs6) {
  32922. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32923. }
  32924. if (this.colors) {
  32925. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32926. }
  32927. if (this.matricesIndices) {
  32928. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32929. }
  32930. if (this.matricesWeights) {
  32931. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32932. }
  32933. if (this.matricesIndicesExtra) {
  32934. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32935. }
  32936. if (this.matricesWeightsExtra) {
  32937. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32938. }
  32939. if (this.indices) {
  32940. meshOrGeometry.setIndices(this.indices, null, updatable);
  32941. }
  32942. return this;
  32943. };
  32944. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32945. if (this.positions) {
  32946. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32947. }
  32948. if (this.normals) {
  32949. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32950. }
  32951. if (this.tangents) {
  32952. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32953. }
  32954. if (this.uvs) {
  32955. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32956. }
  32957. if (this.uvs2) {
  32958. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32959. }
  32960. if (this.uvs3) {
  32961. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32962. }
  32963. if (this.uvs4) {
  32964. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32965. }
  32966. if (this.uvs5) {
  32967. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32968. }
  32969. if (this.uvs6) {
  32970. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32971. }
  32972. if (this.colors) {
  32973. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32974. }
  32975. if (this.matricesIndices) {
  32976. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32977. }
  32978. if (this.matricesWeights) {
  32979. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32980. }
  32981. if (this.matricesIndicesExtra) {
  32982. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32983. }
  32984. if (this.matricesWeightsExtra) {
  32985. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32986. }
  32987. if (this.indices) {
  32988. meshOrGeometry.setIndices(this.indices, null);
  32989. }
  32990. return this;
  32991. };
  32992. /**
  32993. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32994. * Returns the VertexData.
  32995. */
  32996. VertexData.prototype.transform = function (matrix) {
  32997. var transformed = BABYLON.Vector3.Zero();
  32998. var index;
  32999. if (this.positions) {
  33000. var position = BABYLON.Vector3.Zero();
  33001. for (index = 0; index < this.positions.length; index += 3) {
  33002. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33003. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33004. this.positions[index] = transformed.x;
  33005. this.positions[index + 1] = transformed.y;
  33006. this.positions[index + 2] = transformed.z;
  33007. }
  33008. }
  33009. if (this.normals) {
  33010. var normal = BABYLON.Vector3.Zero();
  33011. for (index = 0; index < this.normals.length; index += 3) {
  33012. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33013. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33014. this.normals[index] = transformed.x;
  33015. this.normals[index + 1] = transformed.y;
  33016. this.normals[index + 2] = transformed.z;
  33017. }
  33018. }
  33019. if (this.tangents) {
  33020. var tangent = BABYLON.Vector4.Zero();
  33021. var tangentTransformed = BABYLON.Vector4.Zero();
  33022. for (index = 0; index < this.tangents.length; index += 4) {
  33023. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33024. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33025. this.tangents[index] = tangentTransformed.x;
  33026. this.tangents[index + 1] = tangentTransformed.y;
  33027. this.tangents[index + 2] = tangentTransformed.z;
  33028. this.tangents[index + 3] = tangentTransformed.w;
  33029. }
  33030. }
  33031. return this;
  33032. };
  33033. /**
  33034. * Merges the passed VertexData into the current one.
  33035. * Returns the modified VertexData.
  33036. */
  33037. VertexData.prototype.merge = function (other) {
  33038. this._validate();
  33039. other._validate();
  33040. if (!this.normals !== !other.normals ||
  33041. !this.tangents !== !other.tangents ||
  33042. !this.uvs !== !other.uvs ||
  33043. !this.uvs2 !== !other.uvs2 ||
  33044. !this.uvs3 !== !other.uvs3 ||
  33045. !this.uvs4 !== !other.uvs4 ||
  33046. !this.uvs5 !== !other.uvs5 ||
  33047. !this.uvs6 !== !other.uvs6 ||
  33048. !this.colors !== !other.colors ||
  33049. !this.matricesIndices !== !other.matricesIndices ||
  33050. !this.matricesWeights !== !other.matricesWeights ||
  33051. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33052. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33053. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33054. }
  33055. if (other.indices) {
  33056. if (!this.indices) {
  33057. this.indices = [];
  33058. }
  33059. var offset = this.positions ? this.positions.length / 3 : 0;
  33060. for (var index = 0; index < other.indices.length; index++) {
  33061. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33062. this.indices.push(other.indices[index] + offset);
  33063. }
  33064. }
  33065. this.positions = this._mergeElement(this.positions, other.positions);
  33066. this.normals = this._mergeElement(this.normals, other.normals);
  33067. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33068. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33069. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33070. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33071. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33072. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33073. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33074. this.colors = this._mergeElement(this.colors, other.colors);
  33075. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33076. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33077. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33078. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33079. return this;
  33080. };
  33081. VertexData.prototype._mergeElement = function (source, other) {
  33082. if (!source) {
  33083. return other;
  33084. }
  33085. if (!other) {
  33086. return source;
  33087. }
  33088. var len = other.length + source.length;
  33089. var isSrcTypedArray = source instanceof Float32Array;
  33090. var isOthTypedArray = other instanceof Float32Array;
  33091. // use non-loop method when the source is Float32Array
  33092. if (isSrcTypedArray) {
  33093. var ret32 = new Float32Array(len);
  33094. ret32.set(source);
  33095. ret32.set(other, source.length);
  33096. return ret32;
  33097. // source is number[], when other is also use concat
  33098. }
  33099. else if (!isOthTypedArray) {
  33100. return source.concat(other);
  33101. // source is a number[], but other is a Float32Array, loop required
  33102. }
  33103. else {
  33104. var ret = source.slice(0); // copy source to a separate array
  33105. for (var i = 0, len = other.length; i < len; i++) {
  33106. ret.push(other[i]);
  33107. }
  33108. return ret;
  33109. }
  33110. };
  33111. VertexData.prototype._validate = function () {
  33112. if (!this.positions) {
  33113. throw new Error("Positions are required");
  33114. }
  33115. var getElementCount = function (kind, values) {
  33116. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33117. if ((values.length % stride) !== 0) {
  33118. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33119. }
  33120. return values.length / stride;
  33121. };
  33122. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33123. var validateElementCount = function (kind, values) {
  33124. var elementCount = getElementCount(kind, values);
  33125. if (elementCount !== positionsElementCount) {
  33126. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33127. }
  33128. };
  33129. if (this.normals)
  33130. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33131. if (this.tangents)
  33132. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33133. if (this.uvs)
  33134. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33135. if (this.uvs2)
  33136. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33137. if (this.uvs3)
  33138. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33139. if (this.uvs4)
  33140. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33141. if (this.uvs5)
  33142. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33143. if (this.uvs6)
  33144. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33145. if (this.colors)
  33146. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33147. if (this.matricesIndices)
  33148. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33149. if (this.matricesWeights)
  33150. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33151. if (this.matricesIndicesExtra)
  33152. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33153. if (this.matricesWeightsExtra)
  33154. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33155. };
  33156. /**
  33157. * Serializes the VertexData.
  33158. * Returns a serialized object.
  33159. */
  33160. VertexData.prototype.serialize = function () {
  33161. var serializationObject = this.serialize();
  33162. if (this.positions) {
  33163. serializationObject.positions = this.positions;
  33164. }
  33165. if (this.normals) {
  33166. serializationObject.normals = this.normals;
  33167. }
  33168. if (this.tangents) {
  33169. serializationObject.tangents = this.tangents;
  33170. }
  33171. if (this.uvs) {
  33172. serializationObject.uvs = this.uvs;
  33173. }
  33174. if (this.uvs2) {
  33175. serializationObject.uvs2 = this.uvs2;
  33176. }
  33177. if (this.uvs3) {
  33178. serializationObject.uvs3 = this.uvs3;
  33179. }
  33180. if (this.uvs4) {
  33181. serializationObject.uvs4 = this.uvs4;
  33182. }
  33183. if (this.uvs5) {
  33184. serializationObject.uvs5 = this.uvs5;
  33185. }
  33186. if (this.uvs6) {
  33187. serializationObject.uvs6 = this.uvs6;
  33188. }
  33189. if (this.colors) {
  33190. serializationObject.colors = this.colors;
  33191. }
  33192. if (this.matricesIndices) {
  33193. serializationObject.matricesIndices = this.matricesIndices;
  33194. serializationObject.matricesIndices._isExpanded = true;
  33195. }
  33196. if (this.matricesWeights) {
  33197. serializationObject.matricesWeights = this.matricesWeights;
  33198. }
  33199. if (this.matricesIndicesExtra) {
  33200. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33201. serializationObject.matricesIndicesExtra._isExpanded = true;
  33202. }
  33203. if (this.matricesWeightsExtra) {
  33204. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33205. }
  33206. serializationObject.indices = this.indices;
  33207. return serializationObject;
  33208. };
  33209. // Statics
  33210. /**
  33211. * Returns the object VertexData associated to the passed mesh.
  33212. */
  33213. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33214. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33215. };
  33216. /**
  33217. * Returns the object VertexData associated to the passed geometry.
  33218. */
  33219. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33220. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33221. };
  33222. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33223. var result = new VertexData();
  33224. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33225. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33226. }
  33227. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33228. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33229. }
  33230. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33231. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33232. }
  33233. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33234. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33235. }
  33236. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33237. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33238. }
  33239. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33240. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33241. }
  33242. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33243. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33244. }
  33245. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33246. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33247. }
  33248. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33249. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33250. }
  33251. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33252. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33253. }
  33254. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33255. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33256. }
  33257. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33258. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33259. }
  33260. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33261. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33262. }
  33263. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33264. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33265. }
  33266. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33267. return result;
  33268. };
  33269. /**
  33270. * Creates the vertexData of the Ribbon.
  33271. */
  33272. VertexData.CreateRibbon = function (options) {
  33273. var pathArray = options.pathArray;
  33274. var closeArray = options.closeArray || false;
  33275. var closePath = options.closePath || false;
  33276. var invertUV = options.invertUV || false;
  33277. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33278. var offset = options.offset || defaultOffset;
  33279. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33280. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33281. var customUV = options.uvs;
  33282. var customColors = options.colors;
  33283. var positions = [];
  33284. var indices = [];
  33285. var normals = [];
  33286. var uvs = [];
  33287. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33288. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33289. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33290. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33291. var minlg; // minimal length among all paths from pathArray
  33292. var lg = []; // array of path lengths : nb of vertex per path
  33293. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33294. var p; // path iterator
  33295. var i; // point iterator
  33296. var j; // point iterator
  33297. // if single path in pathArray
  33298. if (pathArray.length < 2) {
  33299. var ar1 = [];
  33300. var ar2 = [];
  33301. for (i = 0; i < pathArray[0].length - offset; i++) {
  33302. ar1.push(pathArray[0][i]);
  33303. ar2.push(pathArray[0][i + offset]);
  33304. }
  33305. pathArray = [ar1, ar2];
  33306. }
  33307. // positions and horizontal distances (u)
  33308. var idc = 0;
  33309. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33310. var path;
  33311. var l;
  33312. minlg = pathArray[0].length;
  33313. var vectlg;
  33314. var dist;
  33315. for (p = 0; p < pathArray.length; p++) {
  33316. uTotalDistance[p] = 0;
  33317. us[p] = [0];
  33318. path = pathArray[p];
  33319. l = path.length;
  33320. minlg = (minlg < l) ? minlg : l;
  33321. j = 0;
  33322. while (j < l) {
  33323. positions.push(path[j].x, path[j].y, path[j].z);
  33324. if (j > 0) {
  33325. vectlg = path[j].subtract(path[j - 1]).length();
  33326. dist = vectlg + uTotalDistance[p];
  33327. us[p].push(dist);
  33328. uTotalDistance[p] = dist;
  33329. }
  33330. j++;
  33331. }
  33332. if (closePath) {
  33333. j--;
  33334. positions.push(path[0].x, path[0].y, path[0].z);
  33335. vectlg = path[j].subtract(path[0]).length();
  33336. dist = vectlg + uTotalDistance[p];
  33337. us[p].push(dist);
  33338. uTotalDistance[p] = dist;
  33339. }
  33340. lg[p] = l + closePathCorr;
  33341. idx[p] = idc;
  33342. idc += (l + closePathCorr);
  33343. }
  33344. // vertical distances (v)
  33345. var path1;
  33346. var path2;
  33347. var vertex1 = null;
  33348. var vertex2 = null;
  33349. for (i = 0; i < minlg + closePathCorr; i++) {
  33350. vTotalDistance[i] = 0;
  33351. vs[i] = [0];
  33352. for (p = 0; p < pathArray.length - 1; p++) {
  33353. path1 = pathArray[p];
  33354. path2 = pathArray[p + 1];
  33355. if (i === minlg) {
  33356. vertex1 = path1[0];
  33357. vertex2 = path2[0];
  33358. }
  33359. else {
  33360. vertex1 = path1[i];
  33361. vertex2 = path2[i];
  33362. }
  33363. vectlg = vertex2.subtract(vertex1).length();
  33364. dist = vectlg + vTotalDistance[i];
  33365. vs[i].push(dist);
  33366. vTotalDistance[i] = dist;
  33367. }
  33368. if (closeArray && vertex2 && vertex1) {
  33369. path1 = pathArray[p];
  33370. path2 = pathArray[0];
  33371. if (i === minlg) {
  33372. vertex2 = path2[0];
  33373. }
  33374. vectlg = vertex2.subtract(vertex1).length();
  33375. dist = vectlg + vTotalDistance[i];
  33376. vTotalDistance[i] = dist;
  33377. }
  33378. }
  33379. // uvs
  33380. var u;
  33381. var v;
  33382. if (customUV) {
  33383. for (p = 0; p < customUV.length; p++) {
  33384. uvs.push(customUV[p].x, customUV[p].y);
  33385. }
  33386. }
  33387. else {
  33388. for (p = 0; p < pathArray.length; p++) {
  33389. for (i = 0; i < minlg + closePathCorr; i++) {
  33390. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33391. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33392. if (invertUV) {
  33393. uvs.push(v, u);
  33394. }
  33395. else {
  33396. uvs.push(u, v);
  33397. }
  33398. }
  33399. }
  33400. }
  33401. // indices
  33402. p = 0; // path index
  33403. var pi = 0; // positions array index
  33404. var l1 = lg[p] - 1; // path1 length
  33405. var l2 = lg[p + 1] - 1; // path2 length
  33406. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33407. var shft = idx[1] - idx[0]; // shift
  33408. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33409. while (pi <= min && p < path1nb) {
  33410. // 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
  33411. indices.push(pi, pi + shft, pi + 1);
  33412. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33413. pi += 1;
  33414. if (pi === min) {
  33415. p++;
  33416. if (p === lg.length - 1) {
  33417. shft = idx[0] - idx[p];
  33418. l1 = lg[p] - 1;
  33419. l2 = lg[0] - 1;
  33420. }
  33421. else {
  33422. shft = idx[p + 1] - idx[p];
  33423. l1 = lg[p] - 1;
  33424. l2 = lg[p + 1] - 1;
  33425. }
  33426. pi = idx[p];
  33427. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33428. }
  33429. }
  33430. // normals
  33431. VertexData.ComputeNormals(positions, indices, normals);
  33432. if (closePath) {
  33433. var indexFirst = 0;
  33434. var indexLast = 0;
  33435. for (p = 0; p < pathArray.length; p++) {
  33436. indexFirst = idx[p] * 3;
  33437. if (p + 1 < pathArray.length) {
  33438. indexLast = (idx[p + 1] - 1) * 3;
  33439. }
  33440. else {
  33441. indexLast = normals.length - 3;
  33442. }
  33443. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33444. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33445. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33446. normals[indexLast] = normals[indexFirst];
  33447. normals[indexLast + 1] = normals[indexFirst + 1];
  33448. normals[indexLast + 2] = normals[indexFirst + 2];
  33449. }
  33450. }
  33451. // sides
  33452. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33453. // Colors
  33454. var colors = null;
  33455. if (customColors) {
  33456. colors = new Float32Array(customColors.length * 4);
  33457. for (var c = 0; c < customColors.length; c++) {
  33458. colors[c * 4] = customColors[c].r;
  33459. colors[c * 4 + 1] = customColors[c].g;
  33460. colors[c * 4 + 2] = customColors[c].b;
  33461. colors[c * 4 + 3] = customColors[c].a;
  33462. }
  33463. }
  33464. // Result
  33465. var vertexData = new VertexData();
  33466. var positions32 = new Float32Array(positions);
  33467. var normals32 = new Float32Array(normals);
  33468. var uvs32 = new Float32Array(uvs);
  33469. vertexData.indices = indices;
  33470. vertexData.positions = positions32;
  33471. vertexData.normals = normals32;
  33472. vertexData.uvs = uvs32;
  33473. if (colors) {
  33474. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33475. }
  33476. if (closePath) {
  33477. vertexData._idx = idx;
  33478. }
  33479. return vertexData;
  33480. };
  33481. /**
  33482. * Creates the VertexData of the Box.
  33483. */
  33484. VertexData.CreateBox = function (options) {
  33485. var normalsSource = [
  33486. new BABYLON.Vector3(0, 0, 1),
  33487. new BABYLON.Vector3(0, 0, -1),
  33488. new BABYLON.Vector3(1, 0, 0),
  33489. new BABYLON.Vector3(-1, 0, 0),
  33490. new BABYLON.Vector3(0, 1, 0),
  33491. new BABYLON.Vector3(0, -1, 0)
  33492. ];
  33493. var indices = [];
  33494. var positions = [];
  33495. var normals = [];
  33496. var uvs = [];
  33497. var width = options.width || options.size || 1;
  33498. var height = options.height || options.size || 1;
  33499. var depth = options.depth || options.size || 1;
  33500. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33501. var faceUV = options.faceUV || new Array(6);
  33502. var faceColors = options.faceColors;
  33503. var colors = [];
  33504. // default face colors and UV if undefined
  33505. for (var f = 0; f < 6; f++) {
  33506. if (faceUV[f] === undefined) {
  33507. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33508. }
  33509. if (faceColors && faceColors[f] === undefined) {
  33510. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33511. }
  33512. }
  33513. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33514. // Create each face in turn.
  33515. for (var index = 0; index < normalsSource.length; index++) {
  33516. var normal = normalsSource[index];
  33517. // Get two vectors perpendicular to the face normal and to each other.
  33518. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33519. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33520. // Six indices (two triangles) per face.
  33521. var verticesLength = positions.length / 3;
  33522. indices.push(verticesLength);
  33523. indices.push(verticesLength + 1);
  33524. indices.push(verticesLength + 2);
  33525. indices.push(verticesLength);
  33526. indices.push(verticesLength + 2);
  33527. indices.push(verticesLength + 3);
  33528. // Four vertices per face.
  33529. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33530. positions.push(vertex.x, vertex.y, vertex.z);
  33531. normals.push(normal.x, normal.y, normal.z);
  33532. uvs.push(faceUV[index].z, faceUV[index].w);
  33533. if (faceColors) {
  33534. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33535. }
  33536. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33537. positions.push(vertex.x, vertex.y, vertex.z);
  33538. normals.push(normal.x, normal.y, normal.z);
  33539. uvs.push(faceUV[index].x, faceUV[index].w);
  33540. if (faceColors) {
  33541. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33542. }
  33543. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33544. positions.push(vertex.x, vertex.y, vertex.z);
  33545. normals.push(normal.x, normal.y, normal.z);
  33546. uvs.push(faceUV[index].x, faceUV[index].y);
  33547. if (faceColors) {
  33548. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33549. }
  33550. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33551. positions.push(vertex.x, vertex.y, vertex.z);
  33552. normals.push(normal.x, normal.y, normal.z);
  33553. uvs.push(faceUV[index].z, faceUV[index].y);
  33554. if (faceColors) {
  33555. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33556. }
  33557. }
  33558. // sides
  33559. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33560. // Result
  33561. var vertexData = new VertexData();
  33562. vertexData.indices = indices;
  33563. vertexData.positions = positions;
  33564. vertexData.normals = normals;
  33565. vertexData.uvs = uvs;
  33566. if (faceColors) {
  33567. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33568. vertexData.colors = totalColors;
  33569. }
  33570. return vertexData;
  33571. };
  33572. /**
  33573. * Creates the VertexData of the Sphere.
  33574. */
  33575. VertexData.CreateSphere = function (options) {
  33576. var segments = options.segments || 32;
  33577. var diameterX = options.diameterX || options.diameter || 1;
  33578. var diameterY = options.diameterY || options.diameter || 1;
  33579. var diameterZ = options.diameterZ || options.diameter || 1;
  33580. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33581. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33582. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33583. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33584. var totalZRotationSteps = 2 + segments;
  33585. var totalYRotationSteps = 2 * totalZRotationSteps;
  33586. var indices = [];
  33587. var positions = [];
  33588. var normals = [];
  33589. var uvs = [];
  33590. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33591. var normalizedZ = zRotationStep / totalZRotationSteps;
  33592. var angleZ = normalizedZ * Math.PI * slice;
  33593. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33594. var normalizedY = yRotationStep / totalYRotationSteps;
  33595. var angleY = normalizedY * Math.PI * 2 * arc;
  33596. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33597. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33598. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33599. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33600. var vertex = complete.multiply(radius);
  33601. var normal = complete.divide(radius).normalize();
  33602. positions.push(vertex.x, vertex.y, vertex.z);
  33603. normals.push(normal.x, normal.y, normal.z);
  33604. uvs.push(normalizedY, normalizedZ);
  33605. }
  33606. if (zRotationStep > 0) {
  33607. var verticesCount = positions.length / 3;
  33608. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33609. indices.push((firstIndex));
  33610. indices.push((firstIndex + 1));
  33611. indices.push(firstIndex + totalYRotationSteps + 1);
  33612. indices.push((firstIndex + totalYRotationSteps + 1));
  33613. indices.push((firstIndex + 1));
  33614. indices.push((firstIndex + totalYRotationSteps + 2));
  33615. }
  33616. }
  33617. }
  33618. // Sides
  33619. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33620. // Result
  33621. var vertexData = new VertexData();
  33622. vertexData.indices = indices;
  33623. vertexData.positions = positions;
  33624. vertexData.normals = normals;
  33625. vertexData.uvs = uvs;
  33626. return vertexData;
  33627. };
  33628. /**
  33629. * Creates the VertexData of the Cylinder or Cone.
  33630. */
  33631. VertexData.CreateCylinder = function (options) {
  33632. var height = options.height || 2;
  33633. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33634. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33635. var tessellation = options.tessellation || 24;
  33636. var subdivisions = options.subdivisions || 1;
  33637. var hasRings = options.hasRings ? true : false;
  33638. var enclose = options.enclose ? true : false;
  33639. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33640. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33641. var faceUV = options.faceUV || new Array(3);
  33642. var faceColors = options.faceColors;
  33643. // default face colors and UV if undefined
  33644. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33645. var ringNb = (hasRings) ? subdivisions : 1;
  33646. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33647. var f;
  33648. for (f = 0; f < surfaceNb; f++) {
  33649. if (faceColors && faceColors[f] === undefined) {
  33650. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33651. }
  33652. }
  33653. for (f = 0; f < surfaceNb; f++) {
  33654. if (faceUV && faceUV[f] === undefined) {
  33655. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33656. }
  33657. }
  33658. var indices = new Array();
  33659. var positions = new Array();
  33660. var normals = new Array();
  33661. var uvs = new Array();
  33662. var colors = new Array();
  33663. var angle_step = Math.PI * 2 * arc / tessellation;
  33664. var angle;
  33665. var h;
  33666. var radius;
  33667. var tan = (diameterBottom - diameterTop) / 2 / height;
  33668. var ringVertex = BABYLON.Vector3.Zero();
  33669. var ringNormal = BABYLON.Vector3.Zero();
  33670. var ringFirstVertex = BABYLON.Vector3.Zero();
  33671. var ringFirstNormal = BABYLON.Vector3.Zero();
  33672. var quadNormal = BABYLON.Vector3.Zero();
  33673. var Y = BABYLON.Axis.Y;
  33674. // positions, normals, uvs
  33675. var i;
  33676. var j;
  33677. var r;
  33678. var ringIdx = 1;
  33679. var s = 1; // surface index
  33680. var cs = 0;
  33681. var v = 0;
  33682. for (i = 0; i <= subdivisions; i++) {
  33683. h = i / subdivisions;
  33684. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33685. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33686. for (r = 0; r < ringIdx; r++) {
  33687. if (hasRings) {
  33688. s += r;
  33689. }
  33690. if (enclose) {
  33691. s += 2 * r;
  33692. }
  33693. for (j = 0; j <= tessellation; j++) {
  33694. angle = j * angle_step;
  33695. // position
  33696. ringVertex.x = Math.cos(-angle) * radius;
  33697. ringVertex.y = -height / 2 + h * height;
  33698. ringVertex.z = Math.sin(-angle) * radius;
  33699. // normal
  33700. if (diameterTop === 0 && i === subdivisions) {
  33701. // if no top cap, reuse former normals
  33702. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33703. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33704. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33705. }
  33706. else {
  33707. ringNormal.x = ringVertex.x;
  33708. ringNormal.z = ringVertex.z;
  33709. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33710. ringNormal.normalize();
  33711. }
  33712. // keep first ring vertex values for enclose
  33713. if (j === 0) {
  33714. ringFirstVertex.copyFrom(ringVertex);
  33715. ringFirstNormal.copyFrom(ringNormal);
  33716. }
  33717. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33718. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33719. if (hasRings) {
  33720. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33721. }
  33722. else {
  33723. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33724. }
  33725. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33726. if (faceColors) {
  33727. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33728. }
  33729. }
  33730. // if enclose, add four vertices and their dedicated normals
  33731. if (arc !== 1 && enclose) {
  33732. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33733. positions.push(0, ringVertex.y, 0);
  33734. positions.push(0, ringVertex.y, 0);
  33735. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33736. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33737. quadNormal.normalize();
  33738. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33739. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33740. quadNormal.normalize();
  33741. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33742. if (hasRings) {
  33743. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33744. }
  33745. else {
  33746. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33747. }
  33748. uvs.push(faceUV[s + 1].x, v);
  33749. uvs.push(faceUV[s + 1].z, v);
  33750. if (hasRings) {
  33751. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33752. }
  33753. else {
  33754. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33755. }
  33756. uvs.push(faceUV[s + 2].x, v);
  33757. uvs.push(faceUV[s + 2].z, v);
  33758. if (faceColors) {
  33759. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33760. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33761. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33762. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33763. }
  33764. }
  33765. if (cs !== s) {
  33766. cs = s;
  33767. }
  33768. }
  33769. }
  33770. // indices
  33771. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33772. var s;
  33773. i = 0;
  33774. for (s = 0; s < subdivisions; s++) {
  33775. var i0 = 0;
  33776. var i1 = 0;
  33777. var i2 = 0;
  33778. var i3 = 0;
  33779. for (j = 0; j < tessellation; j++) {
  33780. i0 = i * (e + 1) + j;
  33781. i1 = (i + 1) * (e + 1) + j;
  33782. i2 = i * (e + 1) + (j + 1);
  33783. i3 = (i + 1) * (e + 1) + (j + 1);
  33784. indices.push(i0, i1, i2);
  33785. indices.push(i3, i2, i1);
  33786. }
  33787. if (arc !== 1 && enclose) {
  33788. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33789. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33790. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33791. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33792. }
  33793. i = (hasRings) ? (i + 2) : (i + 1);
  33794. }
  33795. // Caps
  33796. var createCylinderCap = function (isTop) {
  33797. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33798. if (radius === 0) {
  33799. return;
  33800. }
  33801. // Cap positions, normals & uvs
  33802. var angle;
  33803. var circleVector;
  33804. var i;
  33805. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33806. var c = null;
  33807. if (faceColors) {
  33808. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33809. }
  33810. // cap center
  33811. var vbase = positions.length / 3;
  33812. var offset = isTop ? height / 2 : -height / 2;
  33813. var center = new BABYLON.Vector3(0, offset, 0);
  33814. positions.push(center.x, center.y, center.z);
  33815. normals.push(0, isTop ? 1 : -1, 0);
  33816. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33817. if (c) {
  33818. colors.push(c.r, c.g, c.b, c.a);
  33819. }
  33820. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33821. for (i = 0; i <= tessellation; i++) {
  33822. angle = Math.PI * 2 * i * arc / tessellation;
  33823. var cos = Math.cos(-angle);
  33824. var sin = Math.sin(-angle);
  33825. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33826. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33827. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33828. normals.push(0, isTop ? 1 : -1, 0);
  33829. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33830. if (c) {
  33831. colors.push(c.r, c.g, c.b, c.a);
  33832. }
  33833. }
  33834. // Cap indices
  33835. for (i = 0; i < tessellation; i++) {
  33836. if (!isTop) {
  33837. indices.push(vbase);
  33838. indices.push(vbase + (i + 1));
  33839. indices.push(vbase + (i + 2));
  33840. }
  33841. else {
  33842. indices.push(vbase);
  33843. indices.push(vbase + (i + 2));
  33844. indices.push(vbase + (i + 1));
  33845. }
  33846. }
  33847. };
  33848. // add caps to geometry
  33849. createCylinderCap(false);
  33850. createCylinderCap(true);
  33851. // Sides
  33852. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33853. var vertexData = new VertexData();
  33854. vertexData.indices = indices;
  33855. vertexData.positions = positions;
  33856. vertexData.normals = normals;
  33857. vertexData.uvs = uvs;
  33858. if (faceColors) {
  33859. vertexData.colors = colors;
  33860. }
  33861. return vertexData;
  33862. };
  33863. /**
  33864. * Creates the VertexData of the Torus.
  33865. */
  33866. VertexData.CreateTorus = function (options) {
  33867. var indices = [];
  33868. var positions = [];
  33869. var normals = [];
  33870. var uvs = [];
  33871. var diameter = options.diameter || 1;
  33872. var thickness = options.thickness || 0.5;
  33873. var tessellation = options.tessellation || 16;
  33874. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33875. var stride = tessellation + 1;
  33876. for (var i = 0; i <= tessellation; i++) {
  33877. var u = i / tessellation;
  33878. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33879. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33880. for (var j = 0; j <= tessellation; j++) {
  33881. var v = 1 - j / tessellation;
  33882. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33883. var dx = Math.cos(innerAngle);
  33884. var dy = Math.sin(innerAngle);
  33885. // Create a vertex.
  33886. var normal = new BABYLON.Vector3(dx, dy, 0);
  33887. var position = normal.scale(thickness / 2);
  33888. var textureCoordinate = new BABYLON.Vector2(u, v);
  33889. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33890. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33891. positions.push(position.x, position.y, position.z);
  33892. normals.push(normal.x, normal.y, normal.z);
  33893. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33894. // And create indices for two triangles.
  33895. var nextI = (i + 1) % stride;
  33896. var nextJ = (j + 1) % stride;
  33897. indices.push(i * stride + j);
  33898. indices.push(i * stride + nextJ);
  33899. indices.push(nextI * stride + j);
  33900. indices.push(i * stride + nextJ);
  33901. indices.push(nextI * stride + nextJ);
  33902. indices.push(nextI * stride + j);
  33903. }
  33904. }
  33905. // Sides
  33906. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33907. // Result
  33908. var vertexData = new VertexData();
  33909. vertexData.indices = indices;
  33910. vertexData.positions = positions;
  33911. vertexData.normals = normals;
  33912. vertexData.uvs = uvs;
  33913. return vertexData;
  33914. };
  33915. /**
  33916. * Creates the VertexData of the LineSystem.
  33917. */
  33918. VertexData.CreateLineSystem = function (options) {
  33919. var indices = [];
  33920. var positions = [];
  33921. var lines = options.lines;
  33922. var colors = options.colors;
  33923. var vertexColors = [];
  33924. var idx = 0;
  33925. for (var l = 0; l < lines.length; l++) {
  33926. var points = lines[l];
  33927. for (var index = 0; index < points.length; index++) {
  33928. positions.push(points[index].x, points[index].y, points[index].z);
  33929. if (colors) {
  33930. var color = colors[l];
  33931. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33932. }
  33933. if (index > 0) {
  33934. indices.push(idx - 1);
  33935. indices.push(idx);
  33936. }
  33937. idx++;
  33938. }
  33939. }
  33940. var vertexData = new VertexData();
  33941. vertexData.indices = indices;
  33942. vertexData.positions = positions;
  33943. if (colors) {
  33944. vertexData.colors = vertexColors;
  33945. }
  33946. return vertexData;
  33947. };
  33948. /**
  33949. * Create the VertexData of the DashedLines.
  33950. */
  33951. VertexData.CreateDashedLines = function (options) {
  33952. var dashSize = options.dashSize || 3;
  33953. var gapSize = options.gapSize || 1;
  33954. var dashNb = options.dashNb || 200;
  33955. var points = options.points;
  33956. var positions = new Array();
  33957. var indices = new Array();
  33958. var curvect = BABYLON.Vector3.Zero();
  33959. var lg = 0;
  33960. var nb = 0;
  33961. var shft = 0;
  33962. var dashshft = 0;
  33963. var curshft = 0;
  33964. var idx = 0;
  33965. var i = 0;
  33966. for (i = 0; i < points.length - 1; i++) {
  33967. points[i + 1].subtractToRef(points[i], curvect);
  33968. lg += curvect.length();
  33969. }
  33970. shft = lg / dashNb;
  33971. dashshft = dashSize * shft / (dashSize + gapSize);
  33972. for (i = 0; i < points.length - 1; i++) {
  33973. points[i + 1].subtractToRef(points[i], curvect);
  33974. nb = Math.floor(curvect.length() / shft);
  33975. curvect.normalize();
  33976. for (var j = 0; j < nb; j++) {
  33977. curshft = shft * j;
  33978. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33979. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33980. indices.push(idx, idx + 1);
  33981. idx += 2;
  33982. }
  33983. }
  33984. // Result
  33985. var vertexData = new VertexData();
  33986. vertexData.positions = positions;
  33987. vertexData.indices = indices;
  33988. return vertexData;
  33989. };
  33990. /**
  33991. * Creates the VertexData of the Ground.
  33992. */
  33993. VertexData.CreateGround = function (options) {
  33994. var indices = [];
  33995. var positions = [];
  33996. var normals = [];
  33997. var uvs = [];
  33998. var row, col;
  33999. var width = options.width || 1;
  34000. var height = options.height || 1;
  34001. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34002. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34003. for (row = 0; row <= subdivisionsY; row++) {
  34004. for (col = 0; col <= subdivisionsX; col++) {
  34005. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34006. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34007. positions.push(position.x, position.y, position.z);
  34008. normals.push(normal.x, normal.y, normal.z);
  34009. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34010. }
  34011. }
  34012. for (row = 0; row < subdivisionsY; row++) {
  34013. for (col = 0; col < subdivisionsX; col++) {
  34014. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34015. indices.push(col + 1 + row * (subdivisionsX + 1));
  34016. indices.push(col + row * (subdivisionsX + 1));
  34017. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34018. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34019. indices.push(col + row * (subdivisionsX + 1));
  34020. }
  34021. }
  34022. // Result
  34023. var vertexData = new VertexData();
  34024. vertexData.indices = indices;
  34025. vertexData.positions = positions;
  34026. vertexData.normals = normals;
  34027. vertexData.uvs = uvs;
  34028. return vertexData;
  34029. };
  34030. /**
  34031. * Creates the VertexData of the TiledGround.
  34032. */
  34033. VertexData.CreateTiledGround = function (options) {
  34034. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34035. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34036. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34037. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34038. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34039. var precision = options.precision || { w: 1, h: 1 };
  34040. var indices = new Array();
  34041. var positions = new Array();
  34042. var normals = new Array();
  34043. var uvs = new Array();
  34044. var row, col, tileRow, tileCol;
  34045. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34046. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34047. precision.w = (precision.w < 1) ? 1 : precision.w;
  34048. precision.h = (precision.h < 1) ? 1 : precision.h;
  34049. var tileSize = {
  34050. 'w': (xmax - xmin) / subdivisions.w,
  34051. 'h': (zmax - zmin) / subdivisions.h
  34052. };
  34053. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34054. // Indices
  34055. var base = positions.length / 3;
  34056. var rowLength = precision.w + 1;
  34057. for (row = 0; row < precision.h; row++) {
  34058. for (col = 0; col < precision.w; col++) {
  34059. var square = [
  34060. base + col + row * rowLength,
  34061. base + (col + 1) + row * rowLength,
  34062. base + (col + 1) + (row + 1) * rowLength,
  34063. base + col + (row + 1) * rowLength
  34064. ];
  34065. indices.push(square[1]);
  34066. indices.push(square[2]);
  34067. indices.push(square[3]);
  34068. indices.push(square[0]);
  34069. indices.push(square[1]);
  34070. indices.push(square[3]);
  34071. }
  34072. }
  34073. // Position, normals and uvs
  34074. var position = BABYLON.Vector3.Zero();
  34075. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34076. for (row = 0; row <= precision.h; row++) {
  34077. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34078. for (col = 0; col <= precision.w; col++) {
  34079. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34080. position.y = 0;
  34081. positions.push(position.x, position.y, position.z);
  34082. normals.push(normal.x, normal.y, normal.z);
  34083. uvs.push(col / precision.w, row / precision.h);
  34084. }
  34085. }
  34086. }
  34087. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34088. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34089. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34090. }
  34091. }
  34092. // Result
  34093. var vertexData = new VertexData();
  34094. vertexData.indices = indices;
  34095. vertexData.positions = positions;
  34096. vertexData.normals = normals;
  34097. vertexData.uvs = uvs;
  34098. return vertexData;
  34099. };
  34100. /**
  34101. * Creates the VertexData of the Ground designed from a heightmap.
  34102. */
  34103. VertexData.CreateGroundFromHeightMap = function (options) {
  34104. var indices = [];
  34105. var positions = [];
  34106. var normals = [];
  34107. var uvs = [];
  34108. var row, col;
  34109. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34110. // Vertices
  34111. for (row = 0; row <= options.subdivisions; row++) {
  34112. for (col = 0; col <= options.subdivisions; col++) {
  34113. 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));
  34114. // Compute height
  34115. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34116. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34117. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34118. var r = options.buffer[pos] / 255.0;
  34119. var g = options.buffer[pos + 1] / 255.0;
  34120. var b = options.buffer[pos + 2] / 255.0;
  34121. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34122. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34123. // Add vertex
  34124. positions.push(position.x, position.y, position.z);
  34125. normals.push(0, 0, 0);
  34126. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34127. }
  34128. }
  34129. // Indices
  34130. for (row = 0; row < options.subdivisions; row++) {
  34131. for (col = 0; col < options.subdivisions; col++) {
  34132. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34133. indices.push(col + 1 + row * (options.subdivisions + 1));
  34134. indices.push(col + row * (options.subdivisions + 1));
  34135. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34136. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34137. indices.push(col + row * (options.subdivisions + 1));
  34138. }
  34139. }
  34140. // Normals
  34141. VertexData.ComputeNormals(positions, indices, normals);
  34142. // Result
  34143. var vertexData = new VertexData();
  34144. vertexData.indices = indices;
  34145. vertexData.positions = positions;
  34146. vertexData.normals = normals;
  34147. vertexData.uvs = uvs;
  34148. return vertexData;
  34149. };
  34150. /**
  34151. * Creates the VertexData of the Plane.
  34152. */
  34153. VertexData.CreatePlane = function (options) {
  34154. var indices = [];
  34155. var positions = [];
  34156. var normals = [];
  34157. var uvs = [];
  34158. var width = options.width || options.size || 1;
  34159. var height = options.height || options.size || 1;
  34160. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34161. // Vertices
  34162. var halfWidth = width / 2.0;
  34163. var halfHeight = height / 2.0;
  34164. positions.push(-halfWidth, -halfHeight, 0);
  34165. normals.push(0, 0, -1.0);
  34166. uvs.push(0.0, 0.0);
  34167. positions.push(halfWidth, -halfHeight, 0);
  34168. normals.push(0, 0, -1.0);
  34169. uvs.push(1.0, 0.0);
  34170. positions.push(halfWidth, halfHeight, 0);
  34171. normals.push(0, 0, -1.0);
  34172. uvs.push(1.0, 1.0);
  34173. positions.push(-halfWidth, halfHeight, 0);
  34174. normals.push(0, 0, -1.0);
  34175. uvs.push(0.0, 1.0);
  34176. // Indices
  34177. indices.push(0);
  34178. indices.push(1);
  34179. indices.push(2);
  34180. indices.push(0);
  34181. indices.push(2);
  34182. indices.push(3);
  34183. // Sides
  34184. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34185. // Result
  34186. var vertexData = new VertexData();
  34187. vertexData.indices = indices;
  34188. vertexData.positions = positions;
  34189. vertexData.normals = normals;
  34190. vertexData.uvs = uvs;
  34191. return vertexData;
  34192. };
  34193. /**
  34194. * Creates the VertexData of the Disc or regular Polygon.
  34195. */
  34196. VertexData.CreateDisc = function (options) {
  34197. var positions = new Array();
  34198. var indices = new Array();
  34199. var normals = new Array();
  34200. var uvs = new Array();
  34201. var radius = options.radius || 0.5;
  34202. var tessellation = options.tessellation || 64;
  34203. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34204. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34205. // positions and uvs
  34206. positions.push(0, 0, 0); // disc center first
  34207. uvs.push(0.5, 0.5);
  34208. var theta = Math.PI * 2 * arc;
  34209. var step = theta / tessellation;
  34210. for (var a = 0; a < theta; a += step) {
  34211. var x = Math.cos(a);
  34212. var y = Math.sin(a);
  34213. var u = (x + 1) / 2;
  34214. var v = (1 - y) / 2;
  34215. positions.push(radius * x, radius * y, 0);
  34216. uvs.push(u, v);
  34217. }
  34218. if (arc === 1) {
  34219. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34220. uvs.push(uvs[2], uvs[3]);
  34221. }
  34222. //indices
  34223. var vertexNb = positions.length / 3;
  34224. for (var i = 1; i < vertexNb - 1; i++) {
  34225. indices.push(i + 1, 0, i);
  34226. }
  34227. // result
  34228. VertexData.ComputeNormals(positions, indices, normals);
  34229. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34230. var vertexData = new VertexData();
  34231. vertexData.indices = indices;
  34232. vertexData.positions = positions;
  34233. vertexData.normals = normals;
  34234. vertexData.uvs = uvs;
  34235. return vertexData;
  34236. };
  34237. /**
  34238. * Re-creates the VertexData of the Polygon for sideOrientation.
  34239. */
  34240. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34241. var faceUV = fUV || new Array(3);
  34242. var faceColors = fColors;
  34243. var colors = [];
  34244. // default face colors and UV if undefined
  34245. for (var f = 0; f < 3; f++) {
  34246. if (faceUV[f] === undefined) {
  34247. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34248. }
  34249. if (faceColors && faceColors[f] === undefined) {
  34250. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34251. }
  34252. }
  34253. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34254. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34255. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34256. var indices = polygon.getIndices();
  34257. // set face colours and textures
  34258. var idx = 0;
  34259. var face = 0;
  34260. for (var index = 0; index < normals.length; index += 3) {
  34261. //Edge Face no. 1
  34262. if (Math.abs(normals[index + 1]) < 0.001) {
  34263. face = 1;
  34264. }
  34265. //Top Face no. 0
  34266. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34267. face = 0;
  34268. }
  34269. //Bottom Face no. 2
  34270. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34271. face = 2;
  34272. }
  34273. idx = index / 3;
  34274. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34275. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34276. if (faceColors) {
  34277. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34278. }
  34279. }
  34280. // sides
  34281. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34282. // Result
  34283. var vertexData = new VertexData();
  34284. vertexData.indices = indices;
  34285. vertexData.positions = positions;
  34286. vertexData.normals = normals;
  34287. vertexData.uvs = uvs;
  34288. if (faceColors) {
  34289. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34290. vertexData.colors = totalColors;
  34291. }
  34292. return vertexData;
  34293. };
  34294. /**
  34295. * Creates the VertexData of the IcoSphere.
  34296. */
  34297. VertexData.CreateIcoSphere = function (options) {
  34298. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34299. var radius = options.radius || 1;
  34300. var flat = (options.flat === undefined) ? true : options.flat;
  34301. var subdivisions = options.subdivisions || 4;
  34302. var radiusX = options.radiusX || radius;
  34303. var radiusY = options.radiusY || radius;
  34304. var radiusZ = options.radiusZ || radius;
  34305. var t = (1 + Math.sqrt(5)) / 2;
  34306. // 12 vertex x,y,z
  34307. var ico_vertices = [
  34308. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34309. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34310. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34311. ];
  34312. // index of 3 vertex makes a face of icopshere
  34313. var ico_indices = [
  34314. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34315. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34316. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34317. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34318. ];
  34319. // vertex for uv have aliased position, not for UV
  34320. var vertices_unalias_id = [
  34321. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34322. // vertex alias
  34323. 0,
  34324. 2,
  34325. 3,
  34326. 3,
  34327. 3,
  34328. 4,
  34329. 7,
  34330. 8,
  34331. 9,
  34332. 9,
  34333. 10,
  34334. 11 // 23: B + 12
  34335. ];
  34336. // uv as integer step (not pixels !)
  34337. var ico_vertexuv = [
  34338. 5, 1, 3, 1, 6, 4, 0, 0,
  34339. 5, 3, 4, 2, 2, 2, 4, 0,
  34340. 2, 0, 1, 1, 6, 0, 6, 2,
  34341. // vertex alias (for same vertex on different faces)
  34342. 0, 4,
  34343. 3, 3,
  34344. 4, 4,
  34345. 3, 1,
  34346. 4, 2,
  34347. 4, 4,
  34348. 0, 2,
  34349. 1, 1,
  34350. 2, 2,
  34351. 3, 3,
  34352. 1, 3,
  34353. 2, 4 // 23: B + 12
  34354. ];
  34355. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34356. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34357. // First island of uv mapping
  34358. // v = 4h 3+ 2
  34359. // v = 3h 9+ 4
  34360. // v = 2h 9+ 5 B
  34361. // v = 1h 9 1 0
  34362. // v = 0h 3 8 7 A
  34363. // u = 0 1 2 3 4 5 6 *a
  34364. // Second island of uv mapping
  34365. // v = 4h 0+ B+ 4+
  34366. // v = 3h A+ 2+
  34367. // v = 2h 7+ 6 3+
  34368. // v = 1h 8+ 3+
  34369. // v = 0h
  34370. // u = 0 1 2 3 4 5 6 *a
  34371. // Face layout on texture UV mapping
  34372. // ============
  34373. // \ 4 /\ 16 / ======
  34374. // \ / \ / /\ 11 /
  34375. // \/ 7 \/ / \ /
  34376. // ======= / 10 \/
  34377. // /\ 17 /\ =======
  34378. // / \ / \ \ 15 /\
  34379. // / 8 \/ 12 \ \ / \
  34380. // ============ \/ 6 \
  34381. // \ 18 /\ ============
  34382. // \ / \ \ 5 /\ 0 /
  34383. // \/ 13 \ \ / \ /
  34384. // ======= \/ 1 \/
  34385. // =============
  34386. // /\ 19 /\ 2 /\
  34387. // / \ / \ / \
  34388. // / 14 \/ 9 \/ 3 \
  34389. // ===================
  34390. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34391. var ustep = 138 / 1024;
  34392. var vstep = 239 / 1024;
  34393. var uoffset = 60 / 1024;
  34394. var voffset = 26 / 1024;
  34395. // Second island should have margin, not to touch the first island
  34396. // avoid any borderline artefact in pixel rounding
  34397. var island_u_offset = -40 / 1024;
  34398. var island_v_offset = +20 / 1024;
  34399. // face is either island 0 or 1 :
  34400. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34401. var island = [
  34402. 0, 0, 0, 0, 1,
  34403. 0, 0, 1, 1, 0,
  34404. 0, 0, 1, 1, 0,
  34405. 0, 1, 1, 1, 0 // 15 - 19
  34406. ];
  34407. var indices = new Array();
  34408. var positions = new Array();
  34409. var normals = new Array();
  34410. var uvs = new Array();
  34411. var current_indice = 0;
  34412. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34413. var face_vertex_pos = new Array(3);
  34414. var face_vertex_uv = new Array(3);
  34415. var v012;
  34416. for (v012 = 0; v012 < 3; v012++) {
  34417. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34418. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34419. }
  34420. // create all with normals
  34421. for (var face = 0; face < 20; face++) {
  34422. // 3 vertex per face
  34423. for (v012 = 0; v012 < 3; v012++) {
  34424. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34425. var v_id = ico_indices[3 * face + v012];
  34426. // vertex have 3D position (x,y,z)
  34427. 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]);
  34428. // Normalize to get normal, then scale to radius
  34429. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34430. // uv Coordinates from vertex ID
  34431. 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);
  34432. }
  34433. // Subdivide the face (interpolate pos, norm, uv)
  34434. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34435. // - norm is linear interpolation of vertex corner normal
  34436. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34437. // - uv is linear interpolation
  34438. //
  34439. // Topology is as below for sub-divide by 2
  34440. // vertex shown as v0,v1,v2
  34441. // interp index is i1 to progress in range [v0,v1[
  34442. // interp index is i2 to progress in range [v0,v2[
  34443. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34444. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34445. //
  34446. //
  34447. // i2 v2
  34448. // ^ ^
  34449. // / / \
  34450. // / / \
  34451. // / / \
  34452. // / / (0,1) \
  34453. // / #---------\
  34454. // / / \ (0,0)'/ \
  34455. // / / \ / \
  34456. // / / \ / \
  34457. // / / (0,0) \ / (1,0) \
  34458. // / #---------#---------\
  34459. // v0 v1
  34460. //
  34461. // --------------------> i1
  34462. //
  34463. // interp of (i1,i2):
  34464. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34465. // along i1 : lerp(x0,x1, i1/(S-i2))
  34466. //
  34467. // centroid of triangle is needed to get help normal computation
  34468. // (c1,c2) are used for centroid location
  34469. var interp_vertex = function (i1, i2, c1, c2) {
  34470. // vertex is interpolated from
  34471. // - face_vertex_pos[0..2]
  34472. // - face_vertex_uv[0..2]
  34473. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34474. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34475. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34476. pos_interp.normalize();
  34477. var vertex_normal;
  34478. if (flat) {
  34479. // in flat mode, recalculate normal as face centroid normal
  34480. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34481. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34482. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34483. }
  34484. else {
  34485. // in smooth mode, recalculate normal from each single vertex position
  34486. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34487. }
  34488. // Vertex normal need correction due to X,Y,Z radius scaling
  34489. vertex_normal.x /= radiusX;
  34490. vertex_normal.y /= radiusY;
  34491. vertex_normal.z /= radiusZ;
  34492. vertex_normal.normalize();
  34493. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34494. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34495. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34496. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34497. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34498. uvs.push(uv_interp.x, uv_interp.y);
  34499. // push each vertex has member of a face
  34500. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34501. indices.push(current_indice);
  34502. current_indice++;
  34503. };
  34504. for (var i2 = 0; i2 < subdivisions; i2++) {
  34505. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34506. // face : (i1,i2) for /\ :
  34507. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34508. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34509. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34510. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34511. if (i1 + i2 + 1 < subdivisions) {
  34512. // face : (i1,i2)' for \/ :
  34513. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34514. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34515. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34516. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34517. }
  34518. }
  34519. }
  34520. }
  34521. // Sides
  34522. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34523. // Result
  34524. var vertexData = new VertexData();
  34525. vertexData.indices = indices;
  34526. vertexData.positions = positions;
  34527. vertexData.normals = normals;
  34528. vertexData.uvs = uvs;
  34529. return vertexData;
  34530. };
  34531. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34532. /**
  34533. * Creates the VertexData of the Polyhedron.
  34534. */
  34535. VertexData.CreatePolyhedron = function (options) {
  34536. // provided polyhedron types :
  34537. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34538. // 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)
  34539. var polyhedra = [];
  34540. 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]] };
  34541. 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]] };
  34542. polyhedra[2] = {
  34543. 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]],
  34544. 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]]
  34545. };
  34546. polyhedra[3] = {
  34547. 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]],
  34548. 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]]
  34549. };
  34550. polyhedra[4] = {
  34551. 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]],
  34552. 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]]
  34553. };
  34554. 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]] };
  34555. 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]] };
  34556. 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]] };
  34557. 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]] };
  34558. 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]] };
  34559. 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]] };
  34560. 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]] };
  34561. 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]] };
  34562. 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]] };
  34563. polyhedra[14] = {
  34564. 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]],
  34565. 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]]
  34566. };
  34567. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34568. var size = options.size;
  34569. var sizeX = options.sizeX || size || 1;
  34570. var sizeY = options.sizeY || size || 1;
  34571. var sizeZ = options.sizeZ || size || 1;
  34572. var data = options.custom || polyhedra[type];
  34573. var nbfaces = data.face.length;
  34574. var faceUV = options.faceUV || new Array(nbfaces);
  34575. var faceColors = options.faceColors;
  34576. var flat = (options.flat === undefined) ? true : options.flat;
  34577. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34578. var positions = new Array();
  34579. var indices = new Array();
  34580. var normals = new Array();
  34581. var uvs = new Array();
  34582. var colors = new Array();
  34583. var index = 0;
  34584. var faceIdx = 0; // face cursor in the array "indexes"
  34585. var indexes = new Array();
  34586. var i = 0;
  34587. var f = 0;
  34588. var u, v, ang, x, y, tmp;
  34589. // default face colors and UV if undefined
  34590. if (flat) {
  34591. for (f = 0; f < nbfaces; f++) {
  34592. if (faceColors && faceColors[f] === undefined) {
  34593. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34594. }
  34595. if (faceUV && faceUV[f] === undefined) {
  34596. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34597. }
  34598. }
  34599. }
  34600. if (!flat) {
  34601. for (i = 0; i < data.vertex.length; i++) {
  34602. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34603. uvs.push(0, 0);
  34604. }
  34605. for (f = 0; f < nbfaces; f++) {
  34606. for (i = 0; i < data.face[f].length - 2; i++) {
  34607. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34608. }
  34609. }
  34610. }
  34611. else {
  34612. for (f = 0; f < nbfaces; f++) {
  34613. var fl = data.face[f].length; // number of vertices of the current face
  34614. ang = 2 * Math.PI / fl;
  34615. x = 0.5 * Math.tan(ang / 2);
  34616. y = 0.5;
  34617. // positions, uvs, colors
  34618. for (i = 0; i < fl; i++) {
  34619. // positions
  34620. 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);
  34621. indexes.push(index);
  34622. index++;
  34623. // uvs
  34624. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34625. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34626. uvs.push(u, v);
  34627. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34628. y = x * Math.sin(ang) + y * Math.cos(ang);
  34629. x = tmp;
  34630. // colors
  34631. if (faceColors) {
  34632. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34633. }
  34634. }
  34635. // indices from indexes
  34636. for (i = 0; i < fl - 2; i++) {
  34637. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34638. }
  34639. faceIdx += fl;
  34640. }
  34641. }
  34642. VertexData.ComputeNormals(positions, indices, normals);
  34643. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34644. var vertexData = new VertexData();
  34645. vertexData.positions = positions;
  34646. vertexData.indices = indices;
  34647. vertexData.normals = normals;
  34648. vertexData.uvs = uvs;
  34649. if (faceColors && flat) {
  34650. vertexData.colors = colors;
  34651. }
  34652. return vertexData;
  34653. };
  34654. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34655. /**
  34656. * Creates the VertexData of the Torus Knot.
  34657. */
  34658. VertexData.CreateTorusKnot = function (options) {
  34659. var indices = new Array();
  34660. var positions = new Array();
  34661. var normals = new Array();
  34662. var uvs = new Array();
  34663. var radius = options.radius || 2;
  34664. var tube = options.tube || 0.5;
  34665. var radialSegments = options.radialSegments || 32;
  34666. var tubularSegments = options.tubularSegments || 32;
  34667. var p = options.p || 2;
  34668. var q = options.q || 3;
  34669. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34670. // Helper
  34671. var getPos = function (angle) {
  34672. var cu = Math.cos(angle);
  34673. var su = Math.sin(angle);
  34674. var quOverP = q / p * angle;
  34675. var cs = Math.cos(quOverP);
  34676. var tx = radius * (2 + cs) * 0.5 * cu;
  34677. var ty = radius * (2 + cs) * su * 0.5;
  34678. var tz = radius * Math.sin(quOverP) * 0.5;
  34679. return new BABYLON.Vector3(tx, ty, tz);
  34680. };
  34681. // Vertices
  34682. var i;
  34683. var j;
  34684. for (i = 0; i <= radialSegments; i++) {
  34685. var modI = i % radialSegments;
  34686. var u = modI / radialSegments * 2 * p * Math.PI;
  34687. var p1 = getPos(u);
  34688. var p2 = getPos(u + 0.01);
  34689. var tang = p2.subtract(p1);
  34690. var n = p2.add(p1);
  34691. var bitan = BABYLON.Vector3.Cross(tang, n);
  34692. n = BABYLON.Vector3.Cross(bitan, tang);
  34693. bitan.normalize();
  34694. n.normalize();
  34695. for (j = 0; j < tubularSegments; j++) {
  34696. var modJ = j % tubularSegments;
  34697. var v = modJ / tubularSegments * 2 * Math.PI;
  34698. var cx = -tube * Math.cos(v);
  34699. var cy = tube * Math.sin(v);
  34700. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34701. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34702. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34703. uvs.push(i / radialSegments);
  34704. uvs.push(j / tubularSegments);
  34705. }
  34706. }
  34707. for (i = 0; i < radialSegments; i++) {
  34708. for (j = 0; j < tubularSegments; j++) {
  34709. var jNext = (j + 1) % tubularSegments;
  34710. var a = i * tubularSegments + j;
  34711. var b = (i + 1) * tubularSegments + j;
  34712. var c = (i + 1) * tubularSegments + jNext;
  34713. var d = i * tubularSegments + jNext;
  34714. indices.push(d);
  34715. indices.push(b);
  34716. indices.push(a);
  34717. indices.push(d);
  34718. indices.push(c);
  34719. indices.push(b);
  34720. }
  34721. }
  34722. // Normals
  34723. VertexData.ComputeNormals(positions, indices, normals);
  34724. // Sides
  34725. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34726. // Result
  34727. var vertexData = new VertexData();
  34728. vertexData.indices = indices;
  34729. vertexData.positions = positions;
  34730. vertexData.normals = normals;
  34731. vertexData.uvs = uvs;
  34732. return vertexData;
  34733. };
  34734. // Tools
  34735. /**
  34736. * @param {any} - positions (number[] or Float32Array)
  34737. * @param {any} - indices (number[] or Uint16Array)
  34738. * @param {any} - normals (number[] or Float32Array)
  34739. * options (optional) :
  34740. * facetPositions : optional array of facet positions (vector3)
  34741. * facetNormals : optional array of facet normals (vector3)
  34742. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34743. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34744. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34745. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34746. * bInfo : optional bounding info, required for facetPartitioning computation
  34747. * useRightHandedSystem: optional boolean to for right handed system computation
  34748. * depthSort : optional boolean to enable the facet depth sort computation
  34749. * distanceTo : optional Vector3 to compute the facet depth from this location
  34750. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34751. */
  34752. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34753. // temporary scalar variables
  34754. var index = 0; // facet index
  34755. var p1p2x = 0.0; // p1p2 vector x coordinate
  34756. var p1p2y = 0.0; // p1p2 vector y coordinate
  34757. var p1p2z = 0.0; // p1p2 vector z coordinate
  34758. var p3p2x = 0.0; // p3p2 vector x coordinate
  34759. var p3p2y = 0.0; // p3p2 vector y coordinate
  34760. var p3p2z = 0.0; // p3p2 vector z coordinate
  34761. var faceNormalx = 0.0; // facet normal x coordinate
  34762. var faceNormaly = 0.0; // facet normal y coordinate
  34763. var faceNormalz = 0.0; // facet normal z coordinate
  34764. var length = 0.0; // facet normal length before normalization
  34765. var v1x = 0; // vector1 x index in the positions array
  34766. var v1y = 0; // vector1 y index in the positions array
  34767. var v1z = 0; // vector1 z index in the positions array
  34768. var v2x = 0; // vector2 x index in the positions array
  34769. var v2y = 0; // vector2 y index in the positions array
  34770. var v2z = 0; // vector2 z index in the positions array
  34771. var v3x = 0; // vector3 x index in the positions array
  34772. var v3y = 0; // vector3 y index in the positions array
  34773. var v3z = 0; // vector3 z index in the positions array
  34774. var computeFacetNormals = false;
  34775. var computeFacetPositions = false;
  34776. var computeFacetPartitioning = false;
  34777. var computeDepthSort = false;
  34778. var faceNormalSign = 1;
  34779. var ratio = 0;
  34780. var distanceTo = null;
  34781. if (options) {
  34782. computeFacetNormals = (options.facetNormals) ? true : false;
  34783. computeFacetPositions = (options.facetPositions) ? true : false;
  34784. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34785. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34786. ratio = options.ratio || 0;
  34787. computeDepthSort = (options.depthSort) ? true : false;
  34788. distanceTo = (options.distanceTo);
  34789. if (computeDepthSort) {
  34790. if (distanceTo === undefined) {
  34791. distanceTo = BABYLON.Vector3.Zero();
  34792. }
  34793. var depthSortedFacets = options.depthSortedFacets;
  34794. }
  34795. }
  34796. // facetPartitioning reinit if needed
  34797. var xSubRatio = 0;
  34798. var ySubRatio = 0;
  34799. var zSubRatio = 0;
  34800. var subSq = 0;
  34801. if (computeFacetPartitioning && options && options.bbSize) {
  34802. var ox = 0; // X partitioning index for facet position
  34803. var oy = 0; // Y partinioning index for facet position
  34804. var oz = 0; // Z partinioning index for facet position
  34805. var b1x = 0; // X partitioning index for facet v1 vertex
  34806. var b1y = 0; // Y partitioning index for facet v1 vertex
  34807. var b1z = 0; // z partitioning index for facet v1 vertex
  34808. var b2x = 0; // X partitioning index for facet v2 vertex
  34809. var b2y = 0; // Y partitioning index for facet v2 vertex
  34810. var b2z = 0; // Z partitioning index for facet v2 vertex
  34811. var b3x = 0; // X partitioning index for facet v3 vertex
  34812. var b3y = 0; // Y partitioning index for facet v3 vertex
  34813. var b3z = 0; // Z partitioning index for facet v3 vertex
  34814. var block_idx_o = 0; // facet barycenter block index
  34815. var block_idx_v1 = 0; // v1 vertex block index
  34816. var block_idx_v2 = 0; // v2 vertex block index
  34817. var block_idx_v3 = 0; // v3 vertex block index
  34818. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34819. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34820. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34821. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34822. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34823. subSq = options.subDiv.max * options.subDiv.max;
  34824. options.facetPartitioning.length = 0;
  34825. }
  34826. // reset the normals
  34827. for (index = 0; index < positions.length; index++) {
  34828. normals[index] = 0.0;
  34829. }
  34830. // Loop : 1 indice triplet = 1 facet
  34831. var nbFaces = (indices.length / 3) | 0;
  34832. for (index = 0; index < nbFaces; index++) {
  34833. // get the indexes of the coordinates of each vertex of the facet
  34834. v1x = indices[index * 3] * 3;
  34835. v1y = v1x + 1;
  34836. v1z = v1x + 2;
  34837. v2x = indices[index * 3 + 1] * 3;
  34838. v2y = v2x + 1;
  34839. v2z = v2x + 2;
  34840. v3x = indices[index * 3 + 2] * 3;
  34841. v3y = v3x + 1;
  34842. v3z = v3x + 2;
  34843. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34844. p1p2y = positions[v1y] - positions[v2y];
  34845. p1p2z = positions[v1z] - positions[v2z];
  34846. p3p2x = positions[v3x] - positions[v2x];
  34847. p3p2y = positions[v3y] - positions[v2y];
  34848. p3p2z = positions[v3z] - positions[v2z];
  34849. // compute the face normal with the cross product
  34850. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34851. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34852. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34853. // normalize this normal and store it in the array facetData
  34854. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34855. length = (length === 0) ? 1.0 : length;
  34856. faceNormalx /= length;
  34857. faceNormaly /= length;
  34858. faceNormalz /= length;
  34859. if (computeFacetNormals && options) {
  34860. options.facetNormals[index].x = faceNormalx;
  34861. options.facetNormals[index].y = faceNormaly;
  34862. options.facetNormals[index].z = faceNormalz;
  34863. }
  34864. if (computeFacetPositions && options) {
  34865. // compute and the facet barycenter coordinates in the array facetPositions
  34866. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34867. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34868. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34869. }
  34870. if (computeFacetPartitioning && options) {
  34871. // store the facet indexes in arrays in the main facetPartitioning array :
  34872. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34873. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34874. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34875. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34876. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34877. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34878. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34879. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34880. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34881. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34882. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34883. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34884. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34885. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34886. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34887. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34888. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34889. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34890. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34891. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34892. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34893. // push each facet index in each block containing the vertex
  34894. options.facetPartitioning[block_idx_v1].push(index);
  34895. if (block_idx_v2 != block_idx_v1) {
  34896. options.facetPartitioning[block_idx_v2].push(index);
  34897. }
  34898. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34899. options.facetPartitioning[block_idx_v3].push(index);
  34900. }
  34901. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34902. options.facetPartitioning[block_idx_o].push(index);
  34903. }
  34904. }
  34905. if (computeDepthSort && options && options.facetPositions) {
  34906. var dsf = depthSortedFacets[index];
  34907. dsf.ind = index * 3;
  34908. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34909. }
  34910. // compute the normals anyway
  34911. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34912. normals[v1y] += faceNormaly;
  34913. normals[v1z] += faceNormalz;
  34914. normals[v2x] += faceNormalx;
  34915. normals[v2y] += faceNormaly;
  34916. normals[v2z] += faceNormalz;
  34917. normals[v3x] += faceNormalx;
  34918. normals[v3y] += faceNormaly;
  34919. normals[v3z] += faceNormalz;
  34920. }
  34921. // last normalization of each normal
  34922. for (index = 0; index < normals.length / 3; index++) {
  34923. faceNormalx = normals[index * 3];
  34924. faceNormaly = normals[index * 3 + 1];
  34925. faceNormalz = normals[index * 3 + 2];
  34926. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34927. length = (length === 0) ? 1.0 : length;
  34928. faceNormalx /= length;
  34929. faceNormaly /= length;
  34930. faceNormalz /= length;
  34931. normals[index * 3] = faceNormalx;
  34932. normals[index * 3 + 1] = faceNormaly;
  34933. normals[index * 3 + 2] = faceNormalz;
  34934. }
  34935. };
  34936. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34937. var li = indices.length;
  34938. var ln = normals.length;
  34939. var i;
  34940. var n;
  34941. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34942. switch (sideOrientation) {
  34943. case BABYLON.Mesh.FRONTSIDE:
  34944. // nothing changed
  34945. break;
  34946. case BABYLON.Mesh.BACKSIDE:
  34947. var tmp;
  34948. // indices
  34949. for (i = 0; i < li; i += 3) {
  34950. tmp = indices[i];
  34951. indices[i] = indices[i + 2];
  34952. indices[i + 2] = tmp;
  34953. }
  34954. // normals
  34955. for (n = 0; n < ln; n++) {
  34956. normals[n] = -normals[n];
  34957. }
  34958. break;
  34959. case BABYLON.Mesh.DOUBLESIDE:
  34960. // positions
  34961. var lp = positions.length;
  34962. var l = lp / 3;
  34963. for (var p = 0; p < lp; p++) {
  34964. positions[lp + p] = positions[p];
  34965. }
  34966. // indices
  34967. for (i = 0; i < li; i += 3) {
  34968. indices[i + li] = indices[i + 2] + l;
  34969. indices[i + 1 + li] = indices[i + 1] + l;
  34970. indices[i + 2 + li] = indices[i] + l;
  34971. }
  34972. // normals
  34973. for (n = 0; n < ln; n++) {
  34974. normals[ln + n] = -normals[n];
  34975. }
  34976. // uvs
  34977. var lu = uvs.length;
  34978. var u = 0;
  34979. for (u = 0; u < lu; u++) {
  34980. uvs[u + lu] = uvs[u];
  34981. }
  34982. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34983. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34984. u = 0;
  34985. for (i = 0; i < lu / 2; i++) {
  34986. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34987. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34988. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34989. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34990. u += 2;
  34991. }
  34992. break;
  34993. }
  34994. };
  34995. /**
  34996. * Creates a new VertexData from the imported parameters.
  34997. */
  34998. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34999. var vertexData = new VertexData();
  35000. // positions
  35001. var positions = parsedVertexData.positions;
  35002. if (positions) {
  35003. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35004. }
  35005. // normals
  35006. var normals = parsedVertexData.normals;
  35007. if (normals) {
  35008. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35009. }
  35010. // tangents
  35011. var tangents = parsedVertexData.tangents;
  35012. if (tangents) {
  35013. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35014. }
  35015. // uvs
  35016. var uvs = parsedVertexData.uvs;
  35017. if (uvs) {
  35018. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35019. }
  35020. // uv2s
  35021. var uv2s = parsedVertexData.uv2s;
  35022. if (uv2s) {
  35023. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35024. }
  35025. // uv3s
  35026. var uv3s = parsedVertexData.uv3s;
  35027. if (uv3s) {
  35028. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35029. }
  35030. // uv4s
  35031. var uv4s = parsedVertexData.uv4s;
  35032. if (uv4s) {
  35033. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35034. }
  35035. // uv5s
  35036. var uv5s = parsedVertexData.uv5s;
  35037. if (uv5s) {
  35038. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35039. }
  35040. // uv6s
  35041. var uv6s = parsedVertexData.uv6s;
  35042. if (uv6s) {
  35043. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35044. }
  35045. // colors
  35046. var colors = parsedVertexData.colors;
  35047. if (colors) {
  35048. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35049. }
  35050. // matricesIndices
  35051. var matricesIndices = parsedVertexData.matricesIndices;
  35052. if (matricesIndices) {
  35053. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35054. }
  35055. // matricesWeights
  35056. var matricesWeights = parsedVertexData.matricesWeights;
  35057. if (matricesWeights) {
  35058. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35059. }
  35060. // indices
  35061. var indices = parsedVertexData.indices;
  35062. if (indices) {
  35063. vertexData.indices = indices;
  35064. }
  35065. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35066. };
  35067. return VertexData;
  35068. }());
  35069. BABYLON.VertexData = VertexData;
  35070. })(BABYLON || (BABYLON = {}));
  35071. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35072. var BABYLON;
  35073. (function (BABYLON) {
  35074. /**
  35075. * Class used to store geometry data (vertex buffers + index buffer)
  35076. */
  35077. var Geometry = /** @class */ (function () {
  35078. /**
  35079. * Creates a new geometry
  35080. * @param id defines the unique ID
  35081. * @param scene defines the hosting scene
  35082. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35083. * @param updatable defines if geometry must be updatable (false by default)
  35084. * @param mesh defines the mesh that will be associated with the geometry
  35085. */
  35086. function Geometry(id, scene, vertexData, updatable, mesh) {
  35087. if (updatable === void 0) { updatable = false; }
  35088. if (mesh === void 0) { mesh = null; }
  35089. /**
  35090. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35091. */
  35092. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35093. this._totalVertices = 0;
  35094. this._isDisposed = false;
  35095. this._indexBufferIsUpdatable = false;
  35096. this.id = id;
  35097. this._engine = scene.getEngine();
  35098. this._meshes = [];
  35099. this._scene = scene;
  35100. //Init vertex buffer cache
  35101. this._vertexBuffers = {};
  35102. this._indices = [];
  35103. this._updatable = updatable;
  35104. // vertexData
  35105. if (vertexData) {
  35106. this.setAllVerticesData(vertexData, updatable);
  35107. }
  35108. else {
  35109. this._totalVertices = 0;
  35110. this._indices = [];
  35111. }
  35112. if (this._engine.getCaps().vertexArrayObject) {
  35113. this._vertexArrayObjects = {};
  35114. }
  35115. // applyToMesh
  35116. if (mesh) {
  35117. if (mesh.getClassName() === "LinesMesh") {
  35118. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35119. this.updateExtend();
  35120. }
  35121. this.applyToMesh(mesh);
  35122. mesh.computeWorldMatrix(true);
  35123. }
  35124. }
  35125. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35126. /**
  35127. * 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
  35128. */
  35129. get: function () {
  35130. return this._boundingBias;
  35131. },
  35132. /**
  35133. * 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
  35134. */
  35135. set: function (value) {
  35136. if (this._boundingBias && this._boundingBias.equals(value)) {
  35137. return;
  35138. }
  35139. this._boundingBias = value.clone();
  35140. this.updateBoundingInfo(true, null);
  35141. },
  35142. enumerable: true,
  35143. configurable: true
  35144. });
  35145. /**
  35146. * Static function used to attach a new empty geometry to a mesh
  35147. * @param mesh defines the mesh to attach the geometry to
  35148. * @returns the new {BABYLON.Geometry}
  35149. */
  35150. Geometry.CreateGeometryForMesh = function (mesh) {
  35151. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35152. geometry.applyToMesh(mesh);
  35153. return geometry;
  35154. };
  35155. Object.defineProperty(Geometry.prototype, "extend", {
  35156. /**
  35157. * Gets the current extend of the geometry
  35158. */
  35159. get: function () {
  35160. return this._extend;
  35161. },
  35162. enumerable: true,
  35163. configurable: true
  35164. });
  35165. /**
  35166. * Gets the hosting scene
  35167. * @returns the hosting {BABYLON.Scene}
  35168. */
  35169. Geometry.prototype.getScene = function () {
  35170. return this._scene;
  35171. };
  35172. /**
  35173. * Gets the hosting engine
  35174. * @returns the hosting {BABYLON.Engine}
  35175. */
  35176. Geometry.prototype.getEngine = function () {
  35177. return this._engine;
  35178. };
  35179. /**
  35180. * Defines if the geometry is ready to use
  35181. * @returns true if the geometry is ready to be used
  35182. */
  35183. Geometry.prototype.isReady = function () {
  35184. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35185. };
  35186. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35187. /**
  35188. * Gets a value indicating that the geometry should not be serialized
  35189. */
  35190. get: function () {
  35191. for (var index = 0; index < this._meshes.length; index++) {
  35192. if (!this._meshes[index].doNotSerialize) {
  35193. return false;
  35194. }
  35195. }
  35196. return true;
  35197. },
  35198. enumerable: true,
  35199. configurable: true
  35200. });
  35201. /** @ignore */
  35202. Geometry.prototype._rebuild = function () {
  35203. if (this._vertexArrayObjects) {
  35204. this._vertexArrayObjects = {};
  35205. }
  35206. // Index buffer
  35207. if (this._meshes.length !== 0 && this._indices) {
  35208. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35209. }
  35210. // Vertex buffers
  35211. for (var key in this._vertexBuffers) {
  35212. var vertexBuffer = this._vertexBuffers[key];
  35213. vertexBuffer._rebuild();
  35214. }
  35215. };
  35216. /**
  35217. * Affects all gemetry data in one call
  35218. * @param vertexData defines the geometry data
  35219. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35220. */
  35221. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35222. vertexData.applyToGeometry(this, updatable);
  35223. this.notifyUpdate();
  35224. };
  35225. /**
  35226. * Set specific vertex data
  35227. * @param kind defines the data kind (Position, normal, etc...)
  35228. * @param data defines the vertex data to use
  35229. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35230. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35231. */
  35232. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35233. if (updatable === void 0) { updatable = false; }
  35234. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35235. this.setVerticesBuffer(buffer);
  35236. };
  35237. /**
  35238. * Removes a specific vertex data
  35239. * @param kind defines the data kind (Position, normal, etc...)
  35240. */
  35241. Geometry.prototype.removeVerticesData = function (kind) {
  35242. if (this._vertexBuffers[kind]) {
  35243. this._vertexBuffers[kind].dispose();
  35244. delete this._vertexBuffers[kind];
  35245. }
  35246. };
  35247. /**
  35248. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35249. * @param buffer defines the vertex buffer to use
  35250. */
  35251. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35252. var kind = buffer.getKind();
  35253. if (this._vertexBuffers[kind]) {
  35254. this._vertexBuffers[kind].dispose();
  35255. }
  35256. this._vertexBuffers[kind] = buffer;
  35257. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35258. var data = buffer.getData();
  35259. var stride = buffer.getStrideSize();
  35260. this._totalVertices = data.length / stride;
  35261. this.updateExtend(data, stride);
  35262. this._resetPointsArrayCache();
  35263. var meshes = this._meshes;
  35264. var numOfMeshes = meshes.length;
  35265. for (var index = 0; index < numOfMeshes; index++) {
  35266. var mesh = meshes[index];
  35267. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35268. mesh._createGlobalSubMesh(false);
  35269. mesh.computeWorldMatrix(true);
  35270. }
  35271. }
  35272. this.notifyUpdate(kind);
  35273. if (this._vertexArrayObjects) {
  35274. this._disposeVertexArrayObjects();
  35275. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35276. }
  35277. };
  35278. /**
  35279. * Update a specific vertex buffer
  35280. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35281. * It will do nothing if the buffer is not updatable
  35282. * @param kind defines the data kind (Position, normal, etc...)
  35283. * @param data defines the data to use
  35284. * @param offset defines the offset in the target buffer where to store the data
  35285. */
  35286. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35287. var vertexBuffer = this.getVertexBuffer(kind);
  35288. if (!vertexBuffer) {
  35289. return;
  35290. }
  35291. vertexBuffer.updateDirectly(data, offset);
  35292. this.notifyUpdate(kind);
  35293. };
  35294. /**
  35295. * Update a specific vertex buffer
  35296. * This function will create a new buffer if the current one is not updatable
  35297. * @param kind defines the data kind (Position, normal, etc...)
  35298. * @param data defines the data to use
  35299. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35300. */
  35301. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35302. if (updateExtends === void 0) { updateExtends = false; }
  35303. var vertexBuffer = this.getVertexBuffer(kind);
  35304. if (!vertexBuffer) {
  35305. return;
  35306. }
  35307. vertexBuffer.update(data);
  35308. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35309. var stride = vertexBuffer.getStrideSize();
  35310. this._totalVertices = data.length / stride;
  35311. this.updateBoundingInfo(updateExtends, data);
  35312. }
  35313. this.notifyUpdate(kind);
  35314. };
  35315. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35316. if (updateExtends) {
  35317. this.updateExtend(data);
  35318. }
  35319. var meshes = this._meshes;
  35320. var numOfMeshes = meshes.length;
  35321. this._resetPointsArrayCache();
  35322. for (var index = 0; index < numOfMeshes; index++) {
  35323. var mesh = meshes[index];
  35324. if (updateExtends) {
  35325. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35326. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35327. var subMesh = mesh.subMeshes[subIndex];
  35328. subMesh.refreshBoundingInfo();
  35329. }
  35330. }
  35331. }
  35332. };
  35333. /** @ignore */
  35334. Geometry.prototype._bind = function (effect, indexToBind) {
  35335. if (!effect) {
  35336. return;
  35337. }
  35338. if (indexToBind === undefined) {
  35339. indexToBind = this._indexBuffer;
  35340. }
  35341. var vbs = this.getVertexBuffers();
  35342. if (!vbs) {
  35343. return;
  35344. }
  35345. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35346. this._engine.bindBuffers(vbs, indexToBind, effect);
  35347. return;
  35348. }
  35349. // Using VAO
  35350. if (!this._vertexArrayObjects[effect.key]) {
  35351. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35352. }
  35353. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35354. };
  35355. /**
  35356. * Gets total number of vertices
  35357. * @returns the total number of vertices
  35358. */
  35359. Geometry.prototype.getTotalVertices = function () {
  35360. if (!this.isReady()) {
  35361. return 0;
  35362. }
  35363. return this._totalVertices;
  35364. };
  35365. /**
  35366. * Gets a specific vertex data attached to this geometry
  35367. * @param kind defines the data kind (Position, normal, etc...)
  35368. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35369. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35370. * @returns a float array containing vertex data
  35371. */
  35372. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35373. var vertexBuffer = this.getVertexBuffer(kind);
  35374. if (!vertexBuffer) {
  35375. return null;
  35376. }
  35377. var orig = vertexBuffer.getData();
  35378. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35379. return orig;
  35380. }
  35381. else {
  35382. var len = orig.length;
  35383. var copy = [];
  35384. for (var i = 0; i < len; i++) {
  35385. copy.push(orig[i]);
  35386. }
  35387. return copy;
  35388. }
  35389. };
  35390. /**
  35391. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35392. * @param kind defines the data kind (Position, normal, etc...)
  35393. * @returns true if the vertex buffer with the specified kind is updatable
  35394. */
  35395. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35396. var vb = this._vertexBuffers[kind];
  35397. if (!vb) {
  35398. return false;
  35399. }
  35400. return vb.isUpdatable();
  35401. };
  35402. /**
  35403. * Gets a specific vertex buffer
  35404. * @param kind defines the data kind (Position, normal, etc...)
  35405. * @returns a {BABYLON.VertexBuffer}
  35406. */
  35407. Geometry.prototype.getVertexBuffer = function (kind) {
  35408. if (!this.isReady()) {
  35409. return null;
  35410. }
  35411. return this._vertexBuffers[kind];
  35412. };
  35413. /**
  35414. * Returns all vertex buffers
  35415. * @return an object holding all vertex buffers indexed by kind
  35416. */
  35417. Geometry.prototype.getVertexBuffers = function () {
  35418. if (!this.isReady()) {
  35419. return null;
  35420. }
  35421. return this._vertexBuffers;
  35422. };
  35423. /**
  35424. * Gets a boolean indicating if specific vertex buffer is present
  35425. * @param kind defines the data kind (Position, normal, etc...)
  35426. * @returns true if data is present
  35427. */
  35428. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35429. if (!this._vertexBuffers) {
  35430. if (this._delayInfo) {
  35431. return this._delayInfo.indexOf(kind) !== -1;
  35432. }
  35433. return false;
  35434. }
  35435. return this._vertexBuffers[kind] !== undefined;
  35436. };
  35437. /**
  35438. * Gets a list of all attached data kinds (Position, normal, etc...)
  35439. * @returns a list of string containing all kinds
  35440. */
  35441. Geometry.prototype.getVerticesDataKinds = function () {
  35442. var result = [];
  35443. var kind;
  35444. if (!this._vertexBuffers && this._delayInfo) {
  35445. for (kind in this._delayInfo) {
  35446. result.push(kind);
  35447. }
  35448. }
  35449. else {
  35450. for (kind in this._vertexBuffers) {
  35451. result.push(kind);
  35452. }
  35453. }
  35454. return result;
  35455. };
  35456. /**
  35457. * Update index buffer
  35458. * @param indices defines the indices to store in the index buffer
  35459. * @param offset defines the offset in the target buffer where to store the data
  35460. */
  35461. Geometry.prototype.updateIndices = function (indices, offset) {
  35462. if (!this._indexBuffer) {
  35463. return;
  35464. }
  35465. if (!this._indexBufferIsUpdatable) {
  35466. this.setIndices(indices, null, true);
  35467. }
  35468. else {
  35469. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35470. }
  35471. };
  35472. /**
  35473. * Creates a new index buffer
  35474. * @param indices defines the indices to store in the index buffer
  35475. * @param totalVertices defines the total number of vertices (could be null)
  35476. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35477. */
  35478. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35479. if (totalVertices === void 0) { totalVertices = null; }
  35480. if (updatable === void 0) { updatable = false; }
  35481. if (this._indexBuffer) {
  35482. this._engine._releaseBuffer(this._indexBuffer);
  35483. }
  35484. this._disposeVertexArrayObjects();
  35485. this._indices = indices;
  35486. this._indexBufferIsUpdatable = updatable;
  35487. if (this._meshes.length !== 0 && this._indices) {
  35488. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35489. }
  35490. if (totalVertices != undefined) {
  35491. this._totalVertices = totalVertices;
  35492. }
  35493. var meshes = this._meshes;
  35494. var numOfMeshes = meshes.length;
  35495. for (var index = 0; index < numOfMeshes; index++) {
  35496. meshes[index]._createGlobalSubMesh(true);
  35497. }
  35498. this.notifyUpdate();
  35499. };
  35500. /**
  35501. * Return the total number of indices
  35502. * @returns the total number of indices
  35503. */
  35504. Geometry.prototype.getTotalIndices = function () {
  35505. if (!this.isReady()) {
  35506. return 0;
  35507. }
  35508. return this._indices.length;
  35509. };
  35510. /**
  35511. * Gets the index buffer array
  35512. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35513. * @returns the index buffer array
  35514. */
  35515. Geometry.prototype.getIndices = function (copyWhenShared) {
  35516. if (!this.isReady()) {
  35517. return null;
  35518. }
  35519. var orig = this._indices;
  35520. if (!copyWhenShared || this._meshes.length === 1) {
  35521. return orig;
  35522. }
  35523. else {
  35524. var len = orig.length;
  35525. var copy = [];
  35526. for (var i = 0; i < len; i++) {
  35527. copy.push(orig[i]);
  35528. }
  35529. return copy;
  35530. }
  35531. };
  35532. /**
  35533. * Gets the index buffer
  35534. * @return the index buffer
  35535. */
  35536. Geometry.prototype.getIndexBuffer = function () {
  35537. if (!this.isReady()) {
  35538. return null;
  35539. }
  35540. return this._indexBuffer;
  35541. };
  35542. /** @ignore */
  35543. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35544. if (effect === void 0) { effect = null; }
  35545. if (!effect || !this._vertexArrayObjects) {
  35546. return;
  35547. }
  35548. if (this._vertexArrayObjects[effect.key]) {
  35549. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35550. delete this._vertexArrayObjects[effect.key];
  35551. }
  35552. };
  35553. /**
  35554. * Release the associated resources for a specific mesh
  35555. * @param mesh defines the source mesh
  35556. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35557. */
  35558. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35559. var meshes = this._meshes;
  35560. var index = meshes.indexOf(mesh);
  35561. if (index === -1) {
  35562. return;
  35563. }
  35564. meshes.splice(index, 1);
  35565. mesh._geometry = null;
  35566. if (meshes.length === 0 && shouldDispose) {
  35567. this.dispose();
  35568. }
  35569. };
  35570. /**
  35571. * Apply current geometry to a given mesh
  35572. * @param mesh defines the mesh to apply geometry to
  35573. */
  35574. Geometry.prototype.applyToMesh = function (mesh) {
  35575. if (mesh._geometry === this) {
  35576. return;
  35577. }
  35578. var previousGeometry = mesh._geometry;
  35579. if (previousGeometry) {
  35580. previousGeometry.releaseForMesh(mesh);
  35581. }
  35582. var meshes = this._meshes;
  35583. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35584. mesh._geometry = this;
  35585. this._scene.pushGeometry(this);
  35586. meshes.push(mesh);
  35587. if (this.isReady()) {
  35588. this._applyToMesh(mesh);
  35589. }
  35590. else {
  35591. mesh._boundingInfo = this._boundingInfo;
  35592. }
  35593. };
  35594. Geometry.prototype.updateExtend = function (data, stride) {
  35595. if (data === void 0) { data = null; }
  35596. if (!data) {
  35597. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35598. }
  35599. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35600. };
  35601. Geometry.prototype._applyToMesh = function (mesh) {
  35602. var numOfMeshes = this._meshes.length;
  35603. // vertexBuffers
  35604. for (var kind in this._vertexBuffers) {
  35605. if (numOfMeshes === 1) {
  35606. this._vertexBuffers[kind].create();
  35607. }
  35608. var buffer = this._vertexBuffers[kind].getBuffer();
  35609. if (buffer)
  35610. buffer.references = numOfMeshes;
  35611. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35612. if (!this._extend) {
  35613. this.updateExtend(this._vertexBuffers[kind].getData());
  35614. }
  35615. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35616. mesh._createGlobalSubMesh(false);
  35617. //bounding info was just created again, world matrix should be applied again.
  35618. mesh._updateBoundingInfo();
  35619. }
  35620. }
  35621. // indexBuffer
  35622. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35623. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35624. }
  35625. if (this._indexBuffer) {
  35626. this._indexBuffer.references = numOfMeshes;
  35627. }
  35628. };
  35629. Geometry.prototype.notifyUpdate = function (kind) {
  35630. if (this.onGeometryUpdated) {
  35631. this.onGeometryUpdated(this, kind);
  35632. }
  35633. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35634. var mesh = _a[_i];
  35635. mesh._markSubMeshesAsAttributesDirty();
  35636. }
  35637. };
  35638. /**
  35639. * Load the geometry if it was flagged as delay loaded
  35640. * @param scene defines the hosting scene
  35641. * @param onLoaded defines a callback called when the geometry is loaded
  35642. */
  35643. Geometry.prototype.load = function (scene, onLoaded) {
  35644. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35645. return;
  35646. }
  35647. if (this.isReady()) {
  35648. if (onLoaded) {
  35649. onLoaded();
  35650. }
  35651. return;
  35652. }
  35653. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35654. this._queueLoad(scene, onLoaded);
  35655. };
  35656. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35657. var _this = this;
  35658. if (!this.delayLoadingFile) {
  35659. return;
  35660. }
  35661. scene._addPendingData(this);
  35662. scene._loadFile(this.delayLoadingFile, function (data) {
  35663. if (!_this._delayLoadingFunction) {
  35664. return;
  35665. }
  35666. _this._delayLoadingFunction(JSON.parse(data), _this);
  35667. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35668. _this._delayInfo = [];
  35669. scene._removePendingData(_this);
  35670. var meshes = _this._meshes;
  35671. var numOfMeshes = meshes.length;
  35672. for (var index = 0; index < numOfMeshes; index++) {
  35673. _this._applyToMesh(meshes[index]);
  35674. }
  35675. if (onLoaded) {
  35676. onLoaded();
  35677. }
  35678. }, undefined, true);
  35679. };
  35680. /**
  35681. * Invert the geometry to move from a right handed system to a left handed one.
  35682. */
  35683. Geometry.prototype.toLeftHanded = function () {
  35684. // Flip faces
  35685. var tIndices = this.getIndices(false);
  35686. if (tIndices != null && tIndices.length > 0) {
  35687. for (var i = 0; i < tIndices.length; i += 3) {
  35688. var tTemp = tIndices[i + 0];
  35689. tIndices[i + 0] = tIndices[i + 2];
  35690. tIndices[i + 2] = tTemp;
  35691. }
  35692. this.setIndices(tIndices);
  35693. }
  35694. // Negate position.z
  35695. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35696. if (tPositions != null && tPositions.length > 0) {
  35697. for (var i = 0; i < tPositions.length; i += 3) {
  35698. tPositions[i + 2] = -tPositions[i + 2];
  35699. }
  35700. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35701. }
  35702. // Negate normal.z
  35703. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35704. if (tNormals != null && tNormals.length > 0) {
  35705. for (var i = 0; i < tNormals.length; i += 3) {
  35706. tNormals[i + 2] = -tNormals[i + 2];
  35707. }
  35708. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35709. }
  35710. };
  35711. // Cache
  35712. /** @ignore */
  35713. Geometry.prototype._resetPointsArrayCache = function () {
  35714. this._positions = null;
  35715. };
  35716. /** @ignore */
  35717. Geometry.prototype._generatePointsArray = function () {
  35718. if (this._positions)
  35719. return true;
  35720. this._positions = [];
  35721. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35722. if (!data) {
  35723. return false;
  35724. }
  35725. for (var index = 0; index < data.length; index += 3) {
  35726. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35727. }
  35728. return true;
  35729. };
  35730. /**
  35731. * Gets a value indicating if the geometry is disposed
  35732. * @returns true if the geometry was disposed
  35733. */
  35734. Geometry.prototype.isDisposed = function () {
  35735. return this._isDisposed;
  35736. };
  35737. Geometry.prototype._disposeVertexArrayObjects = function () {
  35738. if (this._vertexArrayObjects) {
  35739. for (var kind in this._vertexArrayObjects) {
  35740. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35741. }
  35742. this._vertexArrayObjects = {};
  35743. }
  35744. };
  35745. /**
  35746. * Free all associated resources
  35747. */
  35748. Geometry.prototype.dispose = function () {
  35749. var meshes = this._meshes;
  35750. var numOfMeshes = meshes.length;
  35751. var index;
  35752. for (index = 0; index < numOfMeshes; index++) {
  35753. this.releaseForMesh(meshes[index]);
  35754. }
  35755. this._meshes = [];
  35756. this._disposeVertexArrayObjects();
  35757. for (var kind in this._vertexBuffers) {
  35758. this._vertexBuffers[kind].dispose();
  35759. }
  35760. this._vertexBuffers = {};
  35761. this._totalVertices = 0;
  35762. if (this._indexBuffer) {
  35763. this._engine._releaseBuffer(this._indexBuffer);
  35764. }
  35765. this._indexBuffer = null;
  35766. this._indices = [];
  35767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35768. this.delayLoadingFile = null;
  35769. this._delayLoadingFunction = null;
  35770. this._delayInfo = [];
  35771. this._boundingInfo = null;
  35772. this._scene.removeGeometry(this);
  35773. this._isDisposed = true;
  35774. };
  35775. /**
  35776. * Clone the current geometry into a new geometry
  35777. * @param id defines the unique ID of the new geometry
  35778. * @returns a new geometry object
  35779. */
  35780. Geometry.prototype.copy = function (id) {
  35781. var vertexData = new BABYLON.VertexData();
  35782. vertexData.indices = [];
  35783. var indices = this.getIndices();
  35784. if (indices) {
  35785. for (var index = 0; index < indices.length; index++) {
  35786. vertexData.indices.push(indices[index]);
  35787. }
  35788. }
  35789. var updatable = false;
  35790. var stopChecking = false;
  35791. var kind;
  35792. for (kind in this._vertexBuffers) {
  35793. // using slice() to make a copy of the array and not just reference it
  35794. var data = this.getVerticesData(kind);
  35795. if (data instanceof Float32Array) {
  35796. vertexData.set(new Float32Array(data), kind);
  35797. }
  35798. else {
  35799. vertexData.set(data.slice(0), kind);
  35800. }
  35801. if (!stopChecking) {
  35802. var vb = this.getVertexBuffer(kind);
  35803. if (vb) {
  35804. updatable = vb.isUpdatable();
  35805. stopChecking = !updatable;
  35806. }
  35807. }
  35808. }
  35809. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35810. geometry.delayLoadState = this.delayLoadState;
  35811. geometry.delayLoadingFile = this.delayLoadingFile;
  35812. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35813. for (kind in this._delayInfo) {
  35814. geometry._delayInfo = geometry._delayInfo || [];
  35815. geometry._delayInfo.push(kind);
  35816. }
  35817. // Bounding info
  35818. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35819. return geometry;
  35820. };
  35821. /**
  35822. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35823. * @return a JSON representation of the current geometry data (without the vertices data)
  35824. */
  35825. Geometry.prototype.serialize = function () {
  35826. var serializationObject = {};
  35827. serializationObject.id = this.id;
  35828. serializationObject.updatable = this._updatable;
  35829. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35830. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35831. }
  35832. return serializationObject;
  35833. };
  35834. Geometry.prototype.toNumberArray = function (origin) {
  35835. if (Array.isArray(origin)) {
  35836. return origin;
  35837. }
  35838. else {
  35839. return Array.prototype.slice.call(origin);
  35840. }
  35841. };
  35842. /**
  35843. * Serialize all vertices data into a JSON oject
  35844. * @returns a JSON representation of the current geometry data
  35845. */
  35846. Geometry.prototype.serializeVerticeData = function () {
  35847. var serializationObject = this.serialize();
  35848. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35849. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35850. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35851. serializationObject.positions._updatable = true;
  35852. }
  35853. }
  35854. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35855. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35856. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35857. serializationObject.normals._updatable = true;
  35858. }
  35859. }
  35860. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35861. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35862. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35863. serializationObject.tangets._updatable = true;
  35864. }
  35865. }
  35866. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35867. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35868. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35869. serializationObject.uvs._updatable = true;
  35870. }
  35871. }
  35872. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35873. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35874. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35875. serializationObject.uv2s._updatable = true;
  35876. }
  35877. }
  35878. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35879. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35880. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35881. serializationObject.uv3s._updatable = true;
  35882. }
  35883. }
  35884. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35885. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35886. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35887. serializationObject.uv4s._updatable = true;
  35888. }
  35889. }
  35890. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35891. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35892. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35893. serializationObject.uv5s._updatable = true;
  35894. }
  35895. }
  35896. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35897. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35898. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35899. serializationObject.uv6s._updatable = true;
  35900. }
  35901. }
  35902. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35903. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35904. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35905. serializationObject.colors._updatable = true;
  35906. }
  35907. }
  35908. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35909. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35910. serializationObject.matricesIndices._isExpanded = true;
  35911. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35912. serializationObject.matricesIndices._updatable = true;
  35913. }
  35914. }
  35915. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35916. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35917. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35918. serializationObject.matricesWeights._updatable = true;
  35919. }
  35920. }
  35921. serializationObject.indices = this.toNumberArray(this.getIndices());
  35922. return serializationObject;
  35923. };
  35924. // Statics
  35925. /**
  35926. * Extracts a clone of a mesh geometry
  35927. * @param mesh defines the source mesh
  35928. * @param id defines the unique ID of the new geometry object
  35929. * @returns the new geometry object
  35930. */
  35931. Geometry.ExtractFromMesh = function (mesh, id) {
  35932. var geometry = mesh._geometry;
  35933. if (!geometry) {
  35934. return null;
  35935. }
  35936. return geometry.copy(id);
  35937. };
  35938. /**
  35939. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35940. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35941. * Be aware Math.random() could cause collisions, but:
  35942. * "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"
  35943. * @returns a string containing a new GUID
  35944. */
  35945. Geometry.RandomId = function () {
  35946. return BABYLON.Tools.RandomId();
  35947. };
  35948. /** @ignore */
  35949. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35950. var scene = mesh.getScene();
  35951. // Geometry
  35952. var geometryId = parsedGeometry.geometryId;
  35953. if (geometryId) {
  35954. var geometry = scene.getGeometryByID(geometryId);
  35955. if (geometry) {
  35956. geometry.applyToMesh(mesh);
  35957. }
  35958. }
  35959. else if (parsedGeometry instanceof ArrayBuffer) {
  35960. var binaryInfo = mesh._binaryInfo;
  35961. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35962. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35963. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35964. }
  35965. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35966. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35967. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35968. }
  35969. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35970. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35971. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35972. }
  35973. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35974. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35975. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35976. }
  35977. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35978. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35979. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35980. }
  35981. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35982. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35983. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35984. }
  35985. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35986. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35987. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35988. }
  35989. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35990. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35991. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35992. }
  35993. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35994. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35995. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35996. }
  35997. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35998. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35999. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36000. }
  36001. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36002. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36003. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36004. }
  36005. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36006. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36007. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36008. }
  36009. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36010. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36011. mesh.setIndices(indicesData, null);
  36012. }
  36013. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36014. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36015. mesh.subMeshes = [];
  36016. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36017. var materialIndex = subMeshesData[(i * 5) + 0];
  36018. var verticesStart = subMeshesData[(i * 5) + 1];
  36019. var verticesCount = subMeshesData[(i * 5) + 2];
  36020. var indexStart = subMeshesData[(i * 5) + 3];
  36021. var indexCount = subMeshesData[(i * 5) + 4];
  36022. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36023. }
  36024. }
  36025. }
  36026. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36027. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36028. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36029. if (parsedGeometry.tangents) {
  36030. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36031. }
  36032. if (parsedGeometry.uvs) {
  36033. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36034. }
  36035. if (parsedGeometry.uvs2) {
  36036. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36037. }
  36038. if (parsedGeometry.uvs3) {
  36039. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36040. }
  36041. if (parsedGeometry.uvs4) {
  36042. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36043. }
  36044. if (parsedGeometry.uvs5) {
  36045. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36046. }
  36047. if (parsedGeometry.uvs6) {
  36048. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36049. }
  36050. if (parsedGeometry.colors) {
  36051. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36052. }
  36053. if (parsedGeometry.matricesIndices) {
  36054. if (!parsedGeometry.matricesIndices._isExpanded) {
  36055. var floatIndices = [];
  36056. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36057. var matricesIndex = parsedGeometry.matricesIndices[i];
  36058. floatIndices.push(matricesIndex & 0x000000FF);
  36059. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36060. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36061. floatIndices.push(matricesIndex >> 24);
  36062. }
  36063. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36064. }
  36065. else {
  36066. delete parsedGeometry.matricesIndices._isExpanded;
  36067. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36068. }
  36069. }
  36070. if (parsedGeometry.matricesIndicesExtra) {
  36071. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36072. var floatIndices = [];
  36073. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36074. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36075. floatIndices.push(matricesIndex & 0x000000FF);
  36076. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36077. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36078. floatIndices.push(matricesIndex >> 24);
  36079. }
  36080. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36081. }
  36082. else {
  36083. delete parsedGeometry.matricesIndices._isExpanded;
  36084. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36085. }
  36086. }
  36087. if (parsedGeometry.matricesWeights) {
  36088. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36089. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36090. }
  36091. if (parsedGeometry.matricesWeightsExtra) {
  36092. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36093. }
  36094. mesh.setIndices(parsedGeometry.indices, null);
  36095. }
  36096. // SubMeshes
  36097. if (parsedGeometry.subMeshes) {
  36098. mesh.subMeshes = [];
  36099. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36100. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36101. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36102. }
  36103. }
  36104. // Flat shading
  36105. if (mesh._shouldGenerateFlatShading) {
  36106. mesh.convertToFlatShadedMesh();
  36107. delete mesh._shouldGenerateFlatShading;
  36108. }
  36109. // Update
  36110. mesh.computeWorldMatrix(true);
  36111. // Octree
  36112. var sceneOctree = scene.selectionOctree;
  36113. if (sceneOctree !== undefined && sceneOctree !== null) {
  36114. sceneOctree.addMesh(mesh);
  36115. }
  36116. };
  36117. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36118. var epsilon = 1e-3;
  36119. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36120. return;
  36121. }
  36122. var noInfluenceBoneIndex = 0.0;
  36123. if (parsedGeometry.skeletonId > -1) {
  36124. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36125. if (!skeleton) {
  36126. return;
  36127. }
  36128. noInfluenceBoneIndex = skeleton.bones.length;
  36129. }
  36130. else {
  36131. return;
  36132. }
  36133. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36134. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36135. var matricesWeights = parsedGeometry.matricesWeights;
  36136. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36137. var influencers = parsedGeometry.numBoneInfluencer;
  36138. var size = matricesWeights.length;
  36139. for (var i = 0; i < size; i += 4) {
  36140. var weight = 0.0;
  36141. var firstZeroWeight = -1;
  36142. for (var j = 0; j < 4; j++) {
  36143. var w = matricesWeights[i + j];
  36144. weight += w;
  36145. if (w < epsilon && firstZeroWeight < 0) {
  36146. firstZeroWeight = j;
  36147. }
  36148. }
  36149. if (matricesWeightsExtra) {
  36150. for (var j = 0; j < 4; j++) {
  36151. var w = matricesWeightsExtra[i + j];
  36152. weight += w;
  36153. if (w < epsilon && firstZeroWeight < 0) {
  36154. firstZeroWeight = j + 4;
  36155. }
  36156. }
  36157. }
  36158. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36159. firstZeroWeight = influencers - 1;
  36160. }
  36161. if (weight > epsilon) {
  36162. var mweight = 1.0 / weight;
  36163. for (var j = 0; j < 4; j++) {
  36164. matricesWeights[i + j] *= mweight;
  36165. }
  36166. if (matricesWeightsExtra) {
  36167. for (var j = 0; j < 4; j++) {
  36168. matricesWeightsExtra[i + j] *= mweight;
  36169. }
  36170. }
  36171. }
  36172. else {
  36173. if (firstZeroWeight >= 4) {
  36174. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36175. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36176. }
  36177. else {
  36178. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36179. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36180. }
  36181. }
  36182. }
  36183. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36184. if (parsedGeometry.matricesWeightsExtra) {
  36185. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36186. }
  36187. };
  36188. /**
  36189. * Create a new geometry from persisted data (Using .babylon file format)
  36190. * @param parsedVertexData defines the persisted data
  36191. * @param scene defines the hosting scene
  36192. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36193. * @returns the new geometry object
  36194. */
  36195. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36196. if (scene.getGeometryByID(parsedVertexData.id)) {
  36197. return null; // null since geometry could be something else than a box...
  36198. }
  36199. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36200. if (BABYLON.Tags) {
  36201. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36202. }
  36203. if (parsedVertexData.delayLoadingFile) {
  36204. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36205. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36206. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36207. geometry._delayInfo = [];
  36208. if (parsedVertexData.hasUVs) {
  36209. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36210. }
  36211. if (parsedVertexData.hasUVs2) {
  36212. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36213. }
  36214. if (parsedVertexData.hasUVs3) {
  36215. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36216. }
  36217. if (parsedVertexData.hasUVs4) {
  36218. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36219. }
  36220. if (parsedVertexData.hasUVs5) {
  36221. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36222. }
  36223. if (parsedVertexData.hasUVs6) {
  36224. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36225. }
  36226. if (parsedVertexData.hasColors) {
  36227. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36228. }
  36229. if (parsedVertexData.hasMatricesIndices) {
  36230. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36231. }
  36232. if (parsedVertexData.hasMatricesWeights) {
  36233. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36234. }
  36235. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36236. }
  36237. else {
  36238. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36239. }
  36240. scene.pushGeometry(geometry, true);
  36241. return geometry;
  36242. };
  36243. return Geometry;
  36244. }());
  36245. BABYLON.Geometry = Geometry;
  36246. // Primitives
  36247. /// Abstract class
  36248. /**
  36249. * Abstract class used to provide common services for all typed geometries
  36250. */
  36251. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36252. __extends(_PrimitiveGeometry, _super);
  36253. /**
  36254. * Creates a new typed geometry
  36255. * @param id defines the unique ID of the geometry
  36256. * @param scene defines the hosting scene
  36257. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36258. * @param mesh defines the hosting mesh (can be null)
  36259. */
  36260. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36261. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36262. if (mesh === void 0) { mesh = null; }
  36263. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36264. _this._canBeRegenerated = _canBeRegenerated;
  36265. _this._beingRegenerated = true;
  36266. _this.regenerate();
  36267. _this._beingRegenerated = false;
  36268. return _this;
  36269. }
  36270. /**
  36271. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36272. * @returns true if the geometry can be regenerated
  36273. */
  36274. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36275. return this._canBeRegenerated;
  36276. };
  36277. /**
  36278. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36279. */
  36280. _PrimitiveGeometry.prototype.regenerate = function () {
  36281. if (!this._canBeRegenerated) {
  36282. return;
  36283. }
  36284. this._beingRegenerated = true;
  36285. this.setAllVerticesData(this._regenerateVertexData(), false);
  36286. this._beingRegenerated = false;
  36287. };
  36288. /**
  36289. * Clone the geometry
  36290. * @param id defines the unique ID of the new geometry
  36291. * @returns the new geometry
  36292. */
  36293. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36294. return _super.prototype.copy.call(this, id);
  36295. };
  36296. // overrides
  36297. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36298. if (!this._beingRegenerated) {
  36299. return;
  36300. }
  36301. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36302. };
  36303. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36304. if (!this._beingRegenerated) {
  36305. return;
  36306. }
  36307. _super.prototype.setVerticesData.call(this, kind, data, false);
  36308. };
  36309. // to override
  36310. /** @ignore */
  36311. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36312. throw new Error("Abstract method");
  36313. };
  36314. _PrimitiveGeometry.prototype.copy = function (id) {
  36315. throw new Error("Must be overriden in sub-classes.");
  36316. };
  36317. _PrimitiveGeometry.prototype.serialize = function () {
  36318. var serializationObject = _super.prototype.serialize.call(this);
  36319. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36320. return serializationObject;
  36321. };
  36322. return _PrimitiveGeometry;
  36323. }(Geometry));
  36324. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36325. /**
  36326. * Creates a ribbon geometry
  36327. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36328. */
  36329. var RibbonGeometry = /** @class */ (function (_super) {
  36330. __extends(RibbonGeometry, _super);
  36331. /**
  36332. * Creates a ribbon geometry
  36333. * @param id defines the unique ID of the geometry
  36334. * @param scene defines the hosting scene
  36335. * @param pathArray defines the array of paths to use
  36336. * @param closeArray defines if the last path and the first path must be joined
  36337. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36338. * @param offset defines the offset between points
  36339. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36340. * @param mesh defines the hosting mesh (can be null)
  36341. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36342. */
  36343. function RibbonGeometry(id, scene,
  36344. /**
  36345. * Defines the array of paths to use
  36346. */
  36347. pathArray,
  36348. /**
  36349. * Defines if the last and first points of each path in your pathArray must be joined
  36350. */
  36351. closeArray,
  36352. /**
  36353. * Defines if the last and first points of each path in your pathArray must be joined
  36354. */
  36355. closePath,
  36356. /**
  36357. * Defines the offset between points
  36358. */
  36359. offset, canBeRegenerated, mesh,
  36360. /**
  36361. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36362. */
  36363. side) {
  36364. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36365. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36366. _this.pathArray = pathArray;
  36367. _this.closeArray = closeArray;
  36368. _this.closePath = closePath;
  36369. _this.offset = offset;
  36370. _this.side = side;
  36371. return _this;
  36372. }
  36373. /** @ignore */
  36374. RibbonGeometry.prototype._regenerateVertexData = function () {
  36375. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36376. };
  36377. RibbonGeometry.prototype.copy = function (id) {
  36378. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36379. };
  36380. return RibbonGeometry;
  36381. }(_PrimitiveGeometry));
  36382. BABYLON.RibbonGeometry = RibbonGeometry;
  36383. /**
  36384. * Creates a box geometry
  36385. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36386. */
  36387. var BoxGeometry = /** @class */ (function (_super) {
  36388. __extends(BoxGeometry, _super);
  36389. /**
  36390. * Creates a box geometry
  36391. * @param id defines the unique ID of the geometry
  36392. * @param scene defines the hosting scene
  36393. * @param size defines the zise of the box (width, height and depth are the same)
  36394. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36395. * @param mesh defines the hosting mesh (can be null)
  36396. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36397. */
  36398. function BoxGeometry(id, scene,
  36399. /**
  36400. * Defines the zise of the box (width, height and depth are the same)
  36401. */
  36402. size, canBeRegenerated, mesh,
  36403. /**
  36404. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36405. */
  36406. side) {
  36407. if (mesh === void 0) { mesh = null; }
  36408. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36409. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36410. _this.size = size;
  36411. _this.side = side;
  36412. return _this;
  36413. }
  36414. BoxGeometry.prototype._regenerateVertexData = function () {
  36415. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36416. };
  36417. BoxGeometry.prototype.copy = function (id) {
  36418. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36419. };
  36420. BoxGeometry.prototype.serialize = function () {
  36421. var serializationObject = _super.prototype.serialize.call(this);
  36422. serializationObject.size = this.size;
  36423. return serializationObject;
  36424. };
  36425. BoxGeometry.Parse = function (parsedBox, scene) {
  36426. if (scene.getGeometryByID(parsedBox.id)) {
  36427. return null; // null since geometry could be something else than a box...
  36428. }
  36429. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36430. if (BABYLON.Tags) {
  36431. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36432. }
  36433. scene.pushGeometry(box, true);
  36434. return box;
  36435. };
  36436. return BoxGeometry;
  36437. }(_PrimitiveGeometry));
  36438. BABYLON.BoxGeometry = BoxGeometry;
  36439. /**
  36440. * Creates a sphere geometry
  36441. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36442. */
  36443. var SphereGeometry = /** @class */ (function (_super) {
  36444. __extends(SphereGeometry, _super);
  36445. /**
  36446. * Create a new sphere geometry
  36447. * @param id defines the unique ID of the geometry
  36448. * @param scene defines the hosting scene
  36449. * @param segments defines the number of segments to use to create the sphere
  36450. * @param diameter defines the diameter of the sphere
  36451. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36452. * @param mesh defines the hosting mesh (can be null)
  36453. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36454. */
  36455. function SphereGeometry(id, scene,
  36456. /**
  36457. * Defines the number of segments to use to create the sphere
  36458. */
  36459. segments,
  36460. /**
  36461. * Defines the diameter of the sphere
  36462. */
  36463. diameter, canBeRegenerated, mesh,
  36464. /**
  36465. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36466. */
  36467. side) {
  36468. if (mesh === void 0) { mesh = null; }
  36469. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36470. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36471. _this.segments = segments;
  36472. _this.diameter = diameter;
  36473. _this.side = side;
  36474. return _this;
  36475. }
  36476. SphereGeometry.prototype._regenerateVertexData = function () {
  36477. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36478. };
  36479. SphereGeometry.prototype.copy = function (id) {
  36480. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36481. };
  36482. SphereGeometry.prototype.serialize = function () {
  36483. var serializationObject = _super.prototype.serialize.call(this);
  36484. serializationObject.segments = this.segments;
  36485. serializationObject.diameter = this.diameter;
  36486. return serializationObject;
  36487. };
  36488. SphereGeometry.Parse = function (parsedSphere, scene) {
  36489. if (scene.getGeometryByID(parsedSphere.id)) {
  36490. return null; // null since geometry could be something else than a sphere...
  36491. }
  36492. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36493. if (BABYLON.Tags) {
  36494. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36495. }
  36496. scene.pushGeometry(sphere, true);
  36497. return sphere;
  36498. };
  36499. return SphereGeometry;
  36500. }(_PrimitiveGeometry));
  36501. BABYLON.SphereGeometry = SphereGeometry;
  36502. /**
  36503. * Creates a disc geometry
  36504. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36505. */
  36506. var DiscGeometry = /** @class */ (function (_super) {
  36507. __extends(DiscGeometry, _super);
  36508. /**
  36509. * Creates a new disc geometry
  36510. * @param id defines the unique ID of the geometry
  36511. * @param scene defines the hosting scene
  36512. * @param radius defines the radius of the disc
  36513. * @param tessellation defines the tesselation factor to apply to the disc
  36514. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36515. * @param mesh defines the hosting mesh (can be null)
  36516. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36517. */
  36518. function DiscGeometry(id, scene,
  36519. /**
  36520. * Defines the radius of the disc
  36521. */
  36522. radius,
  36523. /**
  36524. * Defines the tesselation factor to apply to the disc
  36525. */
  36526. tessellation, canBeRegenerated, mesh,
  36527. /**
  36528. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36529. */
  36530. side) {
  36531. if (mesh === void 0) { mesh = null; }
  36532. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36533. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36534. _this.radius = radius;
  36535. _this.tessellation = tessellation;
  36536. _this.side = side;
  36537. return _this;
  36538. }
  36539. DiscGeometry.prototype._regenerateVertexData = function () {
  36540. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36541. };
  36542. DiscGeometry.prototype.copy = function (id) {
  36543. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36544. };
  36545. return DiscGeometry;
  36546. }(_PrimitiveGeometry));
  36547. BABYLON.DiscGeometry = DiscGeometry;
  36548. /**
  36549. * Creates a new cylinder geometry
  36550. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36551. */
  36552. var CylinderGeometry = /** @class */ (function (_super) {
  36553. __extends(CylinderGeometry, _super);
  36554. /**
  36555. * Creates a new cylinder geometry
  36556. * @param id defines the unique ID of the geometry
  36557. * @param scene defines the hosting scene
  36558. * @param height defines the height of the cylinder
  36559. * @param diameterTop defines the diameter of the cylinder's top cap
  36560. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36561. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36562. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36563. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36564. * @param mesh defines the hosting mesh (can be null)
  36565. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36566. */
  36567. function CylinderGeometry(id, scene,
  36568. /**
  36569. * Defines the height of the cylinder
  36570. */
  36571. height,
  36572. /**
  36573. * Defines the diameter of the cylinder's top cap
  36574. */
  36575. diameterTop,
  36576. /**
  36577. * Defines the diameter of the cylinder's bottom cap
  36578. */
  36579. diameterBottom,
  36580. /**
  36581. * Defines the tessellation factor to apply to the cylinder
  36582. */
  36583. tessellation,
  36584. /**
  36585. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36586. */
  36587. subdivisions, canBeRegenerated, mesh,
  36588. /**
  36589. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36590. */
  36591. side) {
  36592. if (subdivisions === void 0) { subdivisions = 1; }
  36593. if (mesh === void 0) { mesh = null; }
  36594. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36595. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36596. _this.height = height;
  36597. _this.diameterTop = diameterTop;
  36598. _this.diameterBottom = diameterBottom;
  36599. _this.tessellation = tessellation;
  36600. _this.subdivisions = subdivisions;
  36601. _this.side = side;
  36602. return _this;
  36603. }
  36604. CylinderGeometry.prototype._regenerateVertexData = function () {
  36605. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36606. };
  36607. CylinderGeometry.prototype.copy = function (id) {
  36608. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36609. };
  36610. CylinderGeometry.prototype.serialize = function () {
  36611. var serializationObject = _super.prototype.serialize.call(this);
  36612. serializationObject.height = this.height;
  36613. serializationObject.diameterTop = this.diameterTop;
  36614. serializationObject.diameterBottom = this.diameterBottom;
  36615. serializationObject.tessellation = this.tessellation;
  36616. return serializationObject;
  36617. };
  36618. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36619. if (scene.getGeometryByID(parsedCylinder.id)) {
  36620. return null; // null since geometry could be something else than a cylinder...
  36621. }
  36622. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36623. if (BABYLON.Tags) {
  36624. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36625. }
  36626. scene.pushGeometry(cylinder, true);
  36627. return cylinder;
  36628. };
  36629. return CylinderGeometry;
  36630. }(_PrimitiveGeometry));
  36631. BABYLON.CylinderGeometry = CylinderGeometry;
  36632. /**
  36633. * Creates a new torus geometry
  36634. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36635. */
  36636. var TorusGeometry = /** @class */ (function (_super) {
  36637. __extends(TorusGeometry, _super);
  36638. /**
  36639. * Creates a new torus geometry
  36640. * @param id defines the unique ID of the geometry
  36641. * @param scene defines the hosting scene
  36642. * @param diameter defines the diameter of the torus
  36643. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36644. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36645. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36646. * @param mesh defines the hosting mesh (can be null)
  36647. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36648. */
  36649. function TorusGeometry(id, scene,
  36650. /**
  36651. * Defines the diameter of the torus
  36652. */
  36653. diameter,
  36654. /**
  36655. * Defines the thickness of the torus (ie. internal diameter)
  36656. */
  36657. thickness,
  36658. /**
  36659. * Defines the tesselation factor to apply to the torus
  36660. */
  36661. tessellation, canBeRegenerated, mesh,
  36662. /**
  36663. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36664. */
  36665. side) {
  36666. if (mesh === void 0) { mesh = null; }
  36667. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36668. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36669. _this.diameter = diameter;
  36670. _this.thickness = thickness;
  36671. _this.tessellation = tessellation;
  36672. _this.side = side;
  36673. return _this;
  36674. }
  36675. TorusGeometry.prototype._regenerateVertexData = function () {
  36676. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36677. };
  36678. TorusGeometry.prototype.copy = function (id) {
  36679. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36680. };
  36681. TorusGeometry.prototype.serialize = function () {
  36682. var serializationObject = _super.prototype.serialize.call(this);
  36683. serializationObject.diameter = this.diameter;
  36684. serializationObject.thickness = this.thickness;
  36685. serializationObject.tessellation = this.tessellation;
  36686. return serializationObject;
  36687. };
  36688. TorusGeometry.Parse = function (parsedTorus, scene) {
  36689. if (scene.getGeometryByID(parsedTorus.id)) {
  36690. return null; // null since geometry could be something else than a torus...
  36691. }
  36692. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36693. if (BABYLON.Tags) {
  36694. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36695. }
  36696. scene.pushGeometry(torus, true);
  36697. return torus;
  36698. };
  36699. return TorusGeometry;
  36700. }(_PrimitiveGeometry));
  36701. BABYLON.TorusGeometry = TorusGeometry;
  36702. /**
  36703. * Creates a new ground geometry
  36704. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36705. */
  36706. var GroundGeometry = /** @class */ (function (_super) {
  36707. __extends(GroundGeometry, _super);
  36708. /**
  36709. * Creates a new ground geometry
  36710. * @param id defines the unique ID of the geometry
  36711. * @param scene defines the hosting scene
  36712. * @param width defines the width of the ground
  36713. * @param height defines the height of the ground
  36714. * @param subdivisions defines the subdivisions to apply to the ground
  36715. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36716. * @param mesh defines the hosting mesh (can be null)
  36717. */
  36718. function GroundGeometry(id, scene,
  36719. /**
  36720. * Defines the width of the ground
  36721. */
  36722. width,
  36723. /**
  36724. * Defines the height of the ground
  36725. */
  36726. height,
  36727. /**
  36728. * Defines the subdivisions to apply to the ground
  36729. */
  36730. subdivisions, canBeRegenerated, mesh) {
  36731. if (mesh === void 0) { mesh = null; }
  36732. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36733. _this.width = width;
  36734. _this.height = height;
  36735. _this.subdivisions = subdivisions;
  36736. return _this;
  36737. }
  36738. GroundGeometry.prototype._regenerateVertexData = function () {
  36739. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36740. };
  36741. GroundGeometry.prototype.copy = function (id) {
  36742. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36743. };
  36744. GroundGeometry.prototype.serialize = function () {
  36745. var serializationObject = _super.prototype.serialize.call(this);
  36746. serializationObject.width = this.width;
  36747. serializationObject.height = this.height;
  36748. serializationObject.subdivisions = this.subdivisions;
  36749. return serializationObject;
  36750. };
  36751. GroundGeometry.Parse = function (parsedGround, scene) {
  36752. if (scene.getGeometryByID(parsedGround.id)) {
  36753. return null; // null since geometry could be something else than a ground...
  36754. }
  36755. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36756. if (BABYLON.Tags) {
  36757. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36758. }
  36759. scene.pushGeometry(ground, true);
  36760. return ground;
  36761. };
  36762. return GroundGeometry;
  36763. }(_PrimitiveGeometry));
  36764. BABYLON.GroundGeometry = GroundGeometry;
  36765. /**
  36766. * Creates a tiled ground geometry
  36767. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36768. */
  36769. var TiledGroundGeometry = /** @class */ (function (_super) {
  36770. __extends(TiledGroundGeometry, _super);
  36771. /**
  36772. * Creates a tiled ground geometry
  36773. * @param id defines the unique ID of the geometry
  36774. * @param scene defines the hosting scene
  36775. * @param xmin defines the minimum value on X axis
  36776. * @param zmin defines the minimum value on Z axis
  36777. * @param xmax defines the maximum value on X axis
  36778. * @param zmax defines the maximum value on Z axis
  36779. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36780. * @param precision defines the precision to use when computing the tiles
  36781. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36782. * @param mesh defines the hosting mesh (can be null)
  36783. */
  36784. function TiledGroundGeometry(id, scene,
  36785. /**
  36786. * Defines the minimum value on X axis
  36787. */
  36788. xmin,
  36789. /**
  36790. * Defines the minimum value on Z axis
  36791. */
  36792. zmin,
  36793. /**
  36794. * Defines the maximum value on X axis
  36795. */
  36796. xmax,
  36797. /**
  36798. * Defines the maximum value on Z axis
  36799. */
  36800. zmax,
  36801. /**
  36802. * Defines the subdivisions to apply to the ground
  36803. */
  36804. subdivisions,
  36805. /**
  36806. * Defines the precision to use when computing the tiles
  36807. */
  36808. precision, canBeRegenerated, mesh) {
  36809. if (mesh === void 0) { mesh = null; }
  36810. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36811. _this.xmin = xmin;
  36812. _this.zmin = zmin;
  36813. _this.xmax = xmax;
  36814. _this.zmax = zmax;
  36815. _this.subdivisions = subdivisions;
  36816. _this.precision = precision;
  36817. return _this;
  36818. }
  36819. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36820. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36821. };
  36822. TiledGroundGeometry.prototype.copy = function (id) {
  36823. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36824. };
  36825. return TiledGroundGeometry;
  36826. }(_PrimitiveGeometry));
  36827. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36828. /**
  36829. * Creates a plane geometry
  36830. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36831. */
  36832. var PlaneGeometry = /** @class */ (function (_super) {
  36833. __extends(PlaneGeometry, _super);
  36834. /**
  36835. * Creates a plane geometry
  36836. * @param id defines the unique ID of the geometry
  36837. * @param scene defines the hosting scene
  36838. * @param size defines the size of the plane (width === height)
  36839. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36840. * @param mesh defines the hosting mesh (can be null)
  36841. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36842. */
  36843. function PlaneGeometry(id, scene,
  36844. /**
  36845. * Defines the size of the plane (width === height)
  36846. */
  36847. size, canBeRegenerated, mesh,
  36848. /**
  36849. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36850. */
  36851. side) {
  36852. if (mesh === void 0) { mesh = null; }
  36853. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36854. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36855. _this.size = size;
  36856. _this.side = side;
  36857. return _this;
  36858. }
  36859. PlaneGeometry.prototype._regenerateVertexData = function () {
  36860. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36861. };
  36862. PlaneGeometry.prototype.copy = function (id) {
  36863. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36864. };
  36865. PlaneGeometry.prototype.serialize = function () {
  36866. var serializationObject = _super.prototype.serialize.call(this);
  36867. serializationObject.size = this.size;
  36868. return serializationObject;
  36869. };
  36870. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36871. if (scene.getGeometryByID(parsedPlane.id)) {
  36872. return null; // null since geometry could be something else than a ground...
  36873. }
  36874. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36875. if (BABYLON.Tags) {
  36876. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36877. }
  36878. scene.pushGeometry(plane, true);
  36879. return plane;
  36880. };
  36881. return PlaneGeometry;
  36882. }(_PrimitiveGeometry));
  36883. BABYLON.PlaneGeometry = PlaneGeometry;
  36884. /**
  36885. * Creates a torus knot geometry
  36886. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36887. */
  36888. var TorusKnotGeometry = /** @class */ (function (_super) {
  36889. __extends(TorusKnotGeometry, _super);
  36890. /**
  36891. * Creates a torus knot geometry
  36892. * @param id defines the unique ID of the geometry
  36893. * @param scene defines the hosting scene
  36894. * @param radius defines the radius of the torus knot
  36895. * @param tube defines the thickness of the torus knot tube
  36896. * @param radialSegments defines the number of radial segments
  36897. * @param tubularSegments defines the number of tubular segments
  36898. * @param p defines the first number of windings
  36899. * @param q defines the second number of windings
  36900. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36901. * @param mesh defines the hosting mesh (can be null)
  36902. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36903. */
  36904. function TorusKnotGeometry(id, scene,
  36905. /**
  36906. * Defines the radius of the torus knot
  36907. */
  36908. radius,
  36909. /**
  36910. * Defines the thickness of the torus knot tube
  36911. */
  36912. tube,
  36913. /**
  36914. * Defines the number of radial segments
  36915. */
  36916. radialSegments,
  36917. /**
  36918. * Defines the number of tubular segments
  36919. */
  36920. tubularSegments,
  36921. /**
  36922. * Defines the first number of windings
  36923. */
  36924. p,
  36925. /**
  36926. * Defines the second number of windings
  36927. */
  36928. q, canBeRegenerated, mesh,
  36929. /**
  36930. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36931. */
  36932. side) {
  36933. if (mesh === void 0) { mesh = null; }
  36934. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36935. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36936. _this.radius = radius;
  36937. _this.tube = tube;
  36938. _this.radialSegments = radialSegments;
  36939. _this.tubularSegments = tubularSegments;
  36940. _this.p = p;
  36941. _this.q = q;
  36942. _this.side = side;
  36943. return _this;
  36944. }
  36945. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36946. 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 });
  36947. };
  36948. TorusKnotGeometry.prototype.copy = function (id) {
  36949. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36950. };
  36951. TorusKnotGeometry.prototype.serialize = function () {
  36952. var serializationObject = _super.prototype.serialize.call(this);
  36953. serializationObject.radius = this.radius;
  36954. serializationObject.tube = this.tube;
  36955. serializationObject.radialSegments = this.radialSegments;
  36956. serializationObject.tubularSegments = this.tubularSegments;
  36957. serializationObject.p = this.p;
  36958. serializationObject.q = this.q;
  36959. return serializationObject;
  36960. };
  36961. ;
  36962. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36963. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36964. return null; // null since geometry could be something else than a ground...
  36965. }
  36966. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36967. if (BABYLON.Tags) {
  36968. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36969. }
  36970. scene.pushGeometry(torusKnot, true);
  36971. return torusKnot;
  36972. };
  36973. return TorusKnotGeometry;
  36974. }(_PrimitiveGeometry));
  36975. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36976. //}
  36977. })(BABYLON || (BABYLON = {}));
  36978. //# sourceMappingURL=babylon.geometry.js.map
  36979. var BABYLON;
  36980. (function (BABYLON) {
  36981. /**
  36982. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36983. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36984. */
  36985. var PostProcessManager = /** @class */ (function () {
  36986. /**
  36987. * Creates a new instance of @see PostProcess
  36988. * @param scene The scene that the post process is associated with.
  36989. */
  36990. function PostProcessManager(scene) {
  36991. this._vertexBuffers = {};
  36992. this._scene = scene;
  36993. }
  36994. PostProcessManager.prototype._prepareBuffers = function () {
  36995. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36996. return;
  36997. }
  36998. // VBO
  36999. var vertices = [];
  37000. vertices.push(1, 1);
  37001. vertices.push(-1, 1);
  37002. vertices.push(-1, -1);
  37003. vertices.push(1, -1);
  37004. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37005. this._buildIndexBuffer();
  37006. };
  37007. PostProcessManager.prototype._buildIndexBuffer = function () {
  37008. // Indices
  37009. var indices = [];
  37010. indices.push(0);
  37011. indices.push(1);
  37012. indices.push(2);
  37013. indices.push(0);
  37014. indices.push(2);
  37015. indices.push(3);
  37016. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37017. };
  37018. /**
  37019. * Rebuilds the vertex buffers of the manager.
  37020. */
  37021. PostProcessManager.prototype._rebuild = function () {
  37022. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37023. if (!vb) {
  37024. return;
  37025. }
  37026. vb._rebuild();
  37027. this._buildIndexBuffer();
  37028. };
  37029. // Methods
  37030. /**
  37031. * Prepares a frame to be run through a post process.
  37032. * @param sourceTexture The input texture to the post procesess. (default: null)
  37033. * @param postProcesses An array of post processes to be run. (default: null)
  37034. * @returns True if the post processes were able to be run.
  37035. */
  37036. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37037. if (sourceTexture === void 0) { sourceTexture = null; }
  37038. if (postProcesses === void 0) { postProcesses = null; }
  37039. var camera = this._scene.activeCamera;
  37040. if (!camera) {
  37041. return false;
  37042. }
  37043. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37044. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37045. return false;
  37046. }
  37047. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37048. return true;
  37049. };
  37050. /**
  37051. * Manually render a set of post processes to a texture.
  37052. * @param postProcesses An array of post processes to be run.
  37053. * @param targetTexture The target texture to render to.
  37054. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37055. */
  37056. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37057. if (targetTexture === void 0) { targetTexture = null; }
  37058. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37059. var engine = this._scene.getEngine();
  37060. for (var index = 0; index < postProcesses.length; index++) {
  37061. if (index < postProcesses.length - 1) {
  37062. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37063. }
  37064. else {
  37065. if (targetTexture) {
  37066. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37067. }
  37068. else {
  37069. engine.restoreDefaultFramebuffer();
  37070. }
  37071. }
  37072. var pp = postProcesses[index];
  37073. var effect = pp.apply();
  37074. if (effect) {
  37075. pp.onBeforeRenderObservable.notifyObservers(effect);
  37076. // VBOs
  37077. this._prepareBuffers();
  37078. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37079. // Draw order
  37080. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37081. pp.onAfterRenderObservable.notifyObservers(effect);
  37082. }
  37083. }
  37084. // Restore depth buffer
  37085. engine.setDepthBuffer(true);
  37086. engine.setDepthWrite(true);
  37087. };
  37088. /**
  37089. * Finalize the result of the output of the postprocesses.
  37090. * @param doNotPresent If true the result will not be displayed to the screen.
  37091. * @param targetTexture The target texture to render to.
  37092. * @param faceIndex The index of the face to bind the target texture to.
  37093. * @param postProcesses The array of post processes to render.
  37094. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37095. */
  37096. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37097. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37098. var camera = this._scene.activeCamera;
  37099. if (!camera) {
  37100. return;
  37101. }
  37102. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37103. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37104. return;
  37105. }
  37106. var engine = this._scene.getEngine();
  37107. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37108. if (index < len - 1) {
  37109. postProcesses[index + 1].activate(camera, targetTexture);
  37110. }
  37111. else {
  37112. if (targetTexture) {
  37113. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37114. }
  37115. else {
  37116. engine.restoreDefaultFramebuffer();
  37117. }
  37118. }
  37119. if (doNotPresent) {
  37120. break;
  37121. }
  37122. var pp = postProcesses[index];
  37123. var effect = pp.apply();
  37124. if (effect) {
  37125. pp.onBeforeRenderObservable.notifyObservers(effect);
  37126. // VBOs
  37127. this._prepareBuffers();
  37128. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37129. // Draw order
  37130. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37131. pp.onAfterRenderObservable.notifyObservers(effect);
  37132. }
  37133. }
  37134. // Restore states
  37135. engine.setDepthBuffer(true);
  37136. engine.setDepthWrite(true);
  37137. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37138. };
  37139. /**
  37140. * Disposes of the post process manager.
  37141. */
  37142. PostProcessManager.prototype.dispose = function () {
  37143. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37144. if (buffer) {
  37145. buffer.dispose();
  37146. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37147. }
  37148. if (this._indexBuffer) {
  37149. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37150. this._indexBuffer = null;
  37151. }
  37152. };
  37153. return PostProcessManager;
  37154. }());
  37155. BABYLON.PostProcessManager = PostProcessManager;
  37156. })(BABYLON || (BABYLON = {}));
  37157. //# sourceMappingURL=babylon.postProcessManager.js.map
  37158. var BABYLON;
  37159. (function (BABYLON) {
  37160. /**
  37161. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37162. */
  37163. var PerformanceMonitor = /** @class */ (function () {
  37164. /**
  37165. * constructor
  37166. * @param frameSampleSize The number of samples required to saturate the sliding window
  37167. */
  37168. function PerformanceMonitor(frameSampleSize) {
  37169. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37170. this._enabled = true;
  37171. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37172. }
  37173. /**
  37174. * Samples current frame
  37175. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37176. */
  37177. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37178. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37179. if (!this._enabled)
  37180. return;
  37181. if (this._lastFrameTimeMs != null) {
  37182. var dt = timeMs - this._lastFrameTimeMs;
  37183. this._rollingFrameTime.add(dt);
  37184. }
  37185. this._lastFrameTimeMs = timeMs;
  37186. };
  37187. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37188. /**
  37189. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37190. * @return Average frame time in milliseconds
  37191. */
  37192. get: function () {
  37193. return this._rollingFrameTime.average;
  37194. },
  37195. enumerable: true,
  37196. configurable: true
  37197. });
  37198. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37199. /**
  37200. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37201. * @return Frame time variance in milliseconds squared
  37202. */
  37203. get: function () {
  37204. return this._rollingFrameTime.variance;
  37205. },
  37206. enumerable: true,
  37207. configurable: true
  37208. });
  37209. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37210. /**
  37211. * Returns the frame time of the most recent frame
  37212. * @return Frame time in milliseconds
  37213. */
  37214. get: function () {
  37215. return this._rollingFrameTime.history(0);
  37216. },
  37217. enumerable: true,
  37218. configurable: true
  37219. });
  37220. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37221. /**
  37222. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37223. * @return Framerate in frames per second
  37224. */
  37225. get: function () {
  37226. return 1000.0 / this._rollingFrameTime.average;
  37227. },
  37228. enumerable: true,
  37229. configurable: true
  37230. });
  37231. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37232. /**
  37233. * Returns the average framerate in frames per second using the most recent frame time
  37234. * @return Framerate in frames per second
  37235. */
  37236. get: function () {
  37237. var history = this._rollingFrameTime.history(0);
  37238. if (history === 0) {
  37239. return 0;
  37240. }
  37241. return 1000.0 / history;
  37242. },
  37243. enumerable: true,
  37244. configurable: true
  37245. });
  37246. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37247. /**
  37248. * Returns true if enough samples have been taken to completely fill the sliding window
  37249. * @return true if saturated
  37250. */
  37251. get: function () {
  37252. return this._rollingFrameTime.isSaturated();
  37253. },
  37254. enumerable: true,
  37255. configurable: true
  37256. });
  37257. /**
  37258. * Enables contributions to the sliding window sample set
  37259. */
  37260. PerformanceMonitor.prototype.enable = function () {
  37261. this._enabled = true;
  37262. };
  37263. /**
  37264. * Disables contributions to the sliding window sample set
  37265. * Samples will not be interpolated over the disabled period
  37266. */
  37267. PerformanceMonitor.prototype.disable = function () {
  37268. this._enabled = false;
  37269. //clear last sample to avoid interpolating over the disabled period when next enabled
  37270. this._lastFrameTimeMs = null;
  37271. };
  37272. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37273. /**
  37274. * Returns true if sampling is enabled
  37275. * @return true if enabled
  37276. */
  37277. get: function () {
  37278. return this._enabled;
  37279. },
  37280. enumerable: true,
  37281. configurable: true
  37282. });
  37283. /**
  37284. * Resets performance monitor
  37285. */
  37286. PerformanceMonitor.prototype.reset = function () {
  37287. //clear last sample to avoid interpolating over the disabled period when next enabled
  37288. this._lastFrameTimeMs = null;
  37289. //wipe record
  37290. this._rollingFrameTime.reset();
  37291. };
  37292. return PerformanceMonitor;
  37293. }());
  37294. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37295. /**
  37296. * RollingAverage
  37297. *
  37298. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37299. */
  37300. var RollingAverage = /** @class */ (function () {
  37301. /**
  37302. * constructor
  37303. * @param length The number of samples required to saturate the sliding window
  37304. */
  37305. function RollingAverage(length) {
  37306. this._samples = new Array(length);
  37307. this.reset();
  37308. }
  37309. /**
  37310. * Adds a sample to the sample set
  37311. * @param v The sample value
  37312. */
  37313. RollingAverage.prototype.add = function (v) {
  37314. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37315. var delta;
  37316. //we need to check if we've already wrapped round
  37317. if (this.isSaturated()) {
  37318. //remove bottom of stack from mean
  37319. var bottomValue = this._samples[this._pos];
  37320. delta = bottomValue - this.average;
  37321. this.average -= delta / (this._sampleCount - 1);
  37322. this._m2 -= delta * (bottomValue - this.average);
  37323. }
  37324. else {
  37325. this._sampleCount++;
  37326. }
  37327. //add new value to mean
  37328. delta = v - this.average;
  37329. this.average += delta / (this._sampleCount);
  37330. this._m2 += delta * (v - this.average);
  37331. //set the new variance
  37332. this.variance = this._m2 / (this._sampleCount - 1);
  37333. this._samples[this._pos] = v;
  37334. this._pos++;
  37335. this._pos %= this._samples.length; //positive wrap around
  37336. };
  37337. /**
  37338. * Returns previously added values or null if outside of history or outside the sliding window domain
  37339. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37340. * @return Value previously recorded with add() or null if outside of range
  37341. */
  37342. RollingAverage.prototype.history = function (i) {
  37343. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37344. return 0;
  37345. }
  37346. var i0 = this._wrapPosition(this._pos - 1.0);
  37347. return this._samples[this._wrapPosition(i0 - i)];
  37348. };
  37349. /**
  37350. * Returns true if enough samples have been taken to completely fill the sliding window
  37351. * @return true if sample-set saturated
  37352. */
  37353. RollingAverage.prototype.isSaturated = function () {
  37354. return this._sampleCount >= this._samples.length;
  37355. };
  37356. /**
  37357. * Resets the rolling average (equivalent to 0 samples taken so far)
  37358. */
  37359. RollingAverage.prototype.reset = function () {
  37360. this.average = 0;
  37361. this.variance = 0;
  37362. this._sampleCount = 0;
  37363. this._pos = 0;
  37364. this._m2 = 0;
  37365. };
  37366. /**
  37367. * Wraps a value around the sample range boundaries
  37368. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37369. * @return Wrapped position in sample range
  37370. */
  37371. RollingAverage.prototype._wrapPosition = function (i) {
  37372. var max = this._samples.length;
  37373. return ((i % max) + max) % max;
  37374. };
  37375. return RollingAverage;
  37376. }());
  37377. BABYLON.RollingAverage = RollingAverage;
  37378. })(BABYLON || (BABYLON = {}));
  37379. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37380. var BABYLON;
  37381. (function (BABYLON) {
  37382. /**
  37383. * This groups together the common properties used for image processing either in direct forward pass
  37384. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37385. * or not.
  37386. */
  37387. var ImageProcessingConfiguration = /** @class */ (function () {
  37388. function ImageProcessingConfiguration() {
  37389. /**
  37390. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37391. */
  37392. this.colorCurves = new BABYLON.ColorCurves();
  37393. this._colorCurvesEnabled = false;
  37394. this._colorGradingEnabled = false;
  37395. this._colorGradingWithGreenDepth = true;
  37396. this._colorGradingBGR = true;
  37397. this._exposure = 1.0;
  37398. this._toneMappingEnabled = false;
  37399. this._contrast = 1.0;
  37400. /**
  37401. * Vignette stretch size.
  37402. */
  37403. this.vignetteStretch = 0;
  37404. /**
  37405. * Vignette centre X Offset.
  37406. */
  37407. this.vignetteCentreX = 0;
  37408. /**
  37409. * Vignette centre Y Offset.
  37410. */
  37411. this.vignetteCentreY = 0;
  37412. /**
  37413. * Vignette weight or intensity of the vignette effect.
  37414. */
  37415. this.vignetteWeight = 1.5;
  37416. /**
  37417. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37418. * if vignetteEnabled is set to true.
  37419. */
  37420. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37421. /**
  37422. * Camera field of view used by the Vignette effect.
  37423. */
  37424. this.vignetteCameraFov = 0.5;
  37425. this._grainEnabled = false;
  37426. this._grainIntensity = 30;
  37427. this._grainAnimated = false;
  37428. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37429. this._vignetteEnabled = false;
  37430. this._applyByPostProcess = false;
  37431. this._isEnabled = true;
  37432. /**
  37433. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37434. * @type {BABYLON.Observable}
  37435. */
  37436. this.onUpdateParameters = new BABYLON.Observable();
  37437. }
  37438. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37439. /**
  37440. * Gets wether the color curves effect is enabled.
  37441. */
  37442. get: function () {
  37443. return this._colorCurvesEnabled;
  37444. },
  37445. /**
  37446. * Sets wether the color curves effect is enabled.
  37447. */
  37448. set: function (value) {
  37449. if (this._colorCurvesEnabled === value) {
  37450. return;
  37451. }
  37452. this._colorCurvesEnabled = value;
  37453. this._updateParameters();
  37454. },
  37455. enumerable: true,
  37456. configurable: true
  37457. });
  37458. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37459. /**
  37460. * Gets wether the color grading effect is enabled.
  37461. */
  37462. get: function () {
  37463. return this._colorGradingEnabled;
  37464. },
  37465. /**
  37466. * Sets wether the color grading effect is enabled.
  37467. */
  37468. set: function (value) {
  37469. if (this._colorGradingEnabled === value) {
  37470. return;
  37471. }
  37472. this._colorGradingEnabled = value;
  37473. this._updateParameters();
  37474. },
  37475. enumerable: true,
  37476. configurable: true
  37477. });
  37478. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37479. /**
  37480. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37481. */
  37482. get: function () {
  37483. return this._colorGradingWithGreenDepth;
  37484. },
  37485. /**
  37486. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37487. */
  37488. set: function (value) {
  37489. if (this._colorGradingWithGreenDepth === value) {
  37490. return;
  37491. }
  37492. this._colorGradingWithGreenDepth = value;
  37493. this._updateParameters();
  37494. },
  37495. enumerable: true,
  37496. configurable: true
  37497. });
  37498. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37499. /**
  37500. * Gets wether the color grading texture contains BGR values.
  37501. */
  37502. get: function () {
  37503. return this._colorGradingBGR;
  37504. },
  37505. /**
  37506. * Sets wether the color grading texture contains BGR values.
  37507. */
  37508. set: function (value) {
  37509. if (this._colorGradingBGR === value) {
  37510. return;
  37511. }
  37512. this._colorGradingBGR = value;
  37513. this._updateParameters();
  37514. },
  37515. enumerable: true,
  37516. configurable: true
  37517. });
  37518. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37519. /**
  37520. * Gets the Exposure used in the effect.
  37521. */
  37522. get: function () {
  37523. return this._exposure;
  37524. },
  37525. /**
  37526. * Sets the Exposure used in the effect.
  37527. */
  37528. set: function (value) {
  37529. if (this._exposure === value) {
  37530. return;
  37531. }
  37532. this._exposure = value;
  37533. this._updateParameters();
  37534. },
  37535. enumerable: true,
  37536. configurable: true
  37537. });
  37538. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37539. /**
  37540. * Gets wether the tone mapping effect is enabled.
  37541. */
  37542. get: function () {
  37543. return this._toneMappingEnabled;
  37544. },
  37545. /**
  37546. * Sets wether the tone mapping effect is enabled.
  37547. */
  37548. set: function (value) {
  37549. if (this._toneMappingEnabled === value) {
  37550. return;
  37551. }
  37552. this._toneMappingEnabled = value;
  37553. this._updateParameters();
  37554. },
  37555. enumerable: true,
  37556. configurable: true
  37557. });
  37558. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37559. /**
  37560. * Gets the contrast used in the effect.
  37561. */
  37562. get: function () {
  37563. return this._contrast;
  37564. },
  37565. /**
  37566. * Sets the contrast used in the effect.
  37567. */
  37568. set: function (value) {
  37569. if (this._contrast === value) {
  37570. return;
  37571. }
  37572. this._contrast = value;
  37573. this._updateParameters();
  37574. },
  37575. enumerable: true,
  37576. configurable: true
  37577. });
  37578. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37579. /**
  37580. * If the grain effect should be enabled.
  37581. */
  37582. get: function () {
  37583. return this._grainEnabled;
  37584. },
  37585. set: function (value) {
  37586. if (this._grainEnabled === value) {
  37587. return;
  37588. }
  37589. this._grainEnabled = value;
  37590. this._updateParameters();
  37591. },
  37592. enumerable: true,
  37593. configurable: true
  37594. });
  37595. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37596. /**
  37597. * Amount of grain to be applied by the grain effect.
  37598. */
  37599. get: function () {
  37600. return this._grainIntensity;
  37601. },
  37602. set: function (value) {
  37603. if (this._grainIntensity === value) {
  37604. return;
  37605. }
  37606. this._grainIntensity = value;
  37607. },
  37608. enumerable: true,
  37609. configurable: true
  37610. });
  37611. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37612. /**
  37613. * If the grain effect should be animated.
  37614. */
  37615. get: function () {
  37616. return this._grainAnimated;
  37617. },
  37618. set: function (value) {
  37619. if (this._grainAnimated === value) {
  37620. return;
  37621. }
  37622. this._grainAnimated = value;
  37623. this._updateParameters();
  37624. },
  37625. enumerable: true,
  37626. configurable: true
  37627. });
  37628. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37629. /**
  37630. * Gets the vignette blend mode allowing different kind of effect.
  37631. */
  37632. get: function () {
  37633. return this._vignetteBlendMode;
  37634. },
  37635. /**
  37636. * Sets the vignette blend mode allowing different kind of effect.
  37637. */
  37638. set: function (value) {
  37639. if (this._vignetteBlendMode === value) {
  37640. return;
  37641. }
  37642. this._vignetteBlendMode = value;
  37643. this._updateParameters();
  37644. },
  37645. enumerable: true,
  37646. configurable: true
  37647. });
  37648. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37649. /**
  37650. * Gets wether the vignette effect is enabled.
  37651. */
  37652. get: function () {
  37653. return this._vignetteEnabled;
  37654. },
  37655. /**
  37656. * Sets wether the vignette effect is enabled.
  37657. */
  37658. set: function (value) {
  37659. if (this._vignetteEnabled === value) {
  37660. return;
  37661. }
  37662. this._vignetteEnabled = value;
  37663. this._updateParameters();
  37664. },
  37665. enumerable: true,
  37666. configurable: true
  37667. });
  37668. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37669. /**
  37670. * Gets wether the image processing is applied through a post process or not.
  37671. */
  37672. get: function () {
  37673. return this._applyByPostProcess;
  37674. },
  37675. /**
  37676. * Sets wether the image processing is applied through a post process or not.
  37677. */
  37678. set: function (value) {
  37679. if (this._applyByPostProcess === value) {
  37680. return;
  37681. }
  37682. this._applyByPostProcess = value;
  37683. this._updateParameters();
  37684. },
  37685. enumerable: true,
  37686. configurable: true
  37687. });
  37688. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37689. /**
  37690. * Gets wether the image processing is enabled or not.
  37691. */
  37692. get: function () {
  37693. return this._isEnabled;
  37694. },
  37695. /**
  37696. * Sets wether the image processing is enabled or not.
  37697. */
  37698. set: function (value) {
  37699. if (this._isEnabled === value) {
  37700. return;
  37701. }
  37702. this._isEnabled = value;
  37703. this._updateParameters();
  37704. },
  37705. enumerable: true,
  37706. configurable: true
  37707. });
  37708. /**
  37709. * Method called each time the image processing information changes requires to recompile the effect.
  37710. */
  37711. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37712. this.onUpdateParameters.notifyObservers(this);
  37713. };
  37714. ImageProcessingConfiguration.prototype.getClassName = function () {
  37715. return "ImageProcessingConfiguration";
  37716. };
  37717. /**
  37718. * Prepare the list of uniforms associated with the Image Processing effects.
  37719. * @param uniformsList The list of uniforms used in the effect
  37720. * @param defines the list of defines currently in use
  37721. */
  37722. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37723. if (defines.EXPOSURE) {
  37724. uniforms.push("exposureLinear");
  37725. }
  37726. if (defines.CONTRAST) {
  37727. uniforms.push("contrast");
  37728. }
  37729. if (defines.COLORGRADING) {
  37730. uniforms.push("colorTransformSettings");
  37731. }
  37732. if (defines.VIGNETTE) {
  37733. uniforms.push("vInverseScreenSize");
  37734. uniforms.push("vignetteSettings1");
  37735. uniforms.push("vignetteSettings2");
  37736. }
  37737. if (defines.COLORCURVES) {
  37738. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37739. }
  37740. if (defines.GRAIN) {
  37741. uniforms.push("grainVarianceAmount");
  37742. uniforms.push("grainAnimatedSeed");
  37743. }
  37744. };
  37745. /**
  37746. * Prepare the list of samplers associated with the Image Processing effects.
  37747. * @param uniformsList The list of uniforms used in the effect
  37748. * @param defines the list of defines currently in use
  37749. */
  37750. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37751. if (defines.COLORGRADING) {
  37752. samplersList.push("txColorTransform");
  37753. }
  37754. };
  37755. /**
  37756. * Prepare the list of defines associated to the shader.
  37757. * @param defines the list of defines to complete
  37758. */
  37759. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37760. if (forPostProcess === void 0) { forPostProcess = false; }
  37761. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37762. defines.VIGNETTE = false;
  37763. defines.TONEMAPPING = false;
  37764. defines.CONTRAST = false;
  37765. defines.EXPOSURE = false;
  37766. defines.COLORCURVES = false;
  37767. defines.COLORGRADING = false;
  37768. defines.COLORGRADING3D = false;
  37769. defines.IMAGEPROCESSING = false;
  37770. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37771. return;
  37772. }
  37773. defines.VIGNETTE = this.vignetteEnabled;
  37774. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37775. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37776. defines.TONEMAPPING = this.toneMappingEnabled;
  37777. defines.CONTRAST = (this.contrast !== 1.0);
  37778. defines.EXPOSURE = (this.exposure !== 1.0);
  37779. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37780. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37781. if (defines.COLORGRADING) {
  37782. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37783. }
  37784. else {
  37785. defines.COLORGRADING3D = false;
  37786. }
  37787. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37788. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37789. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37790. defines.GRAIN = this.grainEnabled;
  37791. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37792. };
  37793. /**
  37794. * Returns true if all the image processing information are ready.
  37795. */
  37796. ImageProcessingConfiguration.prototype.isReady = function () {
  37797. // Color Grading texure can not be none blocking.
  37798. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37799. };
  37800. /**
  37801. * Binds the image processing to the shader.
  37802. * @param effect The effect to bind to
  37803. */
  37804. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37805. if (aspectRatio === void 0) { aspectRatio = 1; }
  37806. // Color Curves
  37807. if (this._colorCurvesEnabled && this.colorCurves) {
  37808. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37809. }
  37810. // Vignette
  37811. if (this._vignetteEnabled) {
  37812. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37813. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37814. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37815. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37816. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37817. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37818. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37819. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37820. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37821. var vignettePower = -2.0 * this.vignetteWeight;
  37822. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37823. }
  37824. // Exposure
  37825. effect.setFloat("exposureLinear", this.exposure);
  37826. // Contrast
  37827. effect.setFloat("contrast", this.contrast);
  37828. // Color transform settings
  37829. if (this.colorGradingTexture) {
  37830. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37831. var textureSize = this.colorGradingTexture.getSize().height;
  37832. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37833. 0.5 / textureSize, // textureOffset
  37834. textureSize, // textureSize
  37835. this.colorGradingTexture.level // weight
  37836. );
  37837. }
  37838. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37839. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37840. };
  37841. /**
  37842. * Clones the current image processing instance.
  37843. * @return The cloned image processing
  37844. */
  37845. ImageProcessingConfiguration.prototype.clone = function () {
  37846. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37847. };
  37848. /**
  37849. * Serializes the current image processing instance to a json representation.
  37850. * @return a JSON representation
  37851. */
  37852. ImageProcessingConfiguration.prototype.serialize = function () {
  37853. return BABYLON.SerializationHelper.Serialize(this);
  37854. };
  37855. /**
  37856. * Parses the image processing from a json representation.
  37857. * @param source the JSON source to parse
  37858. * @return The parsed image processing
  37859. */
  37860. ImageProcessingConfiguration.Parse = function (source) {
  37861. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37862. };
  37863. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37864. /**
  37865. * Used to apply the vignette as a mix with the pixel color.
  37866. */
  37867. get: function () {
  37868. return this._VIGNETTEMODE_MULTIPLY;
  37869. },
  37870. enumerable: true,
  37871. configurable: true
  37872. });
  37873. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37874. /**
  37875. * Used to apply the vignette as a replacement of the pixel color.
  37876. */
  37877. get: function () {
  37878. return this._VIGNETTEMODE_OPAQUE;
  37879. },
  37880. enumerable: true,
  37881. configurable: true
  37882. });
  37883. // Static constants associated to the image processing.
  37884. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37885. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37886. __decorate([
  37887. BABYLON.serializeAsColorCurves()
  37888. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37889. __decorate([
  37890. BABYLON.serialize()
  37891. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37892. __decorate([
  37893. BABYLON.serializeAsTexture()
  37894. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37895. __decorate([
  37896. BABYLON.serialize()
  37897. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37898. __decorate([
  37899. BABYLON.serialize()
  37900. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37901. __decorate([
  37902. BABYLON.serialize()
  37903. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37904. __decorate([
  37905. BABYLON.serialize()
  37906. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37907. __decorate([
  37908. BABYLON.serialize()
  37909. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37910. __decorate([
  37911. BABYLON.serialize()
  37912. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37913. __decorate([
  37914. BABYLON.serialize()
  37915. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37916. __decorate([
  37917. BABYLON.serialize()
  37918. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37919. __decorate([
  37920. BABYLON.serialize()
  37921. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37922. __decorate([
  37923. BABYLON.serialize()
  37924. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37925. __decorate([
  37926. BABYLON.serializeAsColor4()
  37927. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37928. __decorate([
  37929. BABYLON.serialize()
  37930. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37931. __decorate([
  37932. BABYLON.serialize()
  37933. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37934. __decorate([
  37935. BABYLON.serialize()
  37936. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37937. __decorate([
  37938. BABYLON.serialize()
  37939. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37940. __decorate([
  37941. BABYLON.serialize()
  37942. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37943. __decorate([
  37944. BABYLON.serialize()
  37945. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37946. __decorate([
  37947. BABYLON.serialize()
  37948. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37949. __decorate([
  37950. BABYLON.serialize()
  37951. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37952. return ImageProcessingConfiguration;
  37953. }());
  37954. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37955. })(BABYLON || (BABYLON = {}));
  37956. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37957. var BABYLON;
  37958. (function (BABYLON) {
  37959. /**
  37960. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37961. * It can help converting any input color in a desired output one. This can then be used to create effects
  37962. * from sepia, black and white to sixties or futuristic rendering...
  37963. *
  37964. * The only supported format is currently 3dl.
  37965. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37966. */
  37967. var ColorGradingTexture = /** @class */ (function (_super) {
  37968. __extends(ColorGradingTexture, _super);
  37969. /**
  37970. * Instantiates a ColorGradingTexture from the following parameters.
  37971. *
  37972. * @param url The location of the color gradind data (currently only supporting 3dl)
  37973. * @param scene The scene the texture will be used in
  37974. */
  37975. function ColorGradingTexture(url, scene) {
  37976. var _this = _super.call(this, scene) || this;
  37977. if (!url) {
  37978. return _this;
  37979. }
  37980. _this._engine = scene.getEngine();
  37981. _this._textureMatrix = BABYLON.Matrix.Identity();
  37982. _this.name = url;
  37983. _this.url = url;
  37984. _this.hasAlpha = false;
  37985. _this.isCube = false;
  37986. _this.is3D = _this._engine.webGLVersion > 1;
  37987. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37988. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37989. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37990. _this.anisotropicFilteringLevel = 1;
  37991. _this._texture = _this._getFromCache(url, true);
  37992. if (!_this._texture) {
  37993. if (!scene.useDelayedTextureLoading) {
  37994. _this.loadTexture();
  37995. }
  37996. else {
  37997. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37998. }
  37999. }
  38000. return _this;
  38001. }
  38002. /**
  38003. * Returns the texture matrix used in most of the material.
  38004. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38005. */
  38006. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38007. return this._textureMatrix;
  38008. };
  38009. /**
  38010. * Occurs when the file being loaded is a .3dl LUT file.
  38011. */
  38012. ColorGradingTexture.prototype.load3dlTexture = function () {
  38013. var engine = this._engine;
  38014. var texture;
  38015. if (engine.webGLVersion === 1) {
  38016. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38017. }
  38018. else {
  38019. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38020. }
  38021. this._texture = texture;
  38022. var callback = function (text) {
  38023. if (typeof text !== "string") {
  38024. return;
  38025. }
  38026. var data = null;
  38027. var tempData = null;
  38028. var line;
  38029. var lines = text.split('\n');
  38030. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38031. var maxColor = 0;
  38032. for (var i = 0; i < lines.length; i++) {
  38033. line = lines[i];
  38034. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38035. continue;
  38036. if (line.indexOf('#') === 0)
  38037. continue;
  38038. var words = line.split(" ");
  38039. if (size === 0) {
  38040. // Number of space + one
  38041. size = words.length;
  38042. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38043. tempData = new Float32Array(size * size * size * 4);
  38044. continue;
  38045. }
  38046. if (size != 0) {
  38047. var r = Math.max(parseInt(words[0]), 0);
  38048. var g = Math.max(parseInt(words[1]), 0);
  38049. var b = Math.max(parseInt(words[2]), 0);
  38050. maxColor = Math.max(r, maxColor);
  38051. maxColor = Math.max(g, maxColor);
  38052. maxColor = Math.max(b, maxColor);
  38053. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38054. if (tempData) {
  38055. tempData[pixelStorageIndex + 0] = r;
  38056. tempData[pixelStorageIndex + 1] = g;
  38057. tempData[pixelStorageIndex + 2] = b;
  38058. }
  38059. pixelIndexSlice++;
  38060. if (pixelIndexSlice % size == 0) {
  38061. pixelIndexH++;
  38062. pixelIndexSlice = 0;
  38063. if (pixelIndexH % size == 0) {
  38064. pixelIndexW++;
  38065. pixelIndexH = 0;
  38066. }
  38067. }
  38068. }
  38069. }
  38070. if (tempData && data) {
  38071. for (var i = 0; i < tempData.length; i++) {
  38072. if (i > 0 && (i + 1) % 4 === 0) {
  38073. data[i] = 255;
  38074. }
  38075. else {
  38076. var value = tempData[i];
  38077. data[i] = (value / maxColor * 255);
  38078. }
  38079. }
  38080. }
  38081. if (texture.is3D) {
  38082. texture.updateSize(size, size, size);
  38083. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38084. }
  38085. else {
  38086. texture.updateSize(size * size, size);
  38087. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38088. }
  38089. };
  38090. var scene = this.getScene();
  38091. if (scene) {
  38092. scene._loadFile(this.url, callback);
  38093. }
  38094. else {
  38095. this._engine._loadFile(this.url, callback);
  38096. }
  38097. return this._texture;
  38098. };
  38099. /**
  38100. * Starts the loading process of the texture.
  38101. */
  38102. ColorGradingTexture.prototype.loadTexture = function () {
  38103. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38104. this.load3dlTexture();
  38105. }
  38106. };
  38107. /**
  38108. * Clones the color gradind texture.
  38109. */
  38110. ColorGradingTexture.prototype.clone = function () {
  38111. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38112. // Base texture
  38113. newTexture.level = this.level;
  38114. return newTexture;
  38115. };
  38116. /**
  38117. * Called during delayed load for textures.
  38118. */
  38119. ColorGradingTexture.prototype.delayLoad = function () {
  38120. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38121. return;
  38122. }
  38123. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38124. this._texture = this._getFromCache(this.url, true);
  38125. if (!this._texture) {
  38126. this.loadTexture();
  38127. }
  38128. };
  38129. /**
  38130. * Parses a color grading texture serialized by Babylon.
  38131. * @param parsedTexture The texture information being parsedTexture
  38132. * @param scene The scene to load the texture in
  38133. * @param rootUrl The root url of the data assets to load
  38134. * @return A color gradind texture
  38135. */
  38136. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38137. var texture = null;
  38138. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38139. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38140. texture.name = parsedTexture.name;
  38141. texture.level = parsedTexture.level;
  38142. }
  38143. return texture;
  38144. };
  38145. /**
  38146. * Serializes the LUT texture to json format.
  38147. */
  38148. ColorGradingTexture.prototype.serialize = function () {
  38149. if (!this.name) {
  38150. return null;
  38151. }
  38152. var serializationObject = {};
  38153. serializationObject.name = this.name;
  38154. serializationObject.level = this.level;
  38155. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38156. return serializationObject;
  38157. };
  38158. /**
  38159. * Empty line regex stored for GC.
  38160. */
  38161. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38162. return ColorGradingTexture;
  38163. }(BABYLON.BaseTexture));
  38164. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38165. })(BABYLON || (BABYLON = {}));
  38166. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38167. var BABYLON;
  38168. (function (BABYLON) {
  38169. /**
  38170. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38171. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38172. * 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;
  38173. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38174. */
  38175. var ColorCurves = /** @class */ (function () {
  38176. function ColorCurves() {
  38177. this._dirty = true;
  38178. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38179. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38180. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38181. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38182. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38183. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38184. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38185. this._globalHue = 30;
  38186. this._globalDensity = 0;
  38187. this._globalSaturation = 0;
  38188. this._globalExposure = 0;
  38189. this._highlightsHue = 30;
  38190. this._highlightsDensity = 0;
  38191. this._highlightsSaturation = 0;
  38192. this._highlightsExposure = 0;
  38193. this._midtonesHue = 30;
  38194. this._midtonesDensity = 0;
  38195. this._midtonesSaturation = 0;
  38196. this._midtonesExposure = 0;
  38197. this._shadowsHue = 30;
  38198. this._shadowsDensity = 0;
  38199. this._shadowsSaturation = 0;
  38200. this._shadowsExposure = 0;
  38201. }
  38202. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38203. /**
  38204. * Gets the global Hue value.
  38205. * 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).
  38206. */
  38207. get: function () {
  38208. return this._globalHue;
  38209. },
  38210. /**
  38211. * Sets the global Hue value.
  38212. * 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).
  38213. */
  38214. set: function (value) {
  38215. this._globalHue = value;
  38216. this._dirty = true;
  38217. },
  38218. enumerable: true,
  38219. configurable: true
  38220. });
  38221. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38222. /**
  38223. * Gets the global Density value.
  38224. * 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.
  38225. * Values less than zero provide a filter of opposite hue.
  38226. */
  38227. get: function () {
  38228. return this._globalDensity;
  38229. },
  38230. /**
  38231. * Sets the global Density value.
  38232. * 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.
  38233. * Values less than zero provide a filter of opposite hue.
  38234. */
  38235. set: function (value) {
  38236. this._globalDensity = value;
  38237. this._dirty = true;
  38238. },
  38239. enumerable: true,
  38240. configurable: true
  38241. });
  38242. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38243. /**
  38244. * Gets the global Saturation value.
  38245. * 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.
  38246. */
  38247. get: function () {
  38248. return this._globalSaturation;
  38249. },
  38250. /**
  38251. * Sets the global Saturation value.
  38252. * 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.
  38253. */
  38254. set: function (value) {
  38255. this._globalSaturation = value;
  38256. this._dirty = true;
  38257. },
  38258. enumerable: true,
  38259. configurable: true
  38260. });
  38261. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38262. /**
  38263. * Gets the highlights Hue value.
  38264. * 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).
  38265. */
  38266. get: function () {
  38267. return this._highlightsHue;
  38268. },
  38269. /**
  38270. * Sets the highlights Hue value.
  38271. * 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).
  38272. */
  38273. set: function (value) {
  38274. this._highlightsHue = value;
  38275. this._dirty = true;
  38276. },
  38277. enumerable: true,
  38278. configurable: true
  38279. });
  38280. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38281. /**
  38282. * Gets the highlights Density value.
  38283. * 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.
  38284. * Values less than zero provide a filter of opposite hue.
  38285. */
  38286. get: function () {
  38287. return this._highlightsDensity;
  38288. },
  38289. /**
  38290. * Sets the highlights Density value.
  38291. * 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.
  38292. * Values less than zero provide a filter of opposite hue.
  38293. */
  38294. set: function (value) {
  38295. this._highlightsDensity = value;
  38296. this._dirty = true;
  38297. },
  38298. enumerable: true,
  38299. configurable: true
  38300. });
  38301. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38302. /**
  38303. * Gets the highlights Saturation value.
  38304. * 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.
  38305. */
  38306. get: function () {
  38307. return this._highlightsSaturation;
  38308. },
  38309. /**
  38310. * Sets the highlights Saturation value.
  38311. * 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.
  38312. */
  38313. set: function (value) {
  38314. this._highlightsSaturation = value;
  38315. this._dirty = true;
  38316. },
  38317. enumerable: true,
  38318. configurable: true
  38319. });
  38320. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38321. /**
  38322. * Gets the highlights Exposure value.
  38323. * 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.
  38324. */
  38325. get: function () {
  38326. return this._highlightsExposure;
  38327. },
  38328. /**
  38329. * Sets the highlights Exposure value.
  38330. * 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.
  38331. */
  38332. set: function (value) {
  38333. this._highlightsExposure = value;
  38334. this._dirty = true;
  38335. },
  38336. enumerable: true,
  38337. configurable: true
  38338. });
  38339. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38340. /**
  38341. * Gets the midtones Hue value.
  38342. * 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).
  38343. */
  38344. get: function () {
  38345. return this._midtonesHue;
  38346. },
  38347. /**
  38348. * Sets the midtones Hue value.
  38349. * 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).
  38350. */
  38351. set: function (value) {
  38352. this._midtonesHue = value;
  38353. this._dirty = true;
  38354. },
  38355. enumerable: true,
  38356. configurable: true
  38357. });
  38358. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38359. /**
  38360. * Gets the midtones Density value.
  38361. * 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.
  38362. * Values less than zero provide a filter of opposite hue.
  38363. */
  38364. get: function () {
  38365. return this._midtonesDensity;
  38366. },
  38367. /**
  38368. * Sets the midtones Density value.
  38369. * 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.
  38370. * Values less than zero provide a filter of opposite hue.
  38371. */
  38372. set: function (value) {
  38373. this._midtonesDensity = value;
  38374. this._dirty = true;
  38375. },
  38376. enumerable: true,
  38377. configurable: true
  38378. });
  38379. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38380. /**
  38381. * Gets the midtones Saturation value.
  38382. * 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.
  38383. */
  38384. get: function () {
  38385. return this._midtonesSaturation;
  38386. },
  38387. /**
  38388. * Sets the midtones Saturation value.
  38389. * 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.
  38390. */
  38391. set: function (value) {
  38392. this._midtonesSaturation = value;
  38393. this._dirty = true;
  38394. },
  38395. enumerable: true,
  38396. configurable: true
  38397. });
  38398. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38399. /**
  38400. * Gets the midtones Exposure value.
  38401. * 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.
  38402. */
  38403. get: function () {
  38404. return this._midtonesExposure;
  38405. },
  38406. /**
  38407. * Sets the midtones Exposure value.
  38408. * 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.
  38409. */
  38410. set: function (value) {
  38411. this._midtonesExposure = value;
  38412. this._dirty = true;
  38413. },
  38414. enumerable: true,
  38415. configurable: true
  38416. });
  38417. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38418. /**
  38419. * Gets the shadows Hue value.
  38420. * 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).
  38421. */
  38422. get: function () {
  38423. return this._shadowsHue;
  38424. },
  38425. /**
  38426. * Sets the shadows Hue value.
  38427. * 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).
  38428. */
  38429. set: function (value) {
  38430. this._shadowsHue = value;
  38431. this._dirty = true;
  38432. },
  38433. enumerable: true,
  38434. configurable: true
  38435. });
  38436. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38437. /**
  38438. * Gets the shadows Density value.
  38439. * 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.
  38440. * Values less than zero provide a filter of opposite hue.
  38441. */
  38442. get: function () {
  38443. return this._shadowsDensity;
  38444. },
  38445. /**
  38446. * Sets the shadows Density value.
  38447. * 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.
  38448. * Values less than zero provide a filter of opposite hue.
  38449. */
  38450. set: function (value) {
  38451. this._shadowsDensity = value;
  38452. this._dirty = true;
  38453. },
  38454. enumerable: true,
  38455. configurable: true
  38456. });
  38457. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38458. /**
  38459. * Gets the shadows Saturation value.
  38460. * 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.
  38461. */
  38462. get: function () {
  38463. return this._shadowsSaturation;
  38464. },
  38465. /**
  38466. * Sets the shadows Saturation value.
  38467. * 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.
  38468. */
  38469. set: function (value) {
  38470. this._shadowsSaturation = value;
  38471. this._dirty = true;
  38472. },
  38473. enumerable: true,
  38474. configurable: true
  38475. });
  38476. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38477. /**
  38478. * Gets the shadows Exposure value.
  38479. * 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.
  38480. */
  38481. get: function () {
  38482. return this._shadowsExposure;
  38483. },
  38484. /**
  38485. * Sets the shadows Exposure value.
  38486. * 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.
  38487. */
  38488. set: function (value) {
  38489. this._shadowsExposure = value;
  38490. this._dirty = true;
  38491. },
  38492. enumerable: true,
  38493. configurable: true
  38494. });
  38495. ColorCurves.prototype.getClassName = function () {
  38496. return "ColorCurves";
  38497. };
  38498. /**
  38499. * Binds the color curves to the shader.
  38500. * @param colorCurves The color curve to bind
  38501. * @param effect The effect to bind to
  38502. */
  38503. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38504. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38505. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38506. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38507. if (colorCurves._dirty) {
  38508. colorCurves._dirty = false;
  38509. // Fill in global info.
  38510. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38511. // Compute highlights info.
  38512. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38513. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38514. // Compute midtones info.
  38515. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38516. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38517. // Compute shadows info.
  38518. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38519. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38520. // Compute deltas (neutral is midtones).
  38521. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38522. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38523. }
  38524. if (effect) {
  38525. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38526. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38527. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38528. }
  38529. };
  38530. /**
  38531. * Prepare the list of uniforms associated with the ColorCurves effects.
  38532. * @param uniformsList The list of uniforms used in the effect
  38533. */
  38534. ColorCurves.PrepareUniforms = function (uniformsList) {
  38535. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38536. };
  38537. /**
  38538. * Returns color grading data based on a hue, density, saturation and exposure value.
  38539. * @param filterHue The hue of the color filter.
  38540. * @param filterDensity The density of the color filter.
  38541. * @param saturation The saturation.
  38542. * @param exposure The exposure.
  38543. * @param result The result data container.
  38544. */
  38545. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38546. if (hue == null) {
  38547. return;
  38548. }
  38549. hue = ColorCurves.clamp(hue, 0, 360);
  38550. density = ColorCurves.clamp(density, -100, 100);
  38551. saturation = ColorCurves.clamp(saturation, -100, 100);
  38552. exposure = ColorCurves.clamp(exposure, -100, 100);
  38553. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38554. // so that the maximum filter density is only 50% control. This provides fine control
  38555. // for small values and reasonable range.
  38556. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38557. density *= 0.5;
  38558. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38559. if (density < 0) {
  38560. density *= -1;
  38561. hue = (hue + 180) % 360;
  38562. }
  38563. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38564. result.scaleToRef(2, result);
  38565. result.a = 1 + 0.01 * saturation;
  38566. };
  38567. /**
  38568. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38569. * @param value The input slider value in range [-100,100].
  38570. * @returns Adjusted value.
  38571. */
  38572. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38573. value /= 100;
  38574. var x = Math.abs(value);
  38575. x = Math.pow(x, 2);
  38576. if (value < 0) {
  38577. x *= -1;
  38578. }
  38579. x *= 100;
  38580. return x;
  38581. };
  38582. /**
  38583. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38584. * @param hue The hue (H) input.
  38585. * @param saturation The saturation (S) input.
  38586. * @param brightness The brightness (B) input.
  38587. * @result An RGBA color represented as Vector4.
  38588. */
  38589. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38590. var h = ColorCurves.clamp(hue, 0, 360);
  38591. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38592. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38593. if (s === 0) {
  38594. result.r = v;
  38595. result.g = v;
  38596. result.b = v;
  38597. }
  38598. else {
  38599. // sector 0 to 5
  38600. h /= 60;
  38601. var i = Math.floor(h);
  38602. // fractional part of h
  38603. var f = h - i;
  38604. var p = v * (1 - s);
  38605. var q = v * (1 - s * f);
  38606. var t = v * (1 - s * (1 - f));
  38607. switch (i) {
  38608. case 0:
  38609. result.r = v;
  38610. result.g = t;
  38611. result.b = p;
  38612. break;
  38613. case 1:
  38614. result.r = q;
  38615. result.g = v;
  38616. result.b = p;
  38617. break;
  38618. case 2:
  38619. result.r = p;
  38620. result.g = v;
  38621. result.b = t;
  38622. break;
  38623. case 3:
  38624. result.r = p;
  38625. result.g = q;
  38626. result.b = v;
  38627. break;
  38628. case 4:
  38629. result.r = t;
  38630. result.g = p;
  38631. result.b = v;
  38632. break;
  38633. default:// case 5:
  38634. result.r = v;
  38635. result.g = p;
  38636. result.b = q;
  38637. break;
  38638. }
  38639. }
  38640. result.a = 1;
  38641. };
  38642. /**
  38643. * Returns a value clamped between min and max
  38644. * @param value The value to clamp
  38645. * @param min The minimum of value
  38646. * @param max The maximum of value
  38647. * @returns The clamped value.
  38648. */
  38649. ColorCurves.clamp = function (value, min, max) {
  38650. return Math.min(Math.max(value, min), max);
  38651. };
  38652. /**
  38653. * Clones the current color curve instance.
  38654. * @return The cloned curves
  38655. */
  38656. ColorCurves.prototype.clone = function () {
  38657. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38658. };
  38659. /**
  38660. * Serializes the current color curve instance to a json representation.
  38661. * @return a JSON representation
  38662. */
  38663. ColorCurves.prototype.serialize = function () {
  38664. return BABYLON.SerializationHelper.Serialize(this);
  38665. };
  38666. /**
  38667. * Parses the color curve from a json representation.
  38668. * @param source the JSON source to parse
  38669. * @return The parsed curves
  38670. */
  38671. ColorCurves.Parse = function (source) {
  38672. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38673. };
  38674. __decorate([
  38675. BABYLON.serialize()
  38676. ], ColorCurves.prototype, "_globalHue", void 0);
  38677. __decorate([
  38678. BABYLON.serialize()
  38679. ], ColorCurves.prototype, "_globalDensity", void 0);
  38680. __decorate([
  38681. BABYLON.serialize()
  38682. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38683. __decorate([
  38684. BABYLON.serialize()
  38685. ], ColorCurves.prototype, "_globalExposure", void 0);
  38686. __decorate([
  38687. BABYLON.serialize()
  38688. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38689. __decorate([
  38690. BABYLON.serialize()
  38691. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38692. __decorate([
  38693. BABYLON.serialize()
  38694. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38695. __decorate([
  38696. BABYLON.serialize()
  38697. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38698. __decorate([
  38699. BABYLON.serialize()
  38700. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38701. __decorate([
  38702. BABYLON.serialize()
  38703. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38704. __decorate([
  38705. BABYLON.serialize()
  38706. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38707. __decorate([
  38708. BABYLON.serialize()
  38709. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38710. return ColorCurves;
  38711. }());
  38712. BABYLON.ColorCurves = ColorCurves;
  38713. })(BABYLON || (BABYLON = {}));
  38714. //# sourceMappingURL=babylon.colorCurves.js.map
  38715. //# sourceMappingURL=babylon.behavior.js.map
  38716. var BABYLON;
  38717. (function (BABYLON) {
  38718. /**
  38719. * "Static Class" containing the most commonly used helper while dealing with material for
  38720. * rendering purpose.
  38721. *
  38722. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38723. *
  38724. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38725. */
  38726. var MaterialHelper = /** @class */ (function () {
  38727. function MaterialHelper() {
  38728. }
  38729. /**
  38730. * Bind the current view position to an effect.
  38731. * @param effect The effect to be bound
  38732. * @param scene The scene the eyes position is used from
  38733. */
  38734. MaterialHelper.BindEyePosition = function (effect, scene) {
  38735. if (scene._forcedViewPosition) {
  38736. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38737. return;
  38738. }
  38739. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38740. };
  38741. /**
  38742. * Helps preparing the defines values about the UVs in used in the effect.
  38743. * UVs are shared as much as we can accross chanels in the shaders.
  38744. * @param texture The texture we are preparing the UVs for
  38745. * @param defines The defines to update
  38746. * @param key The chanel key "diffuse", "specular"... used in the shader
  38747. */
  38748. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38749. defines._needUVs = true;
  38750. defines[key] = true;
  38751. if (texture.getTextureMatrix().isIdentity(true)) {
  38752. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38753. if (texture.coordinatesIndex === 0) {
  38754. defines["MAINUV1"] = true;
  38755. }
  38756. else {
  38757. defines["MAINUV2"] = true;
  38758. }
  38759. }
  38760. else {
  38761. defines[key + "DIRECTUV"] = 0;
  38762. }
  38763. };
  38764. /**
  38765. * Binds a texture matrix value to its corrsponding uniform
  38766. * @param texture The texture to bind the matrix for
  38767. * @param uniformBuffer The uniform buffer receivin the data
  38768. * @param key The chanel key "diffuse", "specular"... used in the shader
  38769. */
  38770. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38771. var matrix = texture.getTextureMatrix();
  38772. if (!matrix.isIdentity(true)) {
  38773. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38774. }
  38775. };
  38776. /**
  38777. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38778. * @param mesh defines the current mesh
  38779. * @param scene defines the current scene
  38780. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38781. * @param pointsCloud defines if point cloud rendering has to be turned on
  38782. * @param fogEnabled defines if fog has to be turned on
  38783. * @param alphaTest defines if alpha testing has to be turned on
  38784. * @param defines defines the current list of defines
  38785. */
  38786. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38787. if (defines._areMiscDirty) {
  38788. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38789. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38790. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38791. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38792. defines["ALPHATEST"] = alphaTest;
  38793. }
  38794. };
  38795. /**
  38796. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38797. * @param scene defines the current scene
  38798. * @param engine defines the current engine
  38799. * @param defines specifies the list of active defines
  38800. * @param useInstances defines if instances have to be turned on
  38801. * @param useClipPlane defines if clip plane have to be turned on
  38802. */
  38803. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38804. if (useClipPlane === void 0) { useClipPlane = null; }
  38805. var changed = false;
  38806. if (useClipPlane == null) {
  38807. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38808. }
  38809. if (defines["CLIPPLANE"] !== useClipPlane) {
  38810. defines["CLIPPLANE"] = useClipPlane;
  38811. changed = true;
  38812. }
  38813. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38814. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38815. changed = true;
  38816. }
  38817. if (defines["INSTANCES"] !== useInstances) {
  38818. defines["INSTANCES"] = useInstances;
  38819. changed = true;
  38820. }
  38821. if (changed) {
  38822. defines.markAsUnprocessed();
  38823. }
  38824. };
  38825. /**
  38826. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38827. * @param mesh The mesh containing the geometry data we will draw
  38828. * @param defines The defines to update
  38829. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38830. * @param useBones Precise whether bones should be used or not (override mesh info)
  38831. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38832. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38833. * @returns false if defines are considered not dirty and have not been checked
  38834. */
  38835. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38836. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38837. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38838. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38839. return false;
  38840. }
  38841. defines._normals = defines._needNormals;
  38842. defines._uvs = defines._needUVs;
  38843. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38844. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38845. defines["TANGENT"] = true;
  38846. }
  38847. if (defines._needUVs) {
  38848. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38849. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38850. }
  38851. else {
  38852. defines["UV1"] = false;
  38853. defines["UV2"] = false;
  38854. }
  38855. if (useVertexColor) {
  38856. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38857. defines["VERTEXCOLOR"] = hasVertexColors;
  38858. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38859. }
  38860. if (useBones) {
  38861. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38862. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38863. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38864. }
  38865. else {
  38866. defines["NUM_BONE_INFLUENCERS"] = 0;
  38867. defines["BonesPerMesh"] = 0;
  38868. }
  38869. }
  38870. if (useMorphTargets) {
  38871. var manager = mesh.morphTargetManager;
  38872. if (manager) {
  38873. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38874. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38875. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38876. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38877. }
  38878. else {
  38879. defines["MORPHTARGETS_TANGENT"] = false;
  38880. defines["MORPHTARGETS_NORMAL"] = false;
  38881. defines["MORPHTARGETS"] = false;
  38882. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38883. }
  38884. }
  38885. return true;
  38886. };
  38887. /**
  38888. * Prepares the defines related to the light information passed in parameter
  38889. * @param scene The scene we are intending to draw
  38890. * @param mesh The mesh the effect is compiling for
  38891. * @param defines The defines to update
  38892. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38893. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38894. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38895. * @returns true if normals will be required for the rest of the effect
  38896. */
  38897. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38898. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38899. if (disableLighting === void 0) { disableLighting = false; }
  38900. if (!defines._areLightsDirty) {
  38901. return defines._needNormals;
  38902. }
  38903. var lightIndex = 0;
  38904. var needNormals = false;
  38905. var needRebuild = false;
  38906. var lightmapMode = false;
  38907. var shadowEnabled = false;
  38908. var specularEnabled = false;
  38909. if (scene.lightsEnabled && !disableLighting) {
  38910. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38911. var light = _a[_i];
  38912. needNormals = true;
  38913. if (defines["LIGHT" + lightIndex] === undefined) {
  38914. needRebuild = true;
  38915. }
  38916. defines["LIGHT" + lightIndex] = true;
  38917. defines["SPOTLIGHT" + lightIndex] = false;
  38918. defines["HEMILIGHT" + lightIndex] = false;
  38919. defines["POINTLIGHT" + lightIndex] = false;
  38920. defines["DIRLIGHT" + lightIndex] = false;
  38921. var type;
  38922. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38923. type = "SPOTLIGHT" + lightIndex;
  38924. var spotLight = light;
  38925. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38926. }
  38927. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38928. type = "HEMILIGHT" + lightIndex;
  38929. }
  38930. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38931. type = "POINTLIGHT" + lightIndex;
  38932. }
  38933. else {
  38934. type = "DIRLIGHT" + lightIndex;
  38935. }
  38936. defines[type] = true;
  38937. // Specular
  38938. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38939. specularEnabled = true;
  38940. }
  38941. // Shadows
  38942. defines["SHADOW" + lightIndex] = false;
  38943. defines["SHADOWPCF" + lightIndex] = false;
  38944. defines["SHADOWPCSS" + lightIndex] = false;
  38945. defines["SHADOWPOISSON" + lightIndex] = false;
  38946. defines["SHADOWESM" + lightIndex] = false;
  38947. defines["SHADOWCUBE" + lightIndex] = false;
  38948. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  38949. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  38950. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38951. var shadowGenerator = light.getShadowGenerator();
  38952. if (shadowGenerator) {
  38953. shadowEnabled = true;
  38954. shadowGenerator.prepareDefines(defines, lightIndex);
  38955. }
  38956. }
  38957. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38958. lightmapMode = true;
  38959. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38960. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38961. }
  38962. else {
  38963. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38964. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38965. }
  38966. lightIndex++;
  38967. if (lightIndex === maxSimultaneousLights)
  38968. break;
  38969. }
  38970. }
  38971. defines["SPECULARTERM"] = specularEnabled;
  38972. defines["SHADOWS"] = shadowEnabled;
  38973. // Resetting all other lights if any
  38974. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38975. if (defines["LIGHT" + index] !== undefined) {
  38976. defines["LIGHT" + index] = false;
  38977. defines["HEMILIGHT" + lightIndex] = false;
  38978. defines["POINTLIGHT" + lightIndex] = false;
  38979. defines["DIRLIGHT" + lightIndex] = false;
  38980. defines["SPOTLIGHT" + lightIndex] = false;
  38981. defines["SHADOW" + lightIndex] = false;
  38982. }
  38983. }
  38984. var caps = scene.getEngine().getCaps();
  38985. if (defines["SHADOWFLOAT"] === undefined) {
  38986. needRebuild = true;
  38987. }
  38988. defines["SHADOWFLOAT"] = shadowEnabled &&
  38989. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38990. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38991. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38992. if (needRebuild) {
  38993. defines.rebuild();
  38994. }
  38995. return needNormals;
  38996. };
  38997. /**
  38998. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38999. * that won t be acctive due to defines being turned off.
  39000. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39001. * @param samplersList The samplers list
  39002. * @param defines The defines helping in the list generation
  39003. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39004. */
  39005. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39006. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39007. var uniformsList;
  39008. var uniformBuffersList = null;
  39009. if (uniformsListOrOptions.uniformsNames) {
  39010. var options = uniformsListOrOptions;
  39011. uniformsList = options.uniformsNames;
  39012. uniformBuffersList = options.uniformBuffersNames;
  39013. samplersList = options.samplers;
  39014. defines = options.defines;
  39015. maxSimultaneousLights = options.maxSimultaneousLights;
  39016. }
  39017. else {
  39018. uniformsList = uniformsListOrOptions;
  39019. if (!samplersList) {
  39020. samplersList = [];
  39021. }
  39022. }
  39023. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39024. if (!defines["LIGHT" + lightIndex]) {
  39025. break;
  39026. }
  39027. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39028. if (uniformBuffersList) {
  39029. uniformBuffersList.push("Light" + lightIndex);
  39030. }
  39031. samplersList.push("shadowSampler" + lightIndex);
  39032. samplersList.push("depthSampler" + lightIndex);
  39033. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39034. samplersList.push("projectionLightSampler" + lightIndex);
  39035. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39036. }
  39037. }
  39038. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39039. uniformsList.push("morphTargetInfluences");
  39040. }
  39041. };
  39042. /**
  39043. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39044. * @param defines The defines to update while falling back
  39045. * @param fallbacks The authorized effect fallbacks
  39046. * @param maxSimultaneousLights The maximum number of lights allowed
  39047. * @param rank the current rank of the Effect
  39048. * @returns The newly affected rank
  39049. */
  39050. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39051. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39052. if (rank === void 0) { rank = 0; }
  39053. var lightFallbackRank = 0;
  39054. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39055. if (!defines["LIGHT" + lightIndex]) {
  39056. break;
  39057. }
  39058. if (lightIndex > 0) {
  39059. lightFallbackRank = rank + lightIndex;
  39060. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39061. }
  39062. if (!defines["SHADOWS"]) {
  39063. if (defines["SHADOW" + lightIndex]) {
  39064. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39065. }
  39066. if (defines["SHADOWPCF" + lightIndex]) {
  39067. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39068. }
  39069. if (defines["SHADOWPCSS" + lightIndex]) {
  39070. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39071. }
  39072. if (defines["SHADOWPOISSON" + lightIndex]) {
  39073. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39074. }
  39075. if (defines["SHADOWESM" + lightIndex]) {
  39076. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39077. }
  39078. }
  39079. }
  39080. return lightFallbackRank++;
  39081. };
  39082. /**
  39083. * Prepares the list of attributes required for morph targets according to the effect defines.
  39084. * @param attribs The current list of supported attribs
  39085. * @param mesh The mesh to prepare the morph targets attributes for
  39086. * @param defines The current Defines of the effect
  39087. */
  39088. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39089. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39090. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39091. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39092. var manager = mesh.morphTargetManager;
  39093. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39094. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39095. for (var index = 0; index < influencers; index++) {
  39096. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39097. if (normal) {
  39098. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39099. }
  39100. if (tangent) {
  39101. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39102. }
  39103. if (attribs.length > maxAttributesCount) {
  39104. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39105. }
  39106. }
  39107. }
  39108. };
  39109. /**
  39110. * Prepares the list of attributes required for bones according to the effect defines.
  39111. * @param attribs The current list of supported attribs
  39112. * @param mesh The mesh to prepare the bones attributes for
  39113. * @param defines The current Defines of the effect
  39114. * @param fallbacks The current efffect fallback strategy
  39115. */
  39116. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39117. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39118. fallbacks.addCPUSkinningFallback(0, mesh);
  39119. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39120. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39121. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39122. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39123. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39124. }
  39125. }
  39126. };
  39127. /**
  39128. * Prepares the list of attributes required for instances according to the effect defines.
  39129. * @param attribs The current list of supported attribs
  39130. * @param defines The current Defines of the effect
  39131. */
  39132. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39133. if (defines["INSTANCES"]) {
  39134. attribs.push("world0");
  39135. attribs.push("world1");
  39136. attribs.push("world2");
  39137. attribs.push("world3");
  39138. }
  39139. };
  39140. /**
  39141. * Binds the light shadow information to the effect for the given mesh.
  39142. * @param light The light containing the generator
  39143. * @param scene The scene the lights belongs to
  39144. * @param mesh The mesh we are binding the information to render
  39145. * @param lightIndex The light index in the effect used to render the mesh
  39146. * @param effect The effect we are binding the data to
  39147. */
  39148. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39149. if (light.shadowEnabled && mesh.receiveShadows) {
  39150. var shadowGenerator = light.getShadowGenerator();
  39151. if (shadowGenerator) {
  39152. shadowGenerator.bindShadowLight(lightIndex, effect);
  39153. }
  39154. }
  39155. };
  39156. /**
  39157. * Binds the light information to the effect.
  39158. * @param light The light containing the generator
  39159. * @param effect The effect we are binding the data to
  39160. * @param lightIndex The light index in the effect used to render
  39161. */
  39162. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39163. light.transferToEffect(effect, lightIndex + "");
  39164. };
  39165. /**
  39166. * Binds the lights information from the scene to the effect for the given mesh.
  39167. * @param scene The scene the lights belongs to
  39168. * @param mesh The mesh we are binding the information to render
  39169. * @param effect The effect we are binding the data to
  39170. * @param defines The generated defines for the effect
  39171. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39172. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39173. */
  39174. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39175. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39176. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39177. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39178. for (var i = 0; i < len; i++) {
  39179. var light = mesh._lightSources[i];
  39180. var iAsString = i.toString();
  39181. var scaledIntensity = light.getScaledIntensity();
  39182. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39183. MaterialHelper.BindLightProperties(light, effect, i);
  39184. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39185. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39186. if (defines["SPECULARTERM"]) {
  39187. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39188. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39189. }
  39190. // Shadows
  39191. if (scene.shadowsEnabled) {
  39192. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39193. }
  39194. light._uniformBuffer.update();
  39195. }
  39196. };
  39197. /**
  39198. * Binds the fog information from the scene to the effect for the given mesh.
  39199. * @param scene The scene the lights belongs to
  39200. * @param mesh The mesh we are binding the information to render
  39201. * @param effect The effect we are binding the data to
  39202. */
  39203. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39204. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39205. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39206. effect.setColor3("vFogColor", scene.fogColor);
  39207. }
  39208. };
  39209. /**
  39210. * Binds the bones information from the mesh to the effect.
  39211. * @param mesh The mesh we are binding the information to render
  39212. * @param effect The effect we are binding the data to
  39213. */
  39214. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39215. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39216. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39217. if (matrices && effect) {
  39218. effect.setMatrices("mBones", matrices);
  39219. }
  39220. }
  39221. };
  39222. /**
  39223. * Binds the morph targets information from the mesh to the effect.
  39224. * @param abstractMesh The mesh we are binding the information to render
  39225. * @param effect The effect we are binding the data to
  39226. */
  39227. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39228. var manager = abstractMesh.morphTargetManager;
  39229. if (!abstractMesh || !manager) {
  39230. return;
  39231. }
  39232. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39233. };
  39234. /**
  39235. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39236. * @param defines The generated defines used in the effect
  39237. * @param effect The effect we are binding the data to
  39238. * @param scene The scene we are willing to render with logarithmic scale for
  39239. */
  39240. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39241. if (defines["LOGARITHMICDEPTH"]) {
  39242. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39243. }
  39244. };
  39245. /**
  39246. * Binds the clip plane information from the scene to the effect.
  39247. * @param scene The scene the clip plane information are extracted from
  39248. * @param effect The effect we are binding the data to
  39249. */
  39250. MaterialHelper.BindClipPlane = function (effect, scene) {
  39251. if (scene.clipPlane) {
  39252. var clipPlane = scene.clipPlane;
  39253. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39254. }
  39255. };
  39256. return MaterialHelper;
  39257. }());
  39258. BABYLON.MaterialHelper = MaterialHelper;
  39259. })(BABYLON || (BABYLON = {}));
  39260. //# sourceMappingURL=babylon.materialHelper.js.map
  39261. var BABYLON;
  39262. (function (BABYLON) {
  39263. var PushMaterial = /** @class */ (function (_super) {
  39264. __extends(PushMaterial, _super);
  39265. function PushMaterial(name, scene) {
  39266. var _this = _super.call(this, name, scene) || this;
  39267. _this._normalMatrix = new BABYLON.Matrix();
  39268. _this.storeEffectOnSubMeshes = true;
  39269. return _this;
  39270. }
  39271. PushMaterial.prototype.getEffect = function () {
  39272. return this._activeEffect;
  39273. };
  39274. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39275. if (!mesh) {
  39276. return false;
  39277. }
  39278. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39279. return true;
  39280. }
  39281. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39282. };
  39283. /**
  39284. * Binds the given world matrix to the active effect
  39285. *
  39286. * @param world the matrix to bind
  39287. */
  39288. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39289. this._activeEffect.setMatrix("world", world);
  39290. };
  39291. /**
  39292. * Binds the given normal matrix to the active effect
  39293. *
  39294. * @param normalMatrix the matrix to bind
  39295. */
  39296. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39297. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39298. };
  39299. PushMaterial.prototype.bind = function (world, mesh) {
  39300. if (!mesh) {
  39301. return;
  39302. }
  39303. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39304. };
  39305. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39306. if (effect === void 0) { effect = null; }
  39307. _super.prototype._afterBind.call(this, mesh);
  39308. this.getScene()._cachedEffect = effect;
  39309. };
  39310. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39311. if (visibility === void 0) { visibility = 1; }
  39312. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39313. };
  39314. return PushMaterial;
  39315. }(BABYLON.Material));
  39316. BABYLON.PushMaterial = PushMaterial;
  39317. })(BABYLON || (BABYLON = {}));
  39318. //# sourceMappingURL=babylon.pushMaterial.js.map
  39319. var BABYLON;
  39320. (function (BABYLON) {
  39321. /** @ignore */
  39322. var StandardMaterialDefines = /** @class */ (function (_super) {
  39323. __extends(StandardMaterialDefines, _super);
  39324. function StandardMaterialDefines() {
  39325. var _this = _super.call(this) || this;
  39326. _this.MAINUV1 = false;
  39327. _this.MAINUV2 = false;
  39328. _this.DIFFUSE = false;
  39329. _this.DIFFUSEDIRECTUV = 0;
  39330. _this.AMBIENT = false;
  39331. _this.AMBIENTDIRECTUV = 0;
  39332. _this.OPACITY = false;
  39333. _this.OPACITYDIRECTUV = 0;
  39334. _this.OPACITYRGB = false;
  39335. _this.REFLECTION = false;
  39336. _this.EMISSIVE = false;
  39337. _this.EMISSIVEDIRECTUV = 0;
  39338. _this.SPECULAR = false;
  39339. _this.SPECULARDIRECTUV = 0;
  39340. _this.BUMP = false;
  39341. _this.BUMPDIRECTUV = 0;
  39342. _this.PARALLAX = false;
  39343. _this.PARALLAXOCCLUSION = false;
  39344. _this.SPECULAROVERALPHA = false;
  39345. _this.CLIPPLANE = false;
  39346. _this.ALPHATEST = false;
  39347. _this.DEPTHPREPASS = false;
  39348. _this.ALPHAFROMDIFFUSE = false;
  39349. _this.POINTSIZE = false;
  39350. _this.FOG = false;
  39351. _this.SPECULARTERM = false;
  39352. _this.DIFFUSEFRESNEL = false;
  39353. _this.OPACITYFRESNEL = false;
  39354. _this.REFLECTIONFRESNEL = false;
  39355. _this.REFRACTIONFRESNEL = false;
  39356. _this.EMISSIVEFRESNEL = false;
  39357. _this.FRESNEL = false;
  39358. _this.NORMAL = false;
  39359. _this.UV1 = false;
  39360. _this.UV2 = false;
  39361. _this.VERTEXCOLOR = false;
  39362. _this.VERTEXALPHA = false;
  39363. _this.NUM_BONE_INFLUENCERS = 0;
  39364. _this.BonesPerMesh = 0;
  39365. _this.INSTANCES = false;
  39366. _this.GLOSSINESS = false;
  39367. _this.ROUGHNESS = false;
  39368. _this.EMISSIVEASILLUMINATION = false;
  39369. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39370. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39371. _this.LIGHTMAP = false;
  39372. _this.LIGHTMAPDIRECTUV = 0;
  39373. _this.OBJECTSPACE_NORMALMAP = false;
  39374. _this.USELIGHTMAPASSHADOWMAP = false;
  39375. _this.REFLECTIONMAP_3D = false;
  39376. _this.REFLECTIONMAP_SPHERICAL = false;
  39377. _this.REFLECTIONMAP_PLANAR = false;
  39378. _this.REFLECTIONMAP_CUBIC = false;
  39379. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39380. _this.REFLECTIONMAP_PROJECTION = false;
  39381. _this.REFLECTIONMAP_SKYBOX = false;
  39382. _this.REFLECTIONMAP_EXPLICIT = false;
  39383. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39384. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39385. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39386. _this.INVERTCUBICMAP = false;
  39387. _this.LOGARITHMICDEPTH = false;
  39388. _this.REFRACTION = false;
  39389. _this.REFRACTIONMAP_3D = false;
  39390. _this.REFLECTIONOVERALPHA = false;
  39391. _this.TWOSIDEDLIGHTING = false;
  39392. _this.SHADOWFLOAT = false;
  39393. _this.MORPHTARGETS = false;
  39394. _this.MORPHTARGETS_NORMAL = false;
  39395. _this.MORPHTARGETS_TANGENT = false;
  39396. _this.NUM_MORPH_INFLUENCERS = 0;
  39397. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39398. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39399. _this.IMAGEPROCESSING = false;
  39400. _this.VIGNETTE = false;
  39401. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39402. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39403. _this.TONEMAPPING = false;
  39404. _this.CONTRAST = false;
  39405. _this.COLORCURVES = false;
  39406. _this.COLORGRADING = false;
  39407. _this.COLORGRADING3D = false;
  39408. _this.SAMPLER3DGREENDEPTH = false;
  39409. _this.SAMPLER3DBGRMAP = false;
  39410. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39411. _this.EXPOSURE = false;
  39412. _this.GRAIN = false;
  39413. _this.rebuild();
  39414. return _this;
  39415. }
  39416. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39417. var modes = [
  39418. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39419. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39420. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39421. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39422. ];
  39423. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39424. var mode = modes_1[_i];
  39425. this[mode] = (mode === modeToEnable);
  39426. }
  39427. };
  39428. return StandardMaterialDefines;
  39429. }(BABYLON.MaterialDefines));
  39430. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39431. var StandardMaterial = /** @class */ (function (_super) {
  39432. __extends(StandardMaterial, _super);
  39433. function StandardMaterial(name, scene) {
  39434. var _this = _super.call(this, name, scene) || this;
  39435. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39436. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39437. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39438. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39439. _this.specularPower = 64;
  39440. _this._useAlphaFromDiffuseTexture = false;
  39441. _this._useEmissiveAsIllumination = false;
  39442. _this._linkEmissiveWithDiffuse = false;
  39443. _this._useSpecularOverAlpha = false;
  39444. _this._useReflectionOverAlpha = false;
  39445. _this._disableLighting = false;
  39446. _this._useObjectSpaceNormalMap = false;
  39447. _this._useParallax = false;
  39448. _this._useParallaxOcclusion = false;
  39449. _this.parallaxScaleBias = 0.05;
  39450. _this._roughness = 0;
  39451. _this.indexOfRefraction = 0.98;
  39452. _this.invertRefractionY = true;
  39453. _this._useLightmapAsShadowmap = false;
  39454. _this._useReflectionFresnelFromSpecular = false;
  39455. _this._useGlossinessFromSpecularMapAlpha = false;
  39456. _this._maxSimultaneousLights = 4;
  39457. /**
  39458. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39459. */
  39460. _this._invertNormalMapX = false;
  39461. /**
  39462. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39463. */
  39464. _this._invertNormalMapY = false;
  39465. /**
  39466. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39467. */
  39468. _this._twoSidedLighting = false;
  39469. _this._renderTargets = new BABYLON.SmartArray(16);
  39470. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39471. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39472. // Setup the default processing configuration to the scene.
  39473. _this._attachImageProcessingConfiguration(null);
  39474. _this.getRenderTargetTextures = function () {
  39475. _this._renderTargets.reset();
  39476. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39477. _this._renderTargets.push(_this._reflectionTexture);
  39478. }
  39479. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39480. _this._renderTargets.push(_this._refractionTexture);
  39481. }
  39482. return _this._renderTargets;
  39483. };
  39484. return _this;
  39485. }
  39486. ;
  39487. ;
  39488. ;
  39489. ;
  39490. ;
  39491. ;
  39492. ;
  39493. ;
  39494. ;
  39495. ;
  39496. ;
  39497. ;
  39498. ;
  39499. ;
  39500. ;
  39501. ;
  39502. ;
  39503. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39504. /**
  39505. * Gets the image processing configuration used either in this material.
  39506. */
  39507. get: function () {
  39508. return this._imageProcessingConfiguration;
  39509. },
  39510. /**
  39511. * Sets the Default image processing configuration used either in the this material.
  39512. *
  39513. * If sets to null, the scene one is in use.
  39514. */
  39515. set: function (value) {
  39516. this._attachImageProcessingConfiguration(value);
  39517. // Ensure the effect will be rebuilt.
  39518. this._markAllSubMeshesAsTexturesDirty();
  39519. },
  39520. enumerable: true,
  39521. configurable: true
  39522. });
  39523. /**
  39524. * Attaches a new image processing configuration to the Standard Material.
  39525. * @param configuration
  39526. */
  39527. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39528. var _this = this;
  39529. if (configuration === this._imageProcessingConfiguration) {
  39530. return;
  39531. }
  39532. // Detaches observer.
  39533. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39534. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39535. }
  39536. // Pick the scene configuration if needed.
  39537. if (!configuration) {
  39538. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39539. }
  39540. else {
  39541. this._imageProcessingConfiguration = configuration;
  39542. }
  39543. // Attaches observer.
  39544. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39545. _this._markAllSubMeshesAsImageProcessingDirty();
  39546. });
  39547. };
  39548. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39549. /**
  39550. * Gets wether the color curves effect is enabled.
  39551. */
  39552. get: function () {
  39553. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39554. },
  39555. /**
  39556. * Sets wether the color curves effect is enabled.
  39557. */
  39558. set: function (value) {
  39559. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39560. },
  39561. enumerable: true,
  39562. configurable: true
  39563. });
  39564. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39565. /**
  39566. * Gets wether the color grading effect is enabled.
  39567. */
  39568. get: function () {
  39569. return this.imageProcessingConfiguration.colorGradingEnabled;
  39570. },
  39571. /**
  39572. * Gets wether the color grading effect is enabled.
  39573. */
  39574. set: function (value) {
  39575. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39576. },
  39577. enumerable: true,
  39578. configurable: true
  39579. });
  39580. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39581. /**
  39582. * Gets wether tonemapping is enabled or not.
  39583. */
  39584. get: function () {
  39585. return this._imageProcessingConfiguration.toneMappingEnabled;
  39586. },
  39587. /**
  39588. * Sets wether tonemapping is enabled or not
  39589. */
  39590. set: function (value) {
  39591. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39592. },
  39593. enumerable: true,
  39594. configurable: true
  39595. });
  39596. ;
  39597. ;
  39598. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39599. /**
  39600. * The camera exposure used on this material.
  39601. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39602. * This corresponds to a photographic exposure.
  39603. */
  39604. get: function () {
  39605. return this._imageProcessingConfiguration.exposure;
  39606. },
  39607. /**
  39608. * The camera exposure used on this material.
  39609. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39610. * This corresponds to a photographic exposure.
  39611. */
  39612. set: function (value) {
  39613. this._imageProcessingConfiguration.exposure = value;
  39614. },
  39615. enumerable: true,
  39616. configurable: true
  39617. });
  39618. ;
  39619. ;
  39620. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39621. /**
  39622. * Gets The camera contrast used on this material.
  39623. */
  39624. get: function () {
  39625. return this._imageProcessingConfiguration.contrast;
  39626. },
  39627. /**
  39628. * Sets The camera contrast used on this material.
  39629. */
  39630. set: function (value) {
  39631. this._imageProcessingConfiguration.contrast = value;
  39632. },
  39633. enumerable: true,
  39634. configurable: true
  39635. });
  39636. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39637. /**
  39638. * Gets the Color Grading 2D Lookup Texture.
  39639. */
  39640. get: function () {
  39641. return this._imageProcessingConfiguration.colorGradingTexture;
  39642. },
  39643. /**
  39644. * Sets the Color Grading 2D Lookup Texture.
  39645. */
  39646. set: function (value) {
  39647. this._imageProcessingConfiguration.colorGradingTexture = value;
  39648. },
  39649. enumerable: true,
  39650. configurable: true
  39651. });
  39652. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39653. /**
  39654. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39655. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39656. * 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;
  39657. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39658. */
  39659. get: function () {
  39660. return this._imageProcessingConfiguration.colorCurves;
  39661. },
  39662. /**
  39663. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39664. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39665. * 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;
  39666. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39667. */
  39668. set: function (value) {
  39669. this._imageProcessingConfiguration.colorCurves = value;
  39670. },
  39671. enumerable: true,
  39672. configurable: true
  39673. });
  39674. StandardMaterial.prototype.getClassName = function () {
  39675. return "StandardMaterial";
  39676. };
  39677. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39678. get: function () {
  39679. return this._useLogarithmicDepth;
  39680. },
  39681. set: function (value) {
  39682. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39683. this._markAllSubMeshesAsMiscDirty();
  39684. },
  39685. enumerable: true,
  39686. configurable: true
  39687. });
  39688. StandardMaterial.prototype.needAlphaBlending = function () {
  39689. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39690. };
  39691. StandardMaterial.prototype.needAlphaTesting = function () {
  39692. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39693. };
  39694. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39695. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39696. };
  39697. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39698. return this._diffuseTexture;
  39699. };
  39700. /**
  39701. * Child classes can use it to update shaders
  39702. */
  39703. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39704. if (useInstances === void 0) { useInstances = false; }
  39705. if (subMesh.effect && this.isFrozen) {
  39706. if (this._wasPreviouslyReady && subMesh.effect) {
  39707. return true;
  39708. }
  39709. }
  39710. if (!subMesh._materialDefines) {
  39711. subMesh._materialDefines = new StandardMaterialDefines();
  39712. }
  39713. var scene = this.getScene();
  39714. var defines = subMesh._materialDefines;
  39715. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39716. if (defines._renderId === scene.getRenderId()) {
  39717. return true;
  39718. }
  39719. }
  39720. var engine = scene.getEngine();
  39721. // Lights
  39722. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39723. // Textures
  39724. if (defines._areTexturesDirty) {
  39725. defines._needUVs = false;
  39726. defines.MAINUV1 = false;
  39727. defines.MAINUV2 = false;
  39728. if (scene.texturesEnabled) {
  39729. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39730. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39731. return false;
  39732. }
  39733. else {
  39734. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39735. }
  39736. }
  39737. else {
  39738. defines.DIFFUSE = false;
  39739. }
  39740. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39741. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39742. return false;
  39743. }
  39744. else {
  39745. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39746. }
  39747. }
  39748. else {
  39749. defines.AMBIENT = false;
  39750. }
  39751. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39752. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39753. return false;
  39754. }
  39755. else {
  39756. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39757. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39758. }
  39759. }
  39760. else {
  39761. defines.OPACITY = false;
  39762. }
  39763. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39764. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39765. return false;
  39766. }
  39767. else {
  39768. defines._needNormals = true;
  39769. defines.REFLECTION = true;
  39770. defines.ROUGHNESS = (this._roughness > 0);
  39771. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39772. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39773. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39774. switch (this._reflectionTexture.coordinatesMode) {
  39775. case BABYLON.Texture.CUBIC_MODE:
  39776. case BABYLON.Texture.INVCUBIC_MODE:
  39777. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39778. break;
  39779. case BABYLON.Texture.EXPLICIT_MODE:
  39780. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39781. break;
  39782. case BABYLON.Texture.PLANAR_MODE:
  39783. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39784. break;
  39785. case BABYLON.Texture.PROJECTION_MODE:
  39786. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39787. break;
  39788. case BABYLON.Texture.SKYBOX_MODE:
  39789. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39790. break;
  39791. case BABYLON.Texture.SPHERICAL_MODE:
  39792. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39793. break;
  39794. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39795. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39796. break;
  39797. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39798. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39799. break;
  39800. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39801. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39802. break;
  39803. }
  39804. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39805. }
  39806. }
  39807. else {
  39808. defines.REFLECTION = false;
  39809. }
  39810. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39811. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39812. return false;
  39813. }
  39814. else {
  39815. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39816. }
  39817. }
  39818. else {
  39819. defines.EMISSIVE = false;
  39820. }
  39821. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39822. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39823. return false;
  39824. }
  39825. else {
  39826. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39827. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39828. }
  39829. }
  39830. else {
  39831. defines.LIGHTMAP = false;
  39832. }
  39833. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39834. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39835. return false;
  39836. }
  39837. else {
  39838. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39839. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39840. }
  39841. }
  39842. else {
  39843. defines.SPECULAR = false;
  39844. }
  39845. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39846. // Bump texure can not be not blocking.
  39847. if (!this._bumpTexture.isReady()) {
  39848. return false;
  39849. }
  39850. else {
  39851. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39852. defines.PARALLAX = this._useParallax;
  39853. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39854. }
  39855. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39856. }
  39857. else {
  39858. defines.BUMP = false;
  39859. }
  39860. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39861. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39862. return false;
  39863. }
  39864. else {
  39865. defines._needUVs = true;
  39866. defines.REFRACTION = true;
  39867. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39868. }
  39869. }
  39870. else {
  39871. defines.REFRACTION = false;
  39872. }
  39873. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39874. }
  39875. else {
  39876. defines.DIFFUSE = false;
  39877. defines.AMBIENT = false;
  39878. defines.OPACITY = false;
  39879. defines.REFLECTION = false;
  39880. defines.EMISSIVE = false;
  39881. defines.LIGHTMAP = false;
  39882. defines.BUMP = false;
  39883. defines.REFRACTION = false;
  39884. }
  39885. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39886. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39887. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39888. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39889. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39890. }
  39891. if (defines._areImageProcessingDirty) {
  39892. if (!this._imageProcessingConfiguration.isReady()) {
  39893. return false;
  39894. }
  39895. this._imageProcessingConfiguration.prepareDefines(defines);
  39896. }
  39897. if (defines._areFresnelDirty) {
  39898. if (StandardMaterial.FresnelEnabled) {
  39899. // Fresnel
  39900. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39901. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39902. this._reflectionFresnelParameters) {
  39903. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39904. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39905. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39906. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39907. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39908. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39909. defines._needNormals = true;
  39910. defines.FRESNEL = true;
  39911. }
  39912. }
  39913. else {
  39914. defines.FRESNEL = false;
  39915. }
  39916. }
  39917. // Misc.
  39918. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39919. // Attribs
  39920. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39921. // Values that need to be evaluated on every frame
  39922. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39923. // Get correct effect
  39924. if (defines.isDirty) {
  39925. defines.markAsProcessed();
  39926. scene.resetCachedMaterial();
  39927. // Fallbacks
  39928. var fallbacks = new BABYLON.EffectFallbacks();
  39929. if (defines.REFLECTION) {
  39930. fallbacks.addFallback(0, "REFLECTION");
  39931. }
  39932. if (defines.SPECULAR) {
  39933. fallbacks.addFallback(0, "SPECULAR");
  39934. }
  39935. if (defines.BUMP) {
  39936. fallbacks.addFallback(0, "BUMP");
  39937. }
  39938. if (defines.PARALLAX) {
  39939. fallbacks.addFallback(1, "PARALLAX");
  39940. }
  39941. if (defines.PARALLAXOCCLUSION) {
  39942. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39943. }
  39944. if (defines.SPECULAROVERALPHA) {
  39945. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39946. }
  39947. if (defines.FOG) {
  39948. fallbacks.addFallback(1, "FOG");
  39949. }
  39950. if (defines.POINTSIZE) {
  39951. fallbacks.addFallback(0, "POINTSIZE");
  39952. }
  39953. if (defines.LOGARITHMICDEPTH) {
  39954. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39955. }
  39956. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39957. if (defines.SPECULARTERM) {
  39958. fallbacks.addFallback(0, "SPECULARTERM");
  39959. }
  39960. if (defines.DIFFUSEFRESNEL) {
  39961. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39962. }
  39963. if (defines.OPACITYFRESNEL) {
  39964. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39965. }
  39966. if (defines.REFLECTIONFRESNEL) {
  39967. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39968. }
  39969. if (defines.EMISSIVEFRESNEL) {
  39970. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39971. }
  39972. if (defines.FRESNEL) {
  39973. fallbacks.addFallback(4, "FRESNEL");
  39974. }
  39975. //Attributes
  39976. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39977. if (defines.NORMAL) {
  39978. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39979. }
  39980. if (defines.UV1) {
  39981. attribs.push(BABYLON.VertexBuffer.UVKind);
  39982. }
  39983. if (defines.UV2) {
  39984. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39985. }
  39986. if (defines.VERTEXCOLOR) {
  39987. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39988. }
  39989. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39990. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39991. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39992. var shaderName = "default";
  39993. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39994. "vFogInfos", "vFogColor", "pointSize",
  39995. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39996. "mBones",
  39997. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39998. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39999. "vReflectionPosition", "vReflectionSize",
  40000. "logarithmicDepthConstant", "vTangentSpaceParams"
  40001. ];
  40002. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40003. var uniformBuffers = ["Material", "Scene"];
  40004. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40005. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40006. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40007. uniformsNames: uniforms,
  40008. uniformBuffersNames: uniformBuffers,
  40009. samplers: samplers,
  40010. defines: defines,
  40011. maxSimultaneousLights: this._maxSimultaneousLights
  40012. });
  40013. if (this.customShaderNameResolve) {
  40014. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40015. }
  40016. var join = defines.toString();
  40017. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40018. attributes: attribs,
  40019. uniformsNames: uniforms,
  40020. uniformBuffersNames: uniformBuffers,
  40021. samplers: samplers,
  40022. defines: join,
  40023. fallbacks: fallbacks,
  40024. onCompiled: this.onCompiled,
  40025. onError: this.onError,
  40026. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40027. }, engine), defines);
  40028. this.buildUniformLayout();
  40029. }
  40030. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40031. return false;
  40032. }
  40033. defines._renderId = scene.getRenderId();
  40034. this._wasPreviouslyReady = true;
  40035. return true;
  40036. };
  40037. StandardMaterial.prototype.buildUniformLayout = function () {
  40038. // Order is important !
  40039. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40040. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40041. this._uniformBuffer.addUniform("opacityParts", 4);
  40042. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40043. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40044. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40045. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40046. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40047. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40048. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40049. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40050. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40051. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40052. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40053. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40054. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40055. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40056. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40057. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40058. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40059. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40060. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40061. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40062. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40063. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40064. this._uniformBuffer.addUniform("specularMatrix", 16);
  40065. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40066. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40067. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40068. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40069. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40070. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40071. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40072. this._uniformBuffer.addUniform("pointSize", 1);
  40073. this._uniformBuffer.create();
  40074. };
  40075. StandardMaterial.prototype.unbind = function () {
  40076. if (this._activeEffect) {
  40077. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40078. this._activeEffect.setTexture("reflection2DSampler", null);
  40079. }
  40080. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40081. this._activeEffect.setTexture("refraction2DSampler", null);
  40082. }
  40083. }
  40084. _super.prototype.unbind.call(this);
  40085. };
  40086. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40087. var scene = this.getScene();
  40088. var defines = subMesh._materialDefines;
  40089. if (!defines) {
  40090. return;
  40091. }
  40092. var effect = subMesh.effect;
  40093. if (!effect) {
  40094. return;
  40095. }
  40096. this._activeEffect = effect;
  40097. // Matrices
  40098. this.bindOnlyWorldMatrix(world);
  40099. // Normal Matrix
  40100. if (defines.OBJECTSPACE_NORMALMAP) {
  40101. world.toNormalMatrix(this._normalMatrix);
  40102. this.bindOnlyNormalMatrix(this._normalMatrix);
  40103. }
  40104. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40105. // Bones
  40106. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40107. if (mustRebind) {
  40108. this._uniformBuffer.bindToEffect(effect, "Material");
  40109. this.bindViewProjection(effect);
  40110. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40111. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40112. // Fresnel
  40113. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40114. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40115. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40116. }
  40117. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40118. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40119. }
  40120. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40121. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40122. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40123. }
  40124. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40125. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40126. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40127. }
  40128. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40129. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40130. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40131. }
  40132. }
  40133. // Textures
  40134. if (scene.texturesEnabled) {
  40135. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40136. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40137. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40138. }
  40139. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40140. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40141. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40142. }
  40143. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40144. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40145. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40146. }
  40147. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40148. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40149. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40150. if (this._reflectionTexture.boundingBoxSize) {
  40151. var cubeTexture = this._reflectionTexture;
  40152. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40153. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40154. }
  40155. }
  40156. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40157. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40158. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40159. }
  40160. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40161. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40162. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40163. }
  40164. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40165. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40166. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40167. }
  40168. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40169. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40170. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40171. if (scene._mirroredCameraPosition) {
  40172. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40173. }
  40174. else {
  40175. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40176. }
  40177. }
  40178. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40179. var depth = 1.0;
  40180. if (!this._refractionTexture.isCube) {
  40181. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40182. if (this._refractionTexture.depth) {
  40183. depth = this._refractionTexture.depth;
  40184. }
  40185. }
  40186. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40187. }
  40188. }
  40189. // Point size
  40190. if (this.pointsCloud) {
  40191. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40192. }
  40193. if (defines.SPECULARTERM) {
  40194. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40195. }
  40196. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40197. // Diffuse
  40198. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40199. }
  40200. // Textures
  40201. if (scene.texturesEnabled) {
  40202. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40203. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40204. }
  40205. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40206. effect.setTexture("ambientSampler", this._ambientTexture);
  40207. }
  40208. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40209. effect.setTexture("opacitySampler", this._opacityTexture);
  40210. }
  40211. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40212. if (this._reflectionTexture.isCube) {
  40213. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40214. }
  40215. else {
  40216. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40217. }
  40218. }
  40219. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40220. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40221. }
  40222. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40223. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40224. }
  40225. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40226. effect.setTexture("specularSampler", this._specularTexture);
  40227. }
  40228. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40229. effect.setTexture("bumpSampler", this._bumpTexture);
  40230. }
  40231. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40232. var depth = 1.0;
  40233. if (this._refractionTexture.isCube) {
  40234. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40235. }
  40236. else {
  40237. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40238. }
  40239. }
  40240. }
  40241. // Clip plane
  40242. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40243. // Colors
  40244. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40245. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40246. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40247. }
  40248. if (mustRebind || !this.isFrozen) {
  40249. // Lights
  40250. if (scene.lightsEnabled && !this._disableLighting) {
  40251. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40252. }
  40253. // View
  40254. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40255. this.bindView(effect);
  40256. }
  40257. // Fog
  40258. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40259. // Morph targets
  40260. if (defines.NUM_MORPH_INFLUENCERS) {
  40261. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40262. }
  40263. // Log. depth
  40264. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40265. // image processing
  40266. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40267. this._imageProcessingConfiguration.bind(this._activeEffect);
  40268. }
  40269. }
  40270. this._uniformBuffer.update();
  40271. this._afterBind(mesh, this._activeEffect);
  40272. };
  40273. StandardMaterial.prototype.getAnimatables = function () {
  40274. var results = [];
  40275. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40276. results.push(this._diffuseTexture);
  40277. }
  40278. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40279. results.push(this._ambientTexture);
  40280. }
  40281. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40282. results.push(this._opacityTexture);
  40283. }
  40284. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40285. results.push(this._reflectionTexture);
  40286. }
  40287. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40288. results.push(this._emissiveTexture);
  40289. }
  40290. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40291. results.push(this._specularTexture);
  40292. }
  40293. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40294. results.push(this._bumpTexture);
  40295. }
  40296. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40297. results.push(this._lightmapTexture);
  40298. }
  40299. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40300. results.push(this._refractionTexture);
  40301. }
  40302. return results;
  40303. };
  40304. StandardMaterial.prototype.getActiveTextures = function () {
  40305. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40306. if (this._diffuseTexture) {
  40307. activeTextures.push(this._diffuseTexture);
  40308. }
  40309. if (this._ambientTexture) {
  40310. activeTextures.push(this._ambientTexture);
  40311. }
  40312. if (this._opacityTexture) {
  40313. activeTextures.push(this._opacityTexture);
  40314. }
  40315. if (this._reflectionTexture) {
  40316. activeTextures.push(this._reflectionTexture);
  40317. }
  40318. if (this._emissiveTexture) {
  40319. activeTextures.push(this._emissiveTexture);
  40320. }
  40321. if (this._specularTexture) {
  40322. activeTextures.push(this._specularTexture);
  40323. }
  40324. if (this._bumpTexture) {
  40325. activeTextures.push(this._bumpTexture);
  40326. }
  40327. if (this._lightmapTexture) {
  40328. activeTextures.push(this._lightmapTexture);
  40329. }
  40330. if (this._refractionTexture) {
  40331. activeTextures.push(this._refractionTexture);
  40332. }
  40333. return activeTextures;
  40334. };
  40335. StandardMaterial.prototype.hasTexture = function (texture) {
  40336. if (_super.prototype.hasTexture.call(this, texture)) {
  40337. return true;
  40338. }
  40339. if (this._diffuseTexture === texture) {
  40340. return true;
  40341. }
  40342. if (this._ambientTexture === texture) {
  40343. return true;
  40344. }
  40345. if (this._opacityTexture === texture) {
  40346. return true;
  40347. }
  40348. if (this._reflectionTexture === texture) {
  40349. return true;
  40350. }
  40351. if (this._emissiveTexture === texture) {
  40352. return true;
  40353. }
  40354. if (this._specularTexture === texture) {
  40355. return true;
  40356. }
  40357. if (this._bumpTexture === texture) {
  40358. return true;
  40359. }
  40360. if (this._lightmapTexture === texture) {
  40361. return true;
  40362. }
  40363. if (this._refractionTexture === texture) {
  40364. return true;
  40365. }
  40366. return false;
  40367. };
  40368. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40369. if (forceDisposeTextures) {
  40370. if (this._diffuseTexture) {
  40371. this._diffuseTexture.dispose();
  40372. }
  40373. if (this._ambientTexture) {
  40374. this._ambientTexture.dispose();
  40375. }
  40376. if (this._opacityTexture) {
  40377. this._opacityTexture.dispose();
  40378. }
  40379. if (this._reflectionTexture) {
  40380. this._reflectionTexture.dispose();
  40381. }
  40382. if (this._emissiveTexture) {
  40383. this._emissiveTexture.dispose();
  40384. }
  40385. if (this._specularTexture) {
  40386. this._specularTexture.dispose();
  40387. }
  40388. if (this._bumpTexture) {
  40389. this._bumpTexture.dispose();
  40390. }
  40391. if (this._lightmapTexture) {
  40392. this._lightmapTexture.dispose();
  40393. }
  40394. if (this._refractionTexture) {
  40395. this._refractionTexture.dispose();
  40396. }
  40397. }
  40398. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40399. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40400. }
  40401. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40402. };
  40403. StandardMaterial.prototype.clone = function (name) {
  40404. var _this = this;
  40405. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40406. result.name = name;
  40407. result.id = name;
  40408. return result;
  40409. };
  40410. StandardMaterial.prototype.serialize = function () {
  40411. return BABYLON.SerializationHelper.Serialize(this);
  40412. };
  40413. // Statics
  40414. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40415. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40416. };
  40417. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40418. get: function () {
  40419. return StandardMaterial._DiffuseTextureEnabled;
  40420. },
  40421. set: function (value) {
  40422. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40423. return;
  40424. }
  40425. StandardMaterial._DiffuseTextureEnabled = value;
  40426. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40427. },
  40428. enumerable: true,
  40429. configurable: true
  40430. });
  40431. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40432. get: function () {
  40433. return StandardMaterial._AmbientTextureEnabled;
  40434. },
  40435. set: function (value) {
  40436. if (StandardMaterial._AmbientTextureEnabled === value) {
  40437. return;
  40438. }
  40439. StandardMaterial._AmbientTextureEnabled = value;
  40440. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40441. },
  40442. enumerable: true,
  40443. configurable: true
  40444. });
  40445. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40446. get: function () {
  40447. return StandardMaterial._OpacityTextureEnabled;
  40448. },
  40449. set: function (value) {
  40450. if (StandardMaterial._OpacityTextureEnabled === value) {
  40451. return;
  40452. }
  40453. StandardMaterial._OpacityTextureEnabled = value;
  40454. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40455. },
  40456. enumerable: true,
  40457. configurable: true
  40458. });
  40459. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40460. get: function () {
  40461. return StandardMaterial._ReflectionTextureEnabled;
  40462. },
  40463. set: function (value) {
  40464. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40465. return;
  40466. }
  40467. StandardMaterial._ReflectionTextureEnabled = value;
  40468. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40469. },
  40470. enumerable: true,
  40471. configurable: true
  40472. });
  40473. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40474. get: function () {
  40475. return StandardMaterial._EmissiveTextureEnabled;
  40476. },
  40477. set: function (value) {
  40478. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40479. return;
  40480. }
  40481. StandardMaterial._EmissiveTextureEnabled = value;
  40482. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40483. },
  40484. enumerable: true,
  40485. configurable: true
  40486. });
  40487. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40488. get: function () {
  40489. return StandardMaterial._SpecularTextureEnabled;
  40490. },
  40491. set: function (value) {
  40492. if (StandardMaterial._SpecularTextureEnabled === value) {
  40493. return;
  40494. }
  40495. StandardMaterial._SpecularTextureEnabled = value;
  40496. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40497. },
  40498. enumerable: true,
  40499. configurable: true
  40500. });
  40501. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40502. get: function () {
  40503. return StandardMaterial._BumpTextureEnabled;
  40504. },
  40505. set: function (value) {
  40506. if (StandardMaterial._BumpTextureEnabled === value) {
  40507. return;
  40508. }
  40509. StandardMaterial._BumpTextureEnabled = value;
  40510. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40511. },
  40512. enumerable: true,
  40513. configurable: true
  40514. });
  40515. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40516. get: function () {
  40517. return StandardMaterial._LightmapTextureEnabled;
  40518. },
  40519. set: function (value) {
  40520. if (StandardMaterial._LightmapTextureEnabled === value) {
  40521. return;
  40522. }
  40523. StandardMaterial._LightmapTextureEnabled = value;
  40524. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40525. },
  40526. enumerable: true,
  40527. configurable: true
  40528. });
  40529. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40530. get: function () {
  40531. return StandardMaterial._RefractionTextureEnabled;
  40532. },
  40533. set: function (value) {
  40534. if (StandardMaterial._RefractionTextureEnabled === value) {
  40535. return;
  40536. }
  40537. StandardMaterial._RefractionTextureEnabled = value;
  40538. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40539. },
  40540. enumerable: true,
  40541. configurable: true
  40542. });
  40543. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40544. get: function () {
  40545. return StandardMaterial._ColorGradingTextureEnabled;
  40546. },
  40547. set: function (value) {
  40548. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40549. return;
  40550. }
  40551. StandardMaterial._ColorGradingTextureEnabled = value;
  40552. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40553. },
  40554. enumerable: true,
  40555. configurable: true
  40556. });
  40557. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40558. get: function () {
  40559. return StandardMaterial._FresnelEnabled;
  40560. },
  40561. set: function (value) {
  40562. if (StandardMaterial._FresnelEnabled === value) {
  40563. return;
  40564. }
  40565. StandardMaterial._FresnelEnabled = value;
  40566. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40567. },
  40568. enumerable: true,
  40569. configurable: true
  40570. });
  40571. // Flags used to enable or disable a type of texture for all Standard Materials
  40572. StandardMaterial._DiffuseTextureEnabled = true;
  40573. StandardMaterial._AmbientTextureEnabled = true;
  40574. StandardMaterial._OpacityTextureEnabled = true;
  40575. StandardMaterial._ReflectionTextureEnabled = true;
  40576. StandardMaterial._EmissiveTextureEnabled = true;
  40577. StandardMaterial._SpecularTextureEnabled = true;
  40578. StandardMaterial._BumpTextureEnabled = true;
  40579. StandardMaterial._LightmapTextureEnabled = true;
  40580. StandardMaterial._RefractionTextureEnabled = true;
  40581. StandardMaterial._ColorGradingTextureEnabled = true;
  40582. StandardMaterial._FresnelEnabled = true;
  40583. __decorate([
  40584. BABYLON.serializeAsTexture("diffuseTexture")
  40585. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40586. __decorate([
  40587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40588. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40589. __decorate([
  40590. BABYLON.serializeAsTexture("ambientTexture")
  40591. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40592. __decorate([
  40593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40594. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40595. __decorate([
  40596. BABYLON.serializeAsTexture("opacityTexture")
  40597. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40598. __decorate([
  40599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40600. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40601. __decorate([
  40602. BABYLON.serializeAsTexture("reflectionTexture")
  40603. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40604. __decorate([
  40605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40606. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40607. __decorate([
  40608. BABYLON.serializeAsTexture("emissiveTexture")
  40609. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40610. __decorate([
  40611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40612. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40613. __decorate([
  40614. BABYLON.serializeAsTexture("specularTexture")
  40615. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40616. __decorate([
  40617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40618. ], StandardMaterial.prototype, "specularTexture", void 0);
  40619. __decorate([
  40620. BABYLON.serializeAsTexture("bumpTexture")
  40621. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40622. __decorate([
  40623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40624. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40625. __decorate([
  40626. BABYLON.serializeAsTexture("lightmapTexture")
  40627. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40628. __decorate([
  40629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40630. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40631. __decorate([
  40632. BABYLON.serializeAsTexture("refractionTexture")
  40633. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40634. __decorate([
  40635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40636. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40637. __decorate([
  40638. BABYLON.serializeAsColor3("ambient")
  40639. ], StandardMaterial.prototype, "ambientColor", void 0);
  40640. __decorate([
  40641. BABYLON.serializeAsColor3("diffuse")
  40642. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40643. __decorate([
  40644. BABYLON.serializeAsColor3("specular")
  40645. ], StandardMaterial.prototype, "specularColor", void 0);
  40646. __decorate([
  40647. BABYLON.serializeAsColor3("emissive")
  40648. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40649. __decorate([
  40650. BABYLON.serialize()
  40651. ], StandardMaterial.prototype, "specularPower", void 0);
  40652. __decorate([
  40653. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40654. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40655. __decorate([
  40656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40657. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40658. __decorate([
  40659. BABYLON.serialize("useEmissiveAsIllumination")
  40660. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40661. __decorate([
  40662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40663. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40664. __decorate([
  40665. BABYLON.serialize("linkEmissiveWithDiffuse")
  40666. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40667. __decorate([
  40668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40669. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40670. __decorate([
  40671. BABYLON.serialize("useSpecularOverAlpha")
  40672. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40673. __decorate([
  40674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40675. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40676. __decorate([
  40677. BABYLON.serialize("useReflectionOverAlpha")
  40678. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40679. __decorate([
  40680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40681. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40682. __decorate([
  40683. BABYLON.serialize("disableLighting")
  40684. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40685. __decorate([
  40686. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40687. ], StandardMaterial.prototype, "disableLighting", void 0);
  40688. __decorate([
  40689. BABYLON.serialize("useObjectSpaceNormalMap")
  40690. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40691. __decorate([
  40692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40693. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40694. __decorate([
  40695. BABYLON.serialize("useParallax")
  40696. ], StandardMaterial.prototype, "_useParallax", void 0);
  40697. __decorate([
  40698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40699. ], StandardMaterial.prototype, "useParallax", void 0);
  40700. __decorate([
  40701. BABYLON.serialize("useParallaxOcclusion")
  40702. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40703. __decorate([
  40704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40705. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40706. __decorate([
  40707. BABYLON.serialize()
  40708. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40709. __decorate([
  40710. BABYLON.serialize("roughness")
  40711. ], StandardMaterial.prototype, "_roughness", void 0);
  40712. __decorate([
  40713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40714. ], StandardMaterial.prototype, "roughness", void 0);
  40715. __decorate([
  40716. BABYLON.serialize()
  40717. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40718. __decorate([
  40719. BABYLON.serialize()
  40720. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40721. __decorate([
  40722. BABYLON.serialize("useLightmapAsShadowmap")
  40723. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40724. __decorate([
  40725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40726. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40727. __decorate([
  40728. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40729. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40730. __decorate([
  40731. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40732. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40733. __decorate([
  40734. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40735. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40736. __decorate([
  40737. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40738. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40739. __decorate([
  40740. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40741. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40742. __decorate([
  40743. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40744. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40745. __decorate([
  40746. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40747. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40748. __decorate([
  40749. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40750. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40751. __decorate([
  40752. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40753. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40754. __decorate([
  40755. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40756. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40757. __decorate([
  40758. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40759. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40760. __decorate([
  40761. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40762. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40763. __decorate([
  40764. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40765. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40766. __decorate([
  40767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40768. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40769. __decorate([
  40770. BABYLON.serialize("maxSimultaneousLights")
  40771. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40772. __decorate([
  40773. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40774. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40775. __decorate([
  40776. BABYLON.serialize("invertNormalMapX")
  40777. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40778. __decorate([
  40779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40780. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40781. __decorate([
  40782. BABYLON.serialize("invertNormalMapY")
  40783. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40784. __decorate([
  40785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40786. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40787. __decorate([
  40788. BABYLON.serialize("twoSidedLighting")
  40789. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40790. __decorate([
  40791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40792. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40793. __decorate([
  40794. BABYLON.serialize()
  40795. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40796. return StandardMaterial;
  40797. }(BABYLON.PushMaterial));
  40798. BABYLON.StandardMaterial = StandardMaterial;
  40799. })(BABYLON || (BABYLON = {}));
  40800. //# sourceMappingURL=babylon.standardMaterial.js.map
  40801. var BABYLON;
  40802. (function (BABYLON) {
  40803. /**
  40804. * Manages the defines for the PBR Material.
  40805. */
  40806. var PBRMaterialDefines = /** @class */ (function (_super) {
  40807. __extends(PBRMaterialDefines, _super);
  40808. /**
  40809. * Initializes the PBR Material defines.
  40810. */
  40811. function PBRMaterialDefines() {
  40812. var _this = _super.call(this) || this;
  40813. _this.PBR = true;
  40814. _this.MAINUV1 = false;
  40815. _this.MAINUV2 = false;
  40816. _this.UV1 = false;
  40817. _this.UV2 = false;
  40818. _this.ALBEDO = false;
  40819. _this.ALBEDODIRECTUV = 0;
  40820. _this.VERTEXCOLOR = false;
  40821. _this.AMBIENT = false;
  40822. _this.AMBIENTDIRECTUV = 0;
  40823. _this.AMBIENTINGRAYSCALE = false;
  40824. _this.OPACITY = false;
  40825. _this.VERTEXALPHA = false;
  40826. _this.OPACITYDIRECTUV = 0;
  40827. _this.OPACITYRGB = false;
  40828. _this.ALPHATEST = false;
  40829. _this.DEPTHPREPASS = false;
  40830. _this.ALPHABLEND = false;
  40831. _this.ALPHAFROMALBEDO = false;
  40832. _this.ALPHATESTVALUE = 0.5;
  40833. _this.SPECULAROVERALPHA = false;
  40834. _this.RADIANCEOVERALPHA = false;
  40835. _this.ALPHAFRESNEL = false;
  40836. _this.LINEARALPHAFRESNEL = false;
  40837. _this.PREMULTIPLYALPHA = false;
  40838. _this.EMISSIVE = false;
  40839. _this.EMISSIVEDIRECTUV = 0;
  40840. _this.REFLECTIVITY = false;
  40841. _this.REFLECTIVITYDIRECTUV = 0;
  40842. _this.SPECULARTERM = false;
  40843. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40844. _this.MICROSURFACEAUTOMATIC = false;
  40845. _this.LODBASEDMICROSFURACE = false;
  40846. _this.MICROSURFACEMAP = false;
  40847. _this.MICROSURFACEMAPDIRECTUV = 0;
  40848. _this.METALLICWORKFLOW = false;
  40849. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40850. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40851. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40852. _this.AOSTOREINMETALMAPRED = false;
  40853. _this.ENVIRONMENTBRDF = false;
  40854. _this.NORMAL = false;
  40855. _this.TANGENT = false;
  40856. _this.BUMP = false;
  40857. _this.BUMPDIRECTUV = 0;
  40858. _this.OBJECTSPACE_NORMALMAP = false;
  40859. _this.PARALLAX = false;
  40860. _this.PARALLAXOCCLUSION = false;
  40861. _this.NORMALXYSCALE = true;
  40862. _this.LIGHTMAP = false;
  40863. _this.LIGHTMAPDIRECTUV = 0;
  40864. _this.USELIGHTMAPASSHADOWMAP = false;
  40865. _this.GAMMALIGHTMAP = false;
  40866. _this.REFLECTION = false;
  40867. _this.REFLECTIONMAP_3D = false;
  40868. _this.REFLECTIONMAP_SPHERICAL = false;
  40869. _this.REFLECTIONMAP_PLANAR = false;
  40870. _this.REFLECTIONMAP_CUBIC = false;
  40871. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40872. _this.REFLECTIONMAP_PROJECTION = false;
  40873. _this.REFLECTIONMAP_SKYBOX = false;
  40874. _this.REFLECTIONMAP_EXPLICIT = false;
  40875. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40876. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40877. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40878. _this.INVERTCUBICMAP = false;
  40879. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40880. _this.USESPHERICALINVERTEX = false;
  40881. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40882. _this.LODINREFLECTIONALPHA = false;
  40883. _this.GAMMAREFLECTION = false;
  40884. _this.RADIANCEOCCLUSION = false;
  40885. _this.HORIZONOCCLUSION = false;
  40886. _this.REFRACTION = false;
  40887. _this.REFRACTIONMAP_3D = false;
  40888. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40889. _this.LODINREFRACTIONALPHA = false;
  40890. _this.GAMMAREFRACTION = false;
  40891. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40892. _this.INSTANCES = false;
  40893. _this.NUM_BONE_INFLUENCERS = 0;
  40894. _this.BonesPerMesh = 0;
  40895. _this.NONUNIFORMSCALING = false;
  40896. _this.MORPHTARGETS = false;
  40897. _this.MORPHTARGETS_NORMAL = false;
  40898. _this.MORPHTARGETS_TANGENT = false;
  40899. _this.NUM_MORPH_INFLUENCERS = 0;
  40900. _this.IMAGEPROCESSING = false;
  40901. _this.VIGNETTE = false;
  40902. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40903. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40904. _this.TONEMAPPING = false;
  40905. _this.CONTRAST = false;
  40906. _this.COLORCURVES = false;
  40907. _this.COLORGRADING = false;
  40908. _this.COLORGRADING3D = false;
  40909. _this.SAMPLER3DGREENDEPTH = false;
  40910. _this.SAMPLER3DBGRMAP = false;
  40911. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40912. _this.EXPOSURE = false;
  40913. _this.GRAIN = false;
  40914. _this.USEPHYSICALLIGHTFALLOFF = false;
  40915. _this.TWOSIDEDLIGHTING = false;
  40916. _this.SHADOWFLOAT = false;
  40917. _this.CLIPPLANE = false;
  40918. _this.POINTSIZE = false;
  40919. _this.FOG = false;
  40920. _this.LOGARITHMICDEPTH = false;
  40921. _this.FORCENORMALFORWARD = false;
  40922. _this.rebuild();
  40923. return _this;
  40924. }
  40925. /**
  40926. * Resets the PBR Material defines.
  40927. */
  40928. PBRMaterialDefines.prototype.reset = function () {
  40929. _super.prototype.reset.call(this);
  40930. this.ALPHATESTVALUE = 0.5;
  40931. this.PBR = true;
  40932. };
  40933. return PBRMaterialDefines;
  40934. }(BABYLON.MaterialDefines));
  40935. /**
  40936. * The Physically based material base class of BJS.
  40937. *
  40938. * This offers the main features of a standard PBR material.
  40939. * For more information, please refer to the documentation :
  40940. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40941. */
  40942. var PBRBaseMaterial = /** @class */ (function (_super) {
  40943. __extends(PBRBaseMaterial, _super);
  40944. /**
  40945. * Instantiates a new PBRMaterial instance.
  40946. *
  40947. * @param name The material name
  40948. * @param scene The scene the material will be use in.
  40949. */
  40950. function PBRBaseMaterial(name, scene) {
  40951. var _this = _super.call(this, name, scene) || this;
  40952. /**
  40953. * Intensity of the direct lights e.g. the four lights available in your scene.
  40954. * This impacts both the direct diffuse and specular highlights.
  40955. */
  40956. _this._directIntensity = 1.0;
  40957. /**
  40958. * Intensity of the emissive part of the material.
  40959. * This helps controlling the emissive effect without modifying the emissive color.
  40960. */
  40961. _this._emissiveIntensity = 1.0;
  40962. /**
  40963. * Intensity of the environment e.g. how much the environment will light the object
  40964. * either through harmonics for rough material or through the refelction for shiny ones.
  40965. */
  40966. _this._environmentIntensity = 1.0;
  40967. /**
  40968. * This is a special control allowing the reduction of the specular highlights coming from the
  40969. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40970. */
  40971. _this._specularIntensity = 1.0;
  40972. /**
  40973. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40974. */
  40975. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40976. /**
  40977. * Debug Control allowing disabling the bump map on this material.
  40978. */
  40979. _this._disableBumpMap = false;
  40980. /**
  40981. * AKA Occlusion Texture Intensity in other nomenclature.
  40982. */
  40983. _this._ambientTextureStrength = 1.0;
  40984. /**
  40985. * The color of a material in ambient lighting.
  40986. */
  40987. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40988. /**
  40989. * AKA Diffuse Color in other nomenclature.
  40990. */
  40991. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40992. /**
  40993. * AKA Specular Color in other nomenclature.
  40994. */
  40995. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40996. /**
  40997. * The color applied when light is reflected from a material.
  40998. */
  40999. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41000. /**
  41001. * The color applied when light is emitted from a material.
  41002. */
  41003. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41004. /**
  41005. * AKA Glossiness in other nomenclature.
  41006. */
  41007. _this._microSurface = 0.9;
  41008. /**
  41009. * source material index of refraction (IOR)' / 'destination material IOR.
  41010. */
  41011. _this._indexOfRefraction = 0.66;
  41012. /**
  41013. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41014. */
  41015. _this._invertRefractionY = false;
  41016. /**
  41017. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41018. * Materials half opaque for instance using refraction could benefit from this control.
  41019. */
  41020. _this._linkRefractionWithTransparency = false;
  41021. /**
  41022. * Specifies that the material will use the light map as a show map.
  41023. */
  41024. _this._useLightmapAsShadowmap = false;
  41025. /**
  41026. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41027. * makes the reflect vector face the model (under horizon).
  41028. */
  41029. _this._useHorizonOcclusion = true;
  41030. /**
  41031. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41032. * too much the area relying on ambient texture to define their ambient occlusion.
  41033. */
  41034. _this._useRadianceOcclusion = true;
  41035. /**
  41036. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41037. */
  41038. _this._useAlphaFromAlbedoTexture = false;
  41039. /**
  41040. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41041. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41042. */
  41043. _this._useSpecularOverAlpha = true;
  41044. /**
  41045. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41046. */
  41047. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41048. /**
  41049. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41050. */
  41051. _this._useRoughnessFromMetallicTextureAlpha = true;
  41052. /**
  41053. * Specifies if the metallic texture contains the roughness information in its green channel.
  41054. */
  41055. _this._useRoughnessFromMetallicTextureGreen = false;
  41056. /**
  41057. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41058. */
  41059. _this._useMetallnessFromMetallicTextureBlue = false;
  41060. /**
  41061. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41062. */
  41063. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41064. /**
  41065. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41066. */
  41067. _this._useAmbientInGrayScale = false;
  41068. /**
  41069. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41070. * The material will try to infer what glossiness each pixel should be.
  41071. */
  41072. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41073. /**
  41074. * BJS is using an harcoded light falloff based on a manually sets up range.
  41075. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41076. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41077. */
  41078. _this._usePhysicalLightFalloff = true;
  41079. /**
  41080. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41081. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41082. */
  41083. _this._useRadianceOverAlpha = true;
  41084. /**
  41085. * Allows using an object space normal map (instead of tangent space).
  41086. */
  41087. _this._useObjectSpaceNormalMap = false;
  41088. /**
  41089. * Allows using the bump map in parallax mode.
  41090. */
  41091. _this._useParallax = false;
  41092. /**
  41093. * Allows using the bump map in parallax occlusion mode.
  41094. */
  41095. _this._useParallaxOcclusion = false;
  41096. /**
  41097. * Controls the scale bias of the parallax mode.
  41098. */
  41099. _this._parallaxScaleBias = 0.05;
  41100. /**
  41101. * If sets to true, disables all the lights affecting the material.
  41102. */
  41103. _this._disableLighting = false;
  41104. /**
  41105. * Number of Simultaneous lights allowed on the material.
  41106. */
  41107. _this._maxSimultaneousLights = 4;
  41108. /**
  41109. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41110. */
  41111. _this._invertNormalMapX = false;
  41112. /**
  41113. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41114. */
  41115. _this._invertNormalMapY = false;
  41116. /**
  41117. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41118. */
  41119. _this._twoSidedLighting = false;
  41120. /**
  41121. * Defines the alpha limits in alpha test mode.
  41122. */
  41123. _this._alphaCutOff = 0.4;
  41124. /**
  41125. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41126. */
  41127. _this._forceAlphaTest = false;
  41128. /**
  41129. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41130. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41131. */
  41132. _this._useAlphaFresnel = false;
  41133. /**
  41134. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41135. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41136. */
  41137. _this._useLinearAlphaFresnel = false;
  41138. /**
  41139. * The transparency mode of the material.
  41140. */
  41141. _this._transparencyMode = null;
  41142. /**
  41143. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41144. * from cos thetav and roughness:
  41145. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41146. */
  41147. _this._environmentBRDFTexture = null;
  41148. /**
  41149. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41150. */
  41151. _this._forceIrradianceInFragment = false;
  41152. /**
  41153. * Force normal to face away from face.
  41154. */
  41155. _this._forceNormalForward = false;
  41156. /**
  41157. * Stores the available render targets.
  41158. */
  41159. _this._renderTargets = new BABYLON.SmartArray(16);
  41160. /**
  41161. * Sets the global ambient color for the material used in lighting calculations.
  41162. */
  41163. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41164. // Setup the default processing configuration to the scene.
  41165. _this._attachImageProcessingConfiguration(null);
  41166. _this.getRenderTargetTextures = function () {
  41167. _this._renderTargets.reset();
  41168. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41169. _this._renderTargets.push(_this._reflectionTexture);
  41170. }
  41171. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41172. _this._renderTargets.push(_this._refractionTexture);
  41173. }
  41174. return _this._renderTargets;
  41175. };
  41176. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41177. return _this;
  41178. }
  41179. /**
  41180. * Attaches a new image processing configuration to the PBR Material.
  41181. * @param configuration
  41182. */
  41183. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41184. var _this = this;
  41185. if (configuration === this._imageProcessingConfiguration) {
  41186. return;
  41187. }
  41188. // Detaches observer.
  41189. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41190. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41191. }
  41192. // Pick the scene configuration if needed.
  41193. if (!configuration) {
  41194. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41195. }
  41196. else {
  41197. this._imageProcessingConfiguration = configuration;
  41198. }
  41199. // Attaches observer.
  41200. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41201. _this._markAllSubMeshesAsImageProcessingDirty();
  41202. });
  41203. };
  41204. /**
  41205. * Gets the name of the material class.
  41206. */
  41207. PBRBaseMaterial.prototype.getClassName = function () {
  41208. return "PBRBaseMaterial";
  41209. };
  41210. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41211. /**
  41212. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41213. */
  41214. get: function () {
  41215. return this._useLogarithmicDepth;
  41216. },
  41217. /**
  41218. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41219. */
  41220. set: function (value) {
  41221. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41222. },
  41223. enumerable: true,
  41224. configurable: true
  41225. });
  41226. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41227. /**
  41228. * Gets the current transparency mode.
  41229. */
  41230. get: function () {
  41231. return this._transparencyMode;
  41232. },
  41233. /**
  41234. * Sets the transparency mode of the material.
  41235. */
  41236. set: function (value) {
  41237. if (this._transparencyMode === value) {
  41238. return;
  41239. }
  41240. this._transparencyMode = value;
  41241. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41242. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41243. },
  41244. enumerable: true,
  41245. configurable: true
  41246. });
  41247. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41248. /**
  41249. * Returns true if alpha blending should be disabled.
  41250. */
  41251. get: function () {
  41252. return (this._linkRefractionWithTransparency ||
  41253. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41254. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41255. },
  41256. enumerable: true,
  41257. configurable: true
  41258. });
  41259. /**
  41260. * Specifies whether or not this material should be rendered in alpha blend mode.
  41261. */
  41262. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41263. if (this._disableAlphaBlending) {
  41264. return false;
  41265. }
  41266. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41267. };
  41268. /**
  41269. * Specifies if the mesh will require alpha blending.
  41270. * @param mesh - BJS mesh.
  41271. */
  41272. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41273. if (this._disableAlphaBlending) {
  41274. return false;
  41275. }
  41276. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41277. };
  41278. /**
  41279. * Specifies whether or not this material should be rendered in alpha test mode.
  41280. */
  41281. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41282. if (this._forceAlphaTest) {
  41283. return true;
  41284. }
  41285. if (this._linkRefractionWithTransparency) {
  41286. return false;
  41287. }
  41288. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41289. };
  41290. /**
  41291. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41292. */
  41293. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41294. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41295. };
  41296. /**
  41297. * Gets the texture used for the alpha test.
  41298. */
  41299. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41300. return this._albedoTexture;
  41301. };
  41302. /**
  41303. * Specifies that the submesh is ready to be used.
  41304. * @param mesh - BJS mesh.
  41305. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41306. * @param useInstances - Specifies that instances should be used.
  41307. * @returns - boolean indicating that the submesh is ready or not.
  41308. */
  41309. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41310. if (subMesh.effect && this.isFrozen) {
  41311. if (this._wasPreviouslyReady) {
  41312. return true;
  41313. }
  41314. }
  41315. if (!subMesh._materialDefines) {
  41316. subMesh._materialDefines = new PBRMaterialDefines();
  41317. }
  41318. var defines = subMesh._materialDefines;
  41319. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41320. if (defines._renderId === this.getScene().getRenderId()) {
  41321. return true;
  41322. }
  41323. }
  41324. var scene = this.getScene();
  41325. var engine = scene.getEngine();
  41326. if (defines._areTexturesDirty) {
  41327. if (scene.texturesEnabled) {
  41328. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41329. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41330. return false;
  41331. }
  41332. }
  41333. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41334. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41335. return false;
  41336. }
  41337. }
  41338. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41339. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41340. return false;
  41341. }
  41342. }
  41343. var reflectionTexture = this._getReflectionTexture();
  41344. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41345. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41346. return false;
  41347. }
  41348. }
  41349. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41350. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41351. return false;
  41352. }
  41353. }
  41354. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41355. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41356. return false;
  41357. }
  41358. }
  41359. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41360. if (this._metallicTexture) {
  41361. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41362. return false;
  41363. }
  41364. }
  41365. else if (this._reflectivityTexture) {
  41366. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41367. return false;
  41368. }
  41369. }
  41370. if (this._microSurfaceTexture) {
  41371. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41372. return false;
  41373. }
  41374. }
  41375. }
  41376. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41377. // Bump texture cannot be not blocking.
  41378. if (!this._bumpTexture.isReady()) {
  41379. return false;
  41380. }
  41381. }
  41382. var refractionTexture = this._getRefractionTexture();
  41383. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41384. if (!refractionTexture.isReadyOrNotBlocking()) {
  41385. return false;
  41386. }
  41387. }
  41388. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41389. // This is blocking.
  41390. if (!this._environmentBRDFTexture.isReady()) {
  41391. return false;
  41392. }
  41393. }
  41394. }
  41395. }
  41396. if (defines._areImageProcessingDirty) {
  41397. if (!this._imageProcessingConfiguration.isReady()) {
  41398. return false;
  41399. }
  41400. }
  41401. if (!engine.getCaps().standardDerivatives) {
  41402. var bufferMesh = null;
  41403. if (mesh.getClassName() === "InstancedMesh") {
  41404. bufferMesh = mesh.sourceMesh;
  41405. }
  41406. else if (mesh.getClassName() === "Mesh") {
  41407. bufferMesh = mesh;
  41408. }
  41409. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41410. bufferMesh.createNormals(true);
  41411. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41412. }
  41413. }
  41414. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41415. if (effect) {
  41416. scene.resetCachedMaterial();
  41417. subMesh.setEffect(effect, defines);
  41418. this.buildUniformLayout();
  41419. }
  41420. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41421. return false;
  41422. }
  41423. defines._renderId = scene.getRenderId();
  41424. this._wasPreviouslyReady = true;
  41425. return true;
  41426. };
  41427. /**
  41428. * Specifies if the material uses metallic roughness workflow.
  41429. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41430. */
  41431. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41432. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41433. return true;
  41434. }
  41435. return false;
  41436. };
  41437. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41438. if (onCompiled === void 0) { onCompiled = null; }
  41439. if (onError === void 0) { onError = null; }
  41440. if (useInstances === void 0) { useInstances = null; }
  41441. if (useClipPlane === void 0) { useClipPlane = null; }
  41442. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41443. if (!defines.isDirty) {
  41444. return null;
  41445. }
  41446. defines.markAsProcessed();
  41447. var scene = this.getScene();
  41448. var engine = scene.getEngine();
  41449. // Fallbacks
  41450. var fallbacks = new BABYLON.EffectFallbacks();
  41451. var fallbackRank = 0;
  41452. if (defines.USESPHERICALINVERTEX) {
  41453. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41454. }
  41455. if (defines.FOG) {
  41456. fallbacks.addFallback(fallbackRank, "FOG");
  41457. }
  41458. if (defines.POINTSIZE) {
  41459. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41460. }
  41461. if (defines.LOGARITHMICDEPTH) {
  41462. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41463. }
  41464. if (defines.PARALLAX) {
  41465. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41466. }
  41467. if (defines.PARALLAXOCCLUSION) {
  41468. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41469. }
  41470. if (defines.ENVIRONMENTBRDF) {
  41471. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41472. }
  41473. if (defines.TANGENT) {
  41474. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41475. }
  41476. if (defines.BUMP) {
  41477. fallbacks.addFallback(fallbackRank++, "BUMP");
  41478. }
  41479. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41480. if (defines.SPECULARTERM) {
  41481. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41482. }
  41483. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41484. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41485. }
  41486. if (defines.LIGHTMAP) {
  41487. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41488. }
  41489. if (defines.NORMAL) {
  41490. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41491. }
  41492. if (defines.AMBIENT) {
  41493. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41494. }
  41495. if (defines.EMISSIVE) {
  41496. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41497. }
  41498. if (defines.VERTEXCOLOR) {
  41499. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41500. }
  41501. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41502. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41503. }
  41504. if (defines.MORPHTARGETS) {
  41505. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41506. }
  41507. //Attributes
  41508. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41509. if (defines.NORMAL) {
  41510. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41511. }
  41512. if (defines.TANGENT) {
  41513. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41514. }
  41515. if (defines.UV1) {
  41516. attribs.push(BABYLON.VertexBuffer.UVKind);
  41517. }
  41518. if (defines.UV2) {
  41519. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41520. }
  41521. if (defines.VERTEXCOLOR) {
  41522. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41523. }
  41524. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41525. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41526. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41527. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41528. "vFogInfos", "vFogColor", "pointSize",
  41529. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41530. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41531. "mBones",
  41532. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41533. "vLightingIntensity",
  41534. "logarithmicDepthConstant",
  41535. "vSphericalX", "vSphericalY", "vSphericalZ",
  41536. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41537. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41538. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41539. "vTangentSpaceParams"
  41540. ];
  41541. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41542. "bumpSampler", "lightmapSampler", "opacitySampler",
  41543. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41544. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41545. "microSurfaceSampler", "environmentBrdfSampler"];
  41546. var uniformBuffers = ["Material", "Scene"];
  41547. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41548. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41549. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41550. uniformsNames: uniforms,
  41551. uniformBuffersNames: uniformBuffers,
  41552. samplers: samplers,
  41553. defines: defines,
  41554. maxSimultaneousLights: this._maxSimultaneousLights
  41555. });
  41556. var join = defines.toString();
  41557. return engine.createEffect("pbr", {
  41558. attributes: attribs,
  41559. uniformsNames: uniforms,
  41560. uniformBuffersNames: uniformBuffers,
  41561. samplers: samplers,
  41562. defines: join,
  41563. fallbacks: fallbacks,
  41564. onCompiled: onCompiled,
  41565. onError: onError,
  41566. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41567. }, engine);
  41568. };
  41569. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41570. if (useInstances === void 0) { useInstances = null; }
  41571. if (useClipPlane === void 0) { useClipPlane = null; }
  41572. var scene = this.getScene();
  41573. var engine = scene.getEngine();
  41574. // Lights
  41575. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41576. defines._needNormals = true;
  41577. // Textures
  41578. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41579. if (defines._areTexturesDirty) {
  41580. defines._needUVs = false;
  41581. if (scene.texturesEnabled) {
  41582. if (scene.getEngine().getCaps().textureLOD) {
  41583. defines.LODBASEDMICROSFURACE = true;
  41584. }
  41585. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41586. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41587. }
  41588. else {
  41589. defines.ALBEDO = false;
  41590. }
  41591. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41592. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41593. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41594. }
  41595. else {
  41596. defines.AMBIENT = false;
  41597. }
  41598. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41599. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41600. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41601. }
  41602. else {
  41603. defines.OPACITY = false;
  41604. }
  41605. var reflectionTexture = this._getReflectionTexture();
  41606. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41607. defines.REFLECTION = true;
  41608. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41609. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41610. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41611. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41612. defines.INVERTCUBICMAP = true;
  41613. }
  41614. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41615. switch (reflectionTexture.coordinatesMode) {
  41616. case BABYLON.Texture.CUBIC_MODE:
  41617. case BABYLON.Texture.INVCUBIC_MODE:
  41618. defines.REFLECTIONMAP_CUBIC = true;
  41619. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41620. break;
  41621. case BABYLON.Texture.EXPLICIT_MODE:
  41622. defines.REFLECTIONMAP_EXPLICIT = true;
  41623. break;
  41624. case BABYLON.Texture.PLANAR_MODE:
  41625. defines.REFLECTIONMAP_PLANAR = true;
  41626. break;
  41627. case BABYLON.Texture.PROJECTION_MODE:
  41628. defines.REFLECTIONMAP_PROJECTION = true;
  41629. break;
  41630. case BABYLON.Texture.SKYBOX_MODE:
  41631. defines.REFLECTIONMAP_SKYBOX = true;
  41632. break;
  41633. case BABYLON.Texture.SPHERICAL_MODE:
  41634. defines.REFLECTIONMAP_SPHERICAL = true;
  41635. break;
  41636. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41637. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41638. break;
  41639. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41640. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41641. break;
  41642. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41643. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41644. break;
  41645. }
  41646. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41647. if (reflectionTexture.sphericalPolynomial) {
  41648. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41649. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41650. defines.USESPHERICALINVERTEX = false;
  41651. }
  41652. else {
  41653. defines.USESPHERICALINVERTEX = true;
  41654. }
  41655. }
  41656. }
  41657. }
  41658. else {
  41659. defines.REFLECTION = false;
  41660. defines.REFLECTIONMAP_3D = false;
  41661. defines.REFLECTIONMAP_SPHERICAL = false;
  41662. defines.REFLECTIONMAP_PLANAR = false;
  41663. defines.REFLECTIONMAP_CUBIC = false;
  41664. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41665. defines.REFLECTIONMAP_PROJECTION = false;
  41666. defines.REFLECTIONMAP_SKYBOX = false;
  41667. defines.REFLECTIONMAP_EXPLICIT = false;
  41668. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41669. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41670. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41671. defines.INVERTCUBICMAP = false;
  41672. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41673. defines.USESPHERICALINVERTEX = false;
  41674. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41675. defines.LODINREFLECTIONALPHA = false;
  41676. defines.GAMMAREFLECTION = false;
  41677. }
  41678. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41679. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41680. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41681. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41682. }
  41683. else {
  41684. defines.LIGHTMAP = false;
  41685. }
  41686. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41687. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41688. }
  41689. else {
  41690. defines.EMISSIVE = false;
  41691. }
  41692. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41693. if (this._metallicTexture) {
  41694. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41695. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41696. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41697. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41698. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41699. }
  41700. else if (this._reflectivityTexture) {
  41701. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41702. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41703. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41704. }
  41705. else {
  41706. defines.REFLECTIVITY = false;
  41707. }
  41708. if (this._microSurfaceTexture) {
  41709. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41710. }
  41711. else {
  41712. defines.MICROSURFACEMAP = false;
  41713. }
  41714. }
  41715. else {
  41716. defines.REFLECTIVITY = false;
  41717. defines.MICROSURFACEMAP = false;
  41718. }
  41719. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41720. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41721. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41722. defines.PARALLAX = true;
  41723. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41724. }
  41725. else {
  41726. defines.PARALLAX = false;
  41727. }
  41728. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41729. }
  41730. else {
  41731. defines.BUMP = false;
  41732. }
  41733. var refractionTexture = this._getRefractionTexture();
  41734. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41735. defines.REFRACTION = true;
  41736. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41737. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41738. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41739. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41740. if (this._linkRefractionWithTransparency) {
  41741. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41742. }
  41743. }
  41744. else {
  41745. defines.REFRACTION = false;
  41746. }
  41747. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41748. defines.ENVIRONMENTBRDF = true;
  41749. }
  41750. else {
  41751. defines.ENVIRONMENTBRDF = false;
  41752. }
  41753. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41754. defines.ALPHAFROMALBEDO = true;
  41755. }
  41756. else {
  41757. defines.ALPHAFROMALBEDO = false;
  41758. }
  41759. }
  41760. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41761. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41762. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41763. if (!this.backFaceCulling && this._twoSidedLighting) {
  41764. defines.TWOSIDEDLIGHTING = true;
  41765. }
  41766. else {
  41767. defines.TWOSIDEDLIGHTING = false;
  41768. }
  41769. defines.ALPHATESTVALUE = this._alphaCutOff;
  41770. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41771. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41772. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41773. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41774. }
  41775. if (defines._areImageProcessingDirty) {
  41776. this._imageProcessingConfiguration.prepareDefines(defines);
  41777. }
  41778. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41779. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41780. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41781. // Misc.
  41782. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41783. // Values that need to be evaluated on every frame
  41784. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41785. // Attribs
  41786. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41787. };
  41788. /**
  41789. * Force shader compilation
  41790. */
  41791. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41792. var _this = this;
  41793. var localOptions = __assign({ clipPlane: false }, options);
  41794. var defines = new PBRMaterialDefines();
  41795. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41796. if (effect.isReady()) {
  41797. if (onCompiled) {
  41798. onCompiled(this);
  41799. }
  41800. }
  41801. else {
  41802. effect.onCompileObservable.add(function () {
  41803. if (onCompiled) {
  41804. onCompiled(_this);
  41805. }
  41806. });
  41807. }
  41808. };
  41809. /**
  41810. * Initializes the uniform buffer layout for the shader.
  41811. */
  41812. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41813. // Order is important !
  41814. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41815. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41816. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41817. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41818. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41819. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41820. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41821. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41822. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41823. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41824. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41825. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41826. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41827. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41828. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41829. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41830. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41831. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41832. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41833. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41834. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41835. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41836. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41837. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41838. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41839. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41840. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41841. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41842. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41843. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41844. this._uniformBuffer.addUniform("pointSize", 1);
  41845. this._uniformBuffer.create();
  41846. };
  41847. /**
  41848. * Unbinds the textures.
  41849. */
  41850. PBRBaseMaterial.prototype.unbind = function () {
  41851. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41852. this._uniformBuffer.setTexture("reflectionSampler", null);
  41853. }
  41854. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41855. this._uniformBuffer.setTexture("refractionSampler", null);
  41856. }
  41857. _super.prototype.unbind.call(this);
  41858. };
  41859. /**
  41860. * Binds the submesh data.
  41861. * @param world - The world matrix.
  41862. * @param mesh - The BJS mesh.
  41863. * @param subMesh - A submesh of the BJS mesh.
  41864. */
  41865. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41866. var scene = this.getScene();
  41867. var defines = subMesh._materialDefines;
  41868. if (!defines) {
  41869. return;
  41870. }
  41871. var effect = subMesh.effect;
  41872. if (!effect) {
  41873. return;
  41874. }
  41875. this._activeEffect = effect;
  41876. // Matrices
  41877. this.bindOnlyWorldMatrix(world);
  41878. // Normal Matrix
  41879. if (defines.OBJECTSPACE_NORMALMAP) {
  41880. world.toNormalMatrix(this._normalMatrix);
  41881. this.bindOnlyNormalMatrix(this._normalMatrix);
  41882. }
  41883. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41884. // Bones
  41885. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41886. var reflectionTexture = null;
  41887. if (mustRebind) {
  41888. this._uniformBuffer.bindToEffect(effect, "Material");
  41889. this.bindViewProjection(effect);
  41890. reflectionTexture = this._getReflectionTexture();
  41891. var refractionTexture = this._getRefractionTexture();
  41892. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41893. // Texture uniforms
  41894. if (scene.texturesEnabled) {
  41895. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41896. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41897. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41898. }
  41899. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41900. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41901. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41902. }
  41903. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41904. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41905. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41906. }
  41907. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41908. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41909. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41910. if (reflectionTexture.boundingBoxSize) {
  41911. var cubeTexture = reflectionTexture;
  41912. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41913. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41914. }
  41915. var polynomials = reflectionTexture.sphericalPolynomial;
  41916. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41917. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41918. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41919. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41920. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41921. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41922. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41923. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41924. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41925. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41926. }
  41927. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41928. }
  41929. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41930. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41931. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41932. }
  41933. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41934. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41935. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41936. }
  41937. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41938. if (this._metallicTexture) {
  41939. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41940. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41941. }
  41942. else if (this._reflectivityTexture) {
  41943. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41944. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41945. }
  41946. if (this._microSurfaceTexture) {
  41947. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41948. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41949. }
  41950. }
  41951. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41952. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41953. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41954. if (scene._mirroredCameraPosition) {
  41955. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41956. }
  41957. else {
  41958. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41959. }
  41960. }
  41961. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41962. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41963. var depth = 1.0;
  41964. if (!refractionTexture.isCube) {
  41965. if (refractionTexture.depth) {
  41966. depth = refractionTexture.depth;
  41967. }
  41968. }
  41969. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41970. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41971. }
  41972. }
  41973. // Point size
  41974. if (this.pointsCloud) {
  41975. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41976. }
  41977. // Colors
  41978. if (defines.METALLICWORKFLOW) {
  41979. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41980. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41981. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41982. }
  41983. else {
  41984. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41985. }
  41986. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41987. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41988. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41989. // Misc
  41990. this._lightingInfos.x = this._directIntensity;
  41991. this._lightingInfos.y = this._emissiveIntensity;
  41992. this._lightingInfos.z = this._environmentIntensity;
  41993. this._lightingInfos.w = this._specularIntensity;
  41994. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41995. }
  41996. // Textures
  41997. if (scene.texturesEnabled) {
  41998. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41999. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42000. }
  42001. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42002. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42003. }
  42004. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42005. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42006. }
  42007. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42008. if (defines.LODBASEDMICROSFURACE) {
  42009. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42010. }
  42011. else {
  42012. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42013. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42014. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42015. }
  42016. }
  42017. if (defines.ENVIRONMENTBRDF) {
  42018. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42019. }
  42020. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42021. if (defines.LODBASEDMICROSFURACE) {
  42022. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42023. }
  42024. else {
  42025. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42026. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42027. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42028. }
  42029. }
  42030. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42031. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42032. }
  42033. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42034. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42035. }
  42036. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42037. if (this._metallicTexture) {
  42038. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42039. }
  42040. else if (this._reflectivityTexture) {
  42041. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42042. }
  42043. if (this._microSurfaceTexture) {
  42044. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42045. }
  42046. }
  42047. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42048. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42049. }
  42050. }
  42051. // Clip plane
  42052. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42053. // Colors
  42054. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42055. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42056. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42057. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42058. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42059. }
  42060. if (mustRebind || !this.isFrozen) {
  42061. // Lights
  42062. if (scene.lightsEnabled && !this._disableLighting) {
  42063. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42064. }
  42065. // View
  42066. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42067. this.bindView(effect);
  42068. }
  42069. // Fog
  42070. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42071. // Morph targets
  42072. if (defines.NUM_MORPH_INFLUENCERS) {
  42073. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42074. }
  42075. // image processing
  42076. this._imageProcessingConfiguration.bind(this._activeEffect);
  42077. // Log. depth
  42078. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42079. }
  42080. this._uniformBuffer.update();
  42081. this._afterBind(mesh);
  42082. };
  42083. /**
  42084. * Returns the animatable textures.
  42085. * @returns - Array of animatable textures.
  42086. */
  42087. PBRBaseMaterial.prototype.getAnimatables = function () {
  42088. var results = [];
  42089. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42090. results.push(this._albedoTexture);
  42091. }
  42092. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42093. results.push(this._ambientTexture);
  42094. }
  42095. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42096. results.push(this._opacityTexture);
  42097. }
  42098. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42099. results.push(this._reflectionTexture);
  42100. }
  42101. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42102. results.push(this._emissiveTexture);
  42103. }
  42104. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42105. results.push(this._metallicTexture);
  42106. }
  42107. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42108. results.push(this._reflectivityTexture);
  42109. }
  42110. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42111. results.push(this._bumpTexture);
  42112. }
  42113. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42114. results.push(this._lightmapTexture);
  42115. }
  42116. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42117. results.push(this._refractionTexture);
  42118. }
  42119. return results;
  42120. };
  42121. /**
  42122. * Returns the texture used for reflections.
  42123. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42124. */
  42125. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42126. if (this._reflectionTexture) {
  42127. return this._reflectionTexture;
  42128. }
  42129. return this.getScene().environmentTexture;
  42130. };
  42131. /**
  42132. * Returns the texture used for refraction or null if none is used.
  42133. * @returns - Refection texture if present. If no refraction texture and refraction
  42134. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42135. */
  42136. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42137. if (this._refractionTexture) {
  42138. return this._refractionTexture;
  42139. }
  42140. if (this._linkRefractionWithTransparency) {
  42141. return this.getScene().environmentTexture;
  42142. }
  42143. return null;
  42144. };
  42145. /**
  42146. * Disposes the resources of the material.
  42147. * @param forceDisposeEffect - Forces the disposal of effects.
  42148. * @param forceDisposeTextures - Forces the disposal of all textures.
  42149. */
  42150. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42151. if (forceDisposeTextures) {
  42152. if (this._albedoTexture) {
  42153. this._albedoTexture.dispose();
  42154. }
  42155. if (this._ambientTexture) {
  42156. this._ambientTexture.dispose();
  42157. }
  42158. if (this._opacityTexture) {
  42159. this._opacityTexture.dispose();
  42160. }
  42161. if (this._reflectionTexture) {
  42162. this._reflectionTexture.dispose();
  42163. }
  42164. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42165. this._environmentBRDFTexture.dispose();
  42166. }
  42167. if (this._emissiveTexture) {
  42168. this._emissiveTexture.dispose();
  42169. }
  42170. if (this._metallicTexture) {
  42171. this._metallicTexture.dispose();
  42172. }
  42173. if (this._reflectivityTexture) {
  42174. this._reflectivityTexture.dispose();
  42175. }
  42176. if (this._bumpTexture) {
  42177. this._bumpTexture.dispose();
  42178. }
  42179. if (this._lightmapTexture) {
  42180. this._lightmapTexture.dispose();
  42181. }
  42182. if (this._refractionTexture) {
  42183. this._refractionTexture.dispose();
  42184. }
  42185. }
  42186. this._renderTargets.dispose();
  42187. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42188. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42189. }
  42190. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42191. };
  42192. /**
  42193. * Stores the reflectivity values based on metallic roughness workflow.
  42194. */
  42195. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42196. __decorate([
  42197. BABYLON.serializeAsImageProcessingConfiguration()
  42198. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42199. __decorate([
  42200. BABYLON.serialize()
  42201. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42202. __decorate([
  42203. BABYLON.serialize()
  42204. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42205. return PBRBaseMaterial;
  42206. }(BABYLON.PushMaterial));
  42207. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42208. })(BABYLON || (BABYLON = {}));
  42209. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42210. var BABYLON;
  42211. (function (BABYLON) {
  42212. /**
  42213. * The Physically based simple base material of BJS.
  42214. *
  42215. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42216. * It is used as the base class for both the specGloss and metalRough conventions.
  42217. */
  42218. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42219. __extends(PBRBaseSimpleMaterial, _super);
  42220. /**
  42221. * Instantiates a new PBRMaterial instance.
  42222. *
  42223. * @param name The material name
  42224. * @param scene The scene the material will be use in.
  42225. */
  42226. function PBRBaseSimpleMaterial(name, scene) {
  42227. var _this = _super.call(this, name, scene) || this;
  42228. /**
  42229. * Number of Simultaneous lights allowed on the material.
  42230. */
  42231. _this.maxSimultaneousLights = 4;
  42232. /**
  42233. * If sets to true, disables all the lights affecting the material.
  42234. */
  42235. _this.disableLighting = false;
  42236. /**
  42237. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42238. */
  42239. _this.invertNormalMapX = false;
  42240. /**
  42241. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42242. */
  42243. _this.invertNormalMapY = false;
  42244. /**
  42245. * Emissivie color used to self-illuminate the model.
  42246. */
  42247. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42248. /**
  42249. * Occlusion Channel Strenght.
  42250. */
  42251. _this.occlusionStrength = 1.0;
  42252. _this.useLightmapAsShadowmap = false;
  42253. _this._useAlphaFromAlbedoTexture = true;
  42254. _this._useAmbientInGrayScale = true;
  42255. return _this;
  42256. }
  42257. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42258. /**
  42259. * Gets the current double sided mode.
  42260. */
  42261. get: function () {
  42262. return this._twoSidedLighting;
  42263. },
  42264. /**
  42265. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42266. */
  42267. set: function (value) {
  42268. if (this._twoSidedLighting === value) {
  42269. return;
  42270. }
  42271. this._twoSidedLighting = value;
  42272. this.backFaceCulling = !value;
  42273. this._markAllSubMeshesAsTexturesDirty();
  42274. },
  42275. enumerable: true,
  42276. configurable: true
  42277. });
  42278. /**
  42279. * Return the active textures of the material.
  42280. */
  42281. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42282. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42283. if (this.environmentTexture) {
  42284. activeTextures.push(this.environmentTexture);
  42285. }
  42286. if (this.normalTexture) {
  42287. activeTextures.push(this.normalTexture);
  42288. }
  42289. if (this.emissiveTexture) {
  42290. activeTextures.push(this.emissiveTexture);
  42291. }
  42292. if (this.occlusionTexture) {
  42293. activeTextures.push(this.occlusionTexture);
  42294. }
  42295. if (this.lightmapTexture) {
  42296. activeTextures.push(this.lightmapTexture);
  42297. }
  42298. return activeTextures;
  42299. };
  42300. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42301. if (_super.prototype.hasTexture.call(this, texture)) {
  42302. return true;
  42303. }
  42304. if (this.lightmapTexture === texture) {
  42305. return true;
  42306. }
  42307. return false;
  42308. };
  42309. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42310. return "PBRBaseSimpleMaterial";
  42311. };
  42312. __decorate([
  42313. BABYLON.serialize(),
  42314. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42315. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42316. __decorate([
  42317. BABYLON.serialize(),
  42318. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42319. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42320. __decorate([
  42321. BABYLON.serializeAsTexture(),
  42322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42323. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42324. __decorate([
  42325. BABYLON.serialize(),
  42326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42327. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42328. __decorate([
  42329. BABYLON.serialize(),
  42330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42331. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42332. __decorate([
  42333. BABYLON.serializeAsTexture(),
  42334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42335. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42336. __decorate([
  42337. BABYLON.serializeAsColor3("emissive"),
  42338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42339. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42340. __decorate([
  42341. BABYLON.serializeAsTexture(),
  42342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42343. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42344. __decorate([
  42345. BABYLON.serialize(),
  42346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42347. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42348. __decorate([
  42349. BABYLON.serializeAsTexture(),
  42350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42351. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42352. __decorate([
  42353. BABYLON.serialize(),
  42354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42355. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42356. __decorate([
  42357. BABYLON.serialize()
  42358. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42359. __decorate([
  42360. BABYLON.serializeAsTexture(),
  42361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42362. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42363. __decorate([
  42364. BABYLON.serialize(),
  42365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42366. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42367. return PBRBaseSimpleMaterial;
  42368. }(BABYLON.PBRBaseMaterial));
  42369. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42370. })(BABYLON || (BABYLON = {}));
  42371. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42372. var BABYLON;
  42373. (function (BABYLON) {
  42374. /**
  42375. * The Physically based material of BJS.
  42376. *
  42377. * This offers the main features of a standard PBR material.
  42378. * For more information, please refer to the documentation :
  42379. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42380. */
  42381. var PBRMaterial = /** @class */ (function (_super) {
  42382. __extends(PBRMaterial, _super);
  42383. /**
  42384. * Instantiates a new PBRMaterial instance.
  42385. *
  42386. * @param name The material name
  42387. * @param scene The scene the material will be use in.
  42388. */
  42389. function PBRMaterial(name, scene) {
  42390. var _this = _super.call(this, name, scene) || this;
  42391. /**
  42392. * Intensity of the direct lights e.g. the four lights available in your scene.
  42393. * This impacts both the direct diffuse and specular highlights.
  42394. */
  42395. _this.directIntensity = 1.0;
  42396. /**
  42397. * Intensity of the emissive part of the material.
  42398. * This helps controlling the emissive effect without modifying the emissive color.
  42399. */
  42400. _this.emissiveIntensity = 1.0;
  42401. /**
  42402. * Intensity of the environment e.g. how much the environment will light the object
  42403. * either through harmonics for rough material or through the refelction for shiny ones.
  42404. */
  42405. _this.environmentIntensity = 1.0;
  42406. /**
  42407. * This is a special control allowing the reduction of the specular highlights coming from the
  42408. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42409. */
  42410. _this.specularIntensity = 1.0;
  42411. /**
  42412. * Debug Control allowing disabling the bump map on this material.
  42413. */
  42414. _this.disableBumpMap = false;
  42415. /**
  42416. * AKA Occlusion Texture Intensity in other nomenclature.
  42417. */
  42418. _this.ambientTextureStrength = 1.0;
  42419. /**
  42420. * The color of a material in ambient lighting.
  42421. */
  42422. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42423. /**
  42424. * AKA Diffuse Color in other nomenclature.
  42425. */
  42426. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42427. /**
  42428. * AKA Specular Color in other nomenclature.
  42429. */
  42430. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42431. /**
  42432. * The color reflected from the material.
  42433. */
  42434. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42435. /**
  42436. * The color emitted from the material.
  42437. */
  42438. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42439. /**
  42440. * AKA Glossiness in other nomenclature.
  42441. */
  42442. _this.microSurface = 1.0;
  42443. /**
  42444. * source material index of refraction (IOR)' / 'destination material IOR.
  42445. */
  42446. _this.indexOfRefraction = 0.66;
  42447. /**
  42448. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42449. */
  42450. _this.invertRefractionY = false;
  42451. /**
  42452. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42453. * Materials half opaque for instance using refraction could benefit from this control.
  42454. */
  42455. _this.linkRefractionWithTransparency = false;
  42456. _this.useLightmapAsShadowmap = false;
  42457. /**
  42458. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42459. */
  42460. _this.useAlphaFromAlbedoTexture = false;
  42461. /**
  42462. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42463. */
  42464. _this.forceAlphaTest = false;
  42465. /**
  42466. * Defines the alpha limits in alpha test mode.
  42467. */
  42468. _this.alphaCutOff = 0.4;
  42469. /**
  42470. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42471. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42472. */
  42473. _this.useSpecularOverAlpha = true;
  42474. /**
  42475. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42476. */
  42477. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42478. /**
  42479. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42480. */
  42481. _this.useRoughnessFromMetallicTextureAlpha = true;
  42482. /**
  42483. * Specifies if the metallic texture contains the roughness information in its green channel.
  42484. */
  42485. _this.useRoughnessFromMetallicTextureGreen = false;
  42486. /**
  42487. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42488. */
  42489. _this.useMetallnessFromMetallicTextureBlue = false;
  42490. /**
  42491. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42492. */
  42493. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42494. /**
  42495. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42496. */
  42497. _this.useAmbientInGrayScale = false;
  42498. /**
  42499. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42500. * The material will try to infer what glossiness each pixel should be.
  42501. */
  42502. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42503. /**
  42504. * BJS is using an harcoded light falloff based on a manually sets up range.
  42505. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42506. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42507. */
  42508. _this.usePhysicalLightFalloff = true;
  42509. /**
  42510. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42511. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42512. */
  42513. _this.useRadianceOverAlpha = true;
  42514. /**
  42515. * Allows using an object space normal map (instead of tangent space).
  42516. */
  42517. _this.useObjectSpaceNormalMap = false;
  42518. /**
  42519. * Allows using the bump map in parallax mode.
  42520. */
  42521. _this.useParallax = false;
  42522. /**
  42523. * Allows using the bump map in parallax occlusion mode.
  42524. */
  42525. _this.useParallaxOcclusion = false;
  42526. /**
  42527. * Controls the scale bias of the parallax mode.
  42528. */
  42529. _this.parallaxScaleBias = 0.05;
  42530. /**
  42531. * If sets to true, disables all the lights affecting the material.
  42532. */
  42533. _this.disableLighting = false;
  42534. /**
  42535. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42536. */
  42537. _this.forceIrradianceInFragment = false;
  42538. /**
  42539. * Number of Simultaneous lights allowed on the material.
  42540. */
  42541. _this.maxSimultaneousLights = 4;
  42542. /**
  42543. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42544. */
  42545. _this.invertNormalMapX = false;
  42546. /**
  42547. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42548. */
  42549. _this.invertNormalMapY = false;
  42550. /**
  42551. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42552. */
  42553. _this.twoSidedLighting = false;
  42554. /**
  42555. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42556. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42557. */
  42558. _this.useAlphaFresnel = false;
  42559. /**
  42560. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42561. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42562. */
  42563. _this.useLinearAlphaFresnel = false;
  42564. /**
  42565. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42566. * And/Or occlude the blended part.
  42567. */
  42568. _this.environmentBRDFTexture = null;
  42569. /**
  42570. * Force normal to face away from face.
  42571. */
  42572. _this.forceNormalForward = false;
  42573. /**
  42574. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42575. * makes the reflect vector face the model (under horizon).
  42576. */
  42577. _this.useHorizonOcclusion = true;
  42578. /**
  42579. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42580. * too much the area relying on ambient texture to define their ambient occlusion.
  42581. */
  42582. _this.useRadianceOcclusion = true;
  42583. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42584. return _this;
  42585. }
  42586. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42587. /**
  42588. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42589. */
  42590. get: function () {
  42591. return this._PBRMATERIAL_OPAQUE;
  42592. },
  42593. enumerable: true,
  42594. configurable: true
  42595. });
  42596. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42597. /**
  42598. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42599. */
  42600. get: function () {
  42601. return this._PBRMATERIAL_ALPHATEST;
  42602. },
  42603. enumerable: true,
  42604. configurable: true
  42605. });
  42606. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42607. /**
  42608. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42609. */
  42610. get: function () {
  42611. return this._PBRMATERIAL_ALPHABLEND;
  42612. },
  42613. enumerable: true,
  42614. configurable: true
  42615. });
  42616. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42617. /**
  42618. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42619. * They are also discarded below the alpha cutoff threshold to improve performances.
  42620. */
  42621. get: function () {
  42622. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42623. },
  42624. enumerable: true,
  42625. configurable: true
  42626. });
  42627. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42628. /**
  42629. * Gets the image processing configuration used either in this material.
  42630. */
  42631. get: function () {
  42632. return this._imageProcessingConfiguration;
  42633. },
  42634. /**
  42635. * Sets the Default image processing configuration used either in the this material.
  42636. *
  42637. * If sets to null, the scene one is in use.
  42638. */
  42639. set: function (value) {
  42640. this._attachImageProcessingConfiguration(value);
  42641. // Ensure the effect will be rebuilt.
  42642. this._markAllSubMeshesAsTexturesDirty();
  42643. },
  42644. enumerable: true,
  42645. configurable: true
  42646. });
  42647. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42648. /**
  42649. * Gets wether the color curves effect is enabled.
  42650. */
  42651. get: function () {
  42652. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42653. },
  42654. /**
  42655. * Sets wether the color curves effect is enabled.
  42656. */
  42657. set: function (value) {
  42658. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42659. },
  42660. enumerable: true,
  42661. configurable: true
  42662. });
  42663. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42664. /**
  42665. * Gets wether the color grading effect is enabled.
  42666. */
  42667. get: function () {
  42668. return this.imageProcessingConfiguration.colorGradingEnabled;
  42669. },
  42670. /**
  42671. * Gets wether the color grading effect is enabled.
  42672. */
  42673. set: function (value) {
  42674. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42675. },
  42676. enumerable: true,
  42677. configurable: true
  42678. });
  42679. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42680. /**
  42681. * Gets wether tonemapping is enabled or not.
  42682. */
  42683. get: function () {
  42684. return this._imageProcessingConfiguration.toneMappingEnabled;
  42685. },
  42686. /**
  42687. * Sets wether tonemapping is enabled or not
  42688. */
  42689. set: function (value) {
  42690. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42691. },
  42692. enumerable: true,
  42693. configurable: true
  42694. });
  42695. ;
  42696. ;
  42697. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42698. /**
  42699. * The camera exposure used on this material.
  42700. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42701. * This corresponds to a photographic exposure.
  42702. */
  42703. get: function () {
  42704. return this._imageProcessingConfiguration.exposure;
  42705. },
  42706. /**
  42707. * The camera exposure used on this material.
  42708. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42709. * This corresponds to a photographic exposure.
  42710. */
  42711. set: function (value) {
  42712. this._imageProcessingConfiguration.exposure = value;
  42713. },
  42714. enumerable: true,
  42715. configurable: true
  42716. });
  42717. ;
  42718. ;
  42719. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42720. /**
  42721. * Gets The camera contrast used on this material.
  42722. */
  42723. get: function () {
  42724. return this._imageProcessingConfiguration.contrast;
  42725. },
  42726. /**
  42727. * Sets The camera contrast used on this material.
  42728. */
  42729. set: function (value) {
  42730. this._imageProcessingConfiguration.contrast = value;
  42731. },
  42732. enumerable: true,
  42733. configurable: true
  42734. });
  42735. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42736. /**
  42737. * Gets the Color Grading 2D Lookup Texture.
  42738. */
  42739. get: function () {
  42740. return this._imageProcessingConfiguration.colorGradingTexture;
  42741. },
  42742. /**
  42743. * Sets the Color Grading 2D Lookup Texture.
  42744. */
  42745. set: function (value) {
  42746. this._imageProcessingConfiguration.colorGradingTexture = value;
  42747. },
  42748. enumerable: true,
  42749. configurable: true
  42750. });
  42751. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42752. /**
  42753. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42754. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42755. * 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;
  42756. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42757. */
  42758. get: function () {
  42759. return this._imageProcessingConfiguration.colorCurves;
  42760. },
  42761. /**
  42762. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42763. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42764. * 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;
  42765. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42766. */
  42767. set: function (value) {
  42768. this._imageProcessingConfiguration.colorCurves = value;
  42769. },
  42770. enumerable: true,
  42771. configurable: true
  42772. });
  42773. /**
  42774. * Returns the name of this material class.
  42775. */
  42776. PBRMaterial.prototype.getClassName = function () {
  42777. return "PBRMaterial";
  42778. };
  42779. /**
  42780. * Returns an array of the actively used textures.
  42781. * @returns - Array of BaseTextures
  42782. */
  42783. PBRMaterial.prototype.getActiveTextures = function () {
  42784. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42785. if (this._albedoTexture) {
  42786. activeTextures.push(this._albedoTexture);
  42787. }
  42788. if (this._ambientTexture) {
  42789. activeTextures.push(this._ambientTexture);
  42790. }
  42791. if (this._opacityTexture) {
  42792. activeTextures.push(this._opacityTexture);
  42793. }
  42794. if (this._reflectionTexture) {
  42795. activeTextures.push(this._reflectionTexture);
  42796. }
  42797. if (this._emissiveTexture) {
  42798. activeTextures.push(this._emissiveTexture);
  42799. }
  42800. if (this._reflectivityTexture) {
  42801. activeTextures.push(this._reflectivityTexture);
  42802. }
  42803. if (this._metallicTexture) {
  42804. activeTextures.push(this._metallicTexture);
  42805. }
  42806. if (this._microSurfaceTexture) {
  42807. activeTextures.push(this._microSurfaceTexture);
  42808. }
  42809. if (this._bumpTexture) {
  42810. activeTextures.push(this._bumpTexture);
  42811. }
  42812. if (this._lightmapTexture) {
  42813. activeTextures.push(this._lightmapTexture);
  42814. }
  42815. if (this._refractionTexture) {
  42816. activeTextures.push(this._refractionTexture);
  42817. }
  42818. return activeTextures;
  42819. };
  42820. /**
  42821. * Checks to see if a texture is used in the material.
  42822. * @param texture - Base texture to use.
  42823. * @returns - Boolean specifying if a texture is used in the material.
  42824. */
  42825. PBRMaterial.prototype.hasTexture = function (texture) {
  42826. if (_super.prototype.hasTexture.call(this, texture)) {
  42827. return true;
  42828. }
  42829. if (this._albedoTexture === texture) {
  42830. return true;
  42831. }
  42832. if (this._ambientTexture === texture) {
  42833. return true;
  42834. }
  42835. if (this._opacityTexture === texture) {
  42836. return true;
  42837. }
  42838. if (this._reflectionTexture === texture) {
  42839. return true;
  42840. }
  42841. if (this._reflectivityTexture === texture) {
  42842. return true;
  42843. }
  42844. if (this._metallicTexture === texture) {
  42845. return true;
  42846. }
  42847. if (this._microSurfaceTexture === texture) {
  42848. return true;
  42849. }
  42850. if (this._bumpTexture === texture) {
  42851. return true;
  42852. }
  42853. if (this._lightmapTexture === texture) {
  42854. return true;
  42855. }
  42856. if (this._refractionTexture === texture) {
  42857. return true;
  42858. }
  42859. return false;
  42860. };
  42861. /**
  42862. * Makes a duplicate of the current material.
  42863. * @param name - name to use for the new material.
  42864. */
  42865. PBRMaterial.prototype.clone = function (name) {
  42866. var _this = this;
  42867. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42868. clone.id = name;
  42869. clone.name = name;
  42870. return clone;
  42871. };
  42872. /**
  42873. * Serializes this PBR Material.
  42874. * @returns - An object with the serialized material.
  42875. */
  42876. PBRMaterial.prototype.serialize = function () {
  42877. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42878. serializationObject.customType = "BABYLON.PBRMaterial";
  42879. return serializationObject;
  42880. };
  42881. // Statics
  42882. /**
  42883. * Parses a PBR Material from a serialized object.
  42884. * @param source - Serialized object.
  42885. * @param scene - BJS scene instance.
  42886. * @param rootUrl - url for the scene object
  42887. * @returns - PBRMaterial
  42888. */
  42889. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42890. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42891. };
  42892. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42893. /**
  42894. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42895. */
  42896. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42897. /**
  42898. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42899. */
  42900. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42901. /**
  42902. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42903. * They are also discarded below the alpha cutoff threshold to improve performances.
  42904. */
  42905. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42906. __decorate([
  42907. BABYLON.serialize(),
  42908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42909. ], PBRMaterial.prototype, "directIntensity", void 0);
  42910. __decorate([
  42911. BABYLON.serialize(),
  42912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42913. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42914. __decorate([
  42915. BABYLON.serialize(),
  42916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42917. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42918. __decorate([
  42919. BABYLON.serialize(),
  42920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42921. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42922. __decorate([
  42923. BABYLON.serialize(),
  42924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42925. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42926. __decorate([
  42927. BABYLON.serializeAsTexture(),
  42928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42929. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42930. __decorate([
  42931. BABYLON.serializeAsTexture(),
  42932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42933. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42934. __decorate([
  42935. BABYLON.serialize(),
  42936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42937. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42938. __decorate([
  42939. BABYLON.serializeAsTexture(),
  42940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42941. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42942. __decorate([
  42943. BABYLON.serializeAsTexture(),
  42944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42945. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42946. __decorate([
  42947. BABYLON.serializeAsTexture(),
  42948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42949. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42950. __decorate([
  42951. BABYLON.serializeAsTexture(),
  42952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42953. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42954. __decorate([
  42955. BABYLON.serializeAsTexture(),
  42956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42957. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42958. __decorate([
  42959. BABYLON.serialize(),
  42960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42961. ], PBRMaterial.prototype, "metallic", void 0);
  42962. __decorate([
  42963. BABYLON.serialize(),
  42964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42965. ], PBRMaterial.prototype, "roughness", void 0);
  42966. __decorate([
  42967. BABYLON.serializeAsTexture(),
  42968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42969. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42970. __decorate([
  42971. BABYLON.serializeAsTexture(),
  42972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42973. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42974. __decorate([
  42975. BABYLON.serializeAsTexture(),
  42976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42977. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42978. __decorate([
  42979. BABYLON.serializeAsTexture(),
  42980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42981. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42982. __decorate([
  42983. BABYLON.serializeAsColor3("ambient"),
  42984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42985. ], PBRMaterial.prototype, "ambientColor", void 0);
  42986. __decorate([
  42987. BABYLON.serializeAsColor3("albedo"),
  42988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42989. ], PBRMaterial.prototype, "albedoColor", void 0);
  42990. __decorate([
  42991. BABYLON.serializeAsColor3("reflectivity"),
  42992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42993. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42994. __decorate([
  42995. BABYLON.serializeAsColor3("reflection"),
  42996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42997. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42998. __decorate([
  42999. BABYLON.serializeAsColor3("emissive"),
  43000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43001. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43002. __decorate([
  43003. BABYLON.serialize(),
  43004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43005. ], PBRMaterial.prototype, "microSurface", void 0);
  43006. __decorate([
  43007. BABYLON.serialize(),
  43008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43009. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43010. __decorate([
  43011. BABYLON.serialize(),
  43012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43013. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43014. __decorate([
  43015. BABYLON.serialize(),
  43016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43017. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43018. __decorate([
  43019. BABYLON.serialize(),
  43020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43021. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43022. __decorate([
  43023. BABYLON.serialize(),
  43024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43025. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43026. __decorate([
  43027. BABYLON.serialize(),
  43028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43029. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43030. __decorate([
  43031. BABYLON.serialize(),
  43032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43033. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43034. __decorate([
  43035. BABYLON.serialize(),
  43036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43037. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43038. __decorate([
  43039. BABYLON.serialize(),
  43040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43041. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43042. __decorate([
  43043. BABYLON.serialize(),
  43044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43045. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43046. __decorate([
  43047. BABYLON.serialize(),
  43048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43049. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43050. __decorate([
  43051. BABYLON.serialize(),
  43052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43053. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43054. __decorate([
  43055. BABYLON.serialize(),
  43056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43057. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43058. __decorate([
  43059. BABYLON.serialize(),
  43060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43061. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43062. __decorate([
  43063. BABYLON.serialize(),
  43064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43065. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43066. __decorate([
  43067. BABYLON.serialize(),
  43068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43069. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43070. __decorate([
  43071. BABYLON.serialize(),
  43072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43073. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43074. __decorate([
  43075. BABYLON.serialize(),
  43076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43077. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43078. __decorate([
  43079. BABYLON.serialize(),
  43080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43081. ], PBRMaterial.prototype, "useParallax", void 0);
  43082. __decorate([
  43083. BABYLON.serialize(),
  43084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43085. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43086. __decorate([
  43087. BABYLON.serialize(),
  43088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43089. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43090. __decorate([
  43091. BABYLON.serialize(),
  43092. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43093. ], PBRMaterial.prototype, "disableLighting", void 0);
  43094. __decorate([
  43095. BABYLON.serialize(),
  43096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43097. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43098. __decorate([
  43099. BABYLON.serialize(),
  43100. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43101. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43102. __decorate([
  43103. BABYLON.serialize(),
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43105. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43106. __decorate([
  43107. BABYLON.serialize(),
  43108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43109. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43110. __decorate([
  43111. BABYLON.serialize(),
  43112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43113. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43114. __decorate([
  43115. BABYLON.serialize(),
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43117. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43118. __decorate([
  43119. BABYLON.serialize(),
  43120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43121. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43122. __decorate([
  43123. BABYLON.serializeAsTexture(),
  43124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43125. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43126. __decorate([
  43127. BABYLON.serialize(),
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43129. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43130. __decorate([
  43131. BABYLON.serialize(),
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43133. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43134. __decorate([
  43135. BABYLON.serialize(),
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43137. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43138. return PBRMaterial;
  43139. }(BABYLON.PBRBaseMaterial));
  43140. BABYLON.PBRMaterial = PBRMaterial;
  43141. })(BABYLON || (BABYLON = {}));
  43142. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43143. var BABYLON;
  43144. (function (BABYLON) {
  43145. /**
  43146. * The PBR material of BJS following the metal roughness convention.
  43147. *
  43148. * This fits to the PBR convention in the GLTF definition:
  43149. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43150. */
  43151. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43152. __extends(PBRMetallicRoughnessMaterial, _super);
  43153. /**
  43154. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43155. *
  43156. * @param name The material name
  43157. * @param scene The scene the material will be use in.
  43158. */
  43159. function PBRMetallicRoughnessMaterial(name, scene) {
  43160. var _this = _super.call(this, name, scene) || this;
  43161. _this._useRoughnessFromMetallicTextureAlpha = false;
  43162. _this._useRoughnessFromMetallicTextureGreen = true;
  43163. _this._useMetallnessFromMetallicTextureBlue = true;
  43164. _this.metallic = 1.0;
  43165. _this.roughness = 1.0;
  43166. return _this;
  43167. }
  43168. /**
  43169. * Return the currrent class name of the material.
  43170. */
  43171. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43172. return "PBRMetallicRoughnessMaterial";
  43173. };
  43174. /**
  43175. * Return the active textures of the material.
  43176. */
  43177. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43178. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43179. if (this.baseTexture) {
  43180. activeTextures.push(this.baseTexture);
  43181. }
  43182. if (this.metallicRoughnessTexture) {
  43183. activeTextures.push(this.metallicRoughnessTexture);
  43184. }
  43185. return activeTextures;
  43186. };
  43187. /**
  43188. * Checks to see if a texture is used in the material.
  43189. * @param texture - Base texture to use.
  43190. * @returns - Boolean specifying if a texture is used in the material.
  43191. */
  43192. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43193. if (_super.prototype.hasTexture.call(this, texture)) {
  43194. return true;
  43195. }
  43196. if (this.baseTexture === texture) {
  43197. return true;
  43198. }
  43199. if (this.metallicRoughnessTexture === texture) {
  43200. return true;
  43201. }
  43202. return false;
  43203. };
  43204. /**
  43205. * Makes a duplicate of the current material.
  43206. * @param name - name to use for the new material.
  43207. */
  43208. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43209. var _this = this;
  43210. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43211. clone.id = name;
  43212. clone.name = name;
  43213. return clone;
  43214. };
  43215. /**
  43216. * Serialize the material to a parsable JSON object.
  43217. */
  43218. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43219. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43220. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43221. return serializationObject;
  43222. };
  43223. /**
  43224. * Parses a JSON object correponding to the serialize function.
  43225. */
  43226. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43227. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43228. };
  43229. __decorate([
  43230. BABYLON.serializeAsColor3(),
  43231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43232. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43233. __decorate([
  43234. BABYLON.serializeAsTexture(),
  43235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43236. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43237. __decorate([
  43238. BABYLON.serialize(),
  43239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43240. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43241. __decorate([
  43242. BABYLON.serialize(),
  43243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43244. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43245. __decorate([
  43246. BABYLON.serializeAsTexture(),
  43247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43248. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43249. return PBRMetallicRoughnessMaterial;
  43250. }(BABYLON.PBRBaseSimpleMaterial));
  43251. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43252. })(BABYLON || (BABYLON = {}));
  43253. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43254. var BABYLON;
  43255. (function (BABYLON) {
  43256. /**
  43257. * The PBR material of BJS following the specular glossiness convention.
  43258. *
  43259. * This fits to the PBR convention in the GLTF definition:
  43260. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43261. */
  43262. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43263. __extends(PBRSpecularGlossinessMaterial, _super);
  43264. /**
  43265. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43266. *
  43267. * @param name The material name
  43268. * @param scene The scene the material will be use in.
  43269. */
  43270. function PBRSpecularGlossinessMaterial(name, scene) {
  43271. var _this = _super.call(this, name, scene) || this;
  43272. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43273. return _this;
  43274. }
  43275. /**
  43276. * Return the currrent class name of the material.
  43277. */
  43278. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43279. return "PBRSpecularGlossinessMaterial";
  43280. };
  43281. /**
  43282. * Return the active textures of the material.
  43283. */
  43284. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43285. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43286. if (this.diffuseTexture) {
  43287. activeTextures.push(this.diffuseTexture);
  43288. }
  43289. if (this.specularGlossinessTexture) {
  43290. activeTextures.push(this.specularGlossinessTexture);
  43291. }
  43292. return activeTextures;
  43293. };
  43294. /**
  43295. * Checks to see if a texture is used in the material.
  43296. * @param texture - Base texture to use.
  43297. * @returns - Boolean specifying if a texture is used in the material.
  43298. */
  43299. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43300. if (_super.prototype.hasTexture.call(this, texture)) {
  43301. return true;
  43302. }
  43303. if (this.diffuseTexture === texture) {
  43304. return true;
  43305. }
  43306. if (this.specularGlossinessTexture === texture) {
  43307. return true;
  43308. }
  43309. return false;
  43310. };
  43311. /**
  43312. * Makes a duplicate of the current material.
  43313. * @param name - name to use for the new material.
  43314. */
  43315. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43316. var _this = this;
  43317. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43318. clone.id = name;
  43319. clone.name = name;
  43320. return clone;
  43321. };
  43322. /**
  43323. * Serialize the material to a parsable JSON object.
  43324. */
  43325. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43326. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43327. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43328. return serializationObject;
  43329. };
  43330. /**
  43331. * Parses a JSON object correponding to the serialize function.
  43332. */
  43333. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43334. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43335. };
  43336. __decorate([
  43337. BABYLON.serializeAsColor3("diffuse"),
  43338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43339. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43340. __decorate([
  43341. BABYLON.serializeAsTexture(),
  43342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43343. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43344. __decorate([
  43345. BABYLON.serializeAsColor3("specular"),
  43346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43347. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43348. __decorate([
  43349. BABYLON.serialize(),
  43350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43351. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43352. __decorate([
  43353. BABYLON.serializeAsTexture(),
  43354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43355. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43356. return PBRSpecularGlossinessMaterial;
  43357. }(BABYLON.PBRBaseSimpleMaterial));
  43358. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43359. })(BABYLON || (BABYLON = {}));
  43360. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43361. var BABYLON;
  43362. (function (BABYLON) {
  43363. BABYLON.CameraInputTypes = {};
  43364. var CameraInputsManager = /** @class */ (function () {
  43365. function CameraInputsManager(camera) {
  43366. this.attached = {};
  43367. this.camera = camera;
  43368. this.checkInputs = function () { };
  43369. }
  43370. /**
  43371. * Add an input method to a camera.
  43372. * builtin inputs example: camera.inputs.addGamepad();
  43373. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43374. * @param input camera input method
  43375. */
  43376. CameraInputsManager.prototype.add = function (input) {
  43377. var type = input.getSimpleName();
  43378. if (this.attached[type]) {
  43379. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43380. return;
  43381. }
  43382. this.attached[type] = input;
  43383. input.camera = this.camera;
  43384. //for checkInputs, we are dynamically creating a function
  43385. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43386. if (input.checkInputs) {
  43387. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43388. }
  43389. if (this.attachedElement) {
  43390. input.attachControl(this.attachedElement);
  43391. }
  43392. };
  43393. /**
  43394. * Remove a specific input method from a camera
  43395. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43396. * @param inputToRemove camera input method
  43397. */
  43398. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43399. for (var cam in this.attached) {
  43400. var input = this.attached[cam];
  43401. if (input === inputToRemove) {
  43402. input.detachControl(this.attachedElement);
  43403. input.camera = null;
  43404. delete this.attached[cam];
  43405. this.rebuildInputCheck();
  43406. }
  43407. }
  43408. };
  43409. CameraInputsManager.prototype.removeByType = function (inputType) {
  43410. for (var cam in this.attached) {
  43411. var input = this.attached[cam];
  43412. if (input.getClassName() === inputType) {
  43413. input.detachControl(this.attachedElement);
  43414. input.camera = null;
  43415. delete this.attached[cam];
  43416. this.rebuildInputCheck();
  43417. }
  43418. }
  43419. };
  43420. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43421. var current = this.checkInputs;
  43422. return function () {
  43423. current();
  43424. fn();
  43425. };
  43426. };
  43427. CameraInputsManager.prototype.attachInput = function (input) {
  43428. if (this.attachedElement) {
  43429. input.attachControl(this.attachedElement, this.noPreventDefault);
  43430. }
  43431. };
  43432. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43433. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43434. if (this.attachedElement) {
  43435. return;
  43436. }
  43437. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43438. this.attachedElement = element;
  43439. this.noPreventDefault = noPreventDefault;
  43440. for (var cam in this.attached) {
  43441. this.attached[cam].attachControl(element, noPreventDefault);
  43442. }
  43443. };
  43444. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43445. if (disconnect === void 0) { disconnect = false; }
  43446. if (this.attachedElement !== element) {
  43447. return;
  43448. }
  43449. for (var cam in this.attached) {
  43450. this.attached[cam].detachControl(element);
  43451. if (disconnect) {
  43452. this.attached[cam].camera = null;
  43453. }
  43454. }
  43455. this.attachedElement = null;
  43456. };
  43457. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43458. this.checkInputs = function () { };
  43459. for (var cam in this.attached) {
  43460. var input = this.attached[cam];
  43461. if (input.checkInputs) {
  43462. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43463. }
  43464. }
  43465. };
  43466. /**
  43467. * Remove all attached input methods from a camera
  43468. */
  43469. CameraInputsManager.prototype.clear = function () {
  43470. if (this.attachedElement) {
  43471. this.detachElement(this.attachedElement, true);
  43472. }
  43473. this.attached = {};
  43474. this.attachedElement = null;
  43475. this.checkInputs = function () { };
  43476. };
  43477. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43478. var inputs = {};
  43479. for (var cam in this.attached) {
  43480. var input = this.attached[cam];
  43481. var res = BABYLON.SerializationHelper.Serialize(input);
  43482. inputs[input.getClassName()] = res;
  43483. }
  43484. serializedCamera.inputsmgr = inputs;
  43485. };
  43486. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43487. var parsedInputs = parsedCamera.inputsmgr;
  43488. if (parsedInputs) {
  43489. this.clear();
  43490. for (var n in parsedInputs) {
  43491. var construct = BABYLON.CameraInputTypes[n];
  43492. if (construct) {
  43493. var parsedinput = parsedInputs[n];
  43494. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43495. this.add(input);
  43496. }
  43497. }
  43498. }
  43499. else {
  43500. //2016-03-08 this part is for managing backward compatibility
  43501. for (var n in this.attached) {
  43502. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43503. if (construct) {
  43504. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43505. this.remove(this.attached[n]);
  43506. this.add(input);
  43507. }
  43508. }
  43509. }
  43510. };
  43511. return CameraInputsManager;
  43512. }());
  43513. BABYLON.CameraInputsManager = CameraInputsManager;
  43514. })(BABYLON || (BABYLON = {}));
  43515. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43516. var BABYLON;
  43517. (function (BABYLON) {
  43518. var TargetCamera = /** @class */ (function (_super) {
  43519. __extends(TargetCamera, _super);
  43520. function TargetCamera(name, position, scene) {
  43521. var _this = _super.call(this, name, position, scene) || this;
  43522. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43523. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43524. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43525. _this.speed = 2.0;
  43526. _this.noRotationConstraint = false;
  43527. _this.lockedTarget = null;
  43528. _this._currentTarget = BABYLON.Vector3.Zero();
  43529. _this._viewMatrix = BABYLON.Matrix.Zero();
  43530. _this._camMatrix = BABYLON.Matrix.Zero();
  43531. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43532. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43533. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43534. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43535. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43536. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43537. _this._tempMatrix = BABYLON.Matrix.Zero();
  43538. return _this;
  43539. }
  43540. TargetCamera.prototype.getFrontPosition = function (distance) {
  43541. this.getWorldMatrix();
  43542. var direction = this.getTarget().subtract(this.position);
  43543. direction.normalize();
  43544. direction.scaleInPlace(distance);
  43545. return this.globalPosition.add(direction);
  43546. };
  43547. TargetCamera.prototype._getLockedTargetPosition = function () {
  43548. if (!this.lockedTarget) {
  43549. return null;
  43550. }
  43551. if (this.lockedTarget.absolutePosition) {
  43552. this.lockedTarget.computeWorldMatrix();
  43553. }
  43554. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43555. };
  43556. TargetCamera.prototype.storeState = function () {
  43557. this._storedPosition = this.position.clone();
  43558. this._storedRotation = this.rotation.clone();
  43559. if (this.rotationQuaternion) {
  43560. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43561. }
  43562. return _super.prototype.storeState.call(this);
  43563. };
  43564. /**
  43565. * Restored camera state. You must call storeState() first
  43566. */
  43567. TargetCamera.prototype._restoreStateValues = function () {
  43568. if (!_super.prototype._restoreStateValues.call(this)) {
  43569. return false;
  43570. }
  43571. this.position = this._storedPosition.clone();
  43572. this.rotation = this._storedRotation.clone();
  43573. if (this.rotationQuaternion) {
  43574. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43575. }
  43576. this.cameraDirection.copyFromFloats(0, 0, 0);
  43577. this.cameraRotation.copyFromFloats(0, 0);
  43578. return true;
  43579. };
  43580. // Cache
  43581. TargetCamera.prototype._initCache = function () {
  43582. _super.prototype._initCache.call(this);
  43583. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43584. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43585. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43586. };
  43587. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43588. if (!ignoreParentClass) {
  43589. _super.prototype._updateCache.call(this);
  43590. }
  43591. var lockedTargetPosition = this._getLockedTargetPosition();
  43592. if (!lockedTargetPosition) {
  43593. this._cache.lockedTarget = null;
  43594. }
  43595. else {
  43596. if (!this._cache.lockedTarget) {
  43597. this._cache.lockedTarget = lockedTargetPosition.clone();
  43598. }
  43599. else {
  43600. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43601. }
  43602. }
  43603. this._cache.rotation.copyFrom(this.rotation);
  43604. if (this.rotationQuaternion)
  43605. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43606. };
  43607. // Synchronized
  43608. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43609. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43610. return false;
  43611. }
  43612. var lockedTargetPosition = this._getLockedTargetPosition();
  43613. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43614. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43615. };
  43616. // Methods
  43617. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43618. var engine = this.getEngine();
  43619. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43620. };
  43621. // Target
  43622. TargetCamera.prototype.setTarget = function (target) {
  43623. this.upVector.normalize();
  43624. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43625. this._camMatrix.invert();
  43626. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43627. var vDir = target.subtract(this.position);
  43628. if (vDir.x >= 0.0) {
  43629. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43630. }
  43631. else {
  43632. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43633. }
  43634. this.rotation.z = 0;
  43635. if (isNaN(this.rotation.x)) {
  43636. this.rotation.x = 0;
  43637. }
  43638. if (isNaN(this.rotation.y)) {
  43639. this.rotation.y = 0;
  43640. }
  43641. if (isNaN(this.rotation.z)) {
  43642. this.rotation.z = 0;
  43643. }
  43644. if (this.rotationQuaternion) {
  43645. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43646. }
  43647. };
  43648. /**
  43649. * Return the current target position of the camera. This value is expressed in local space.
  43650. */
  43651. TargetCamera.prototype.getTarget = function () {
  43652. return this._currentTarget;
  43653. };
  43654. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43655. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43656. };
  43657. TargetCamera.prototype._updatePosition = function () {
  43658. if (this.parent) {
  43659. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43660. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43661. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43662. return;
  43663. }
  43664. this.position.addInPlace(this.cameraDirection);
  43665. };
  43666. TargetCamera.prototype._checkInputs = function () {
  43667. var needToMove = this._decideIfNeedsToMove();
  43668. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43669. // Move
  43670. if (needToMove) {
  43671. this._updatePosition();
  43672. }
  43673. // Rotate
  43674. if (needToRotate) {
  43675. this.rotation.x += this.cameraRotation.x;
  43676. this.rotation.y += this.cameraRotation.y;
  43677. //rotate, if quaternion is set and rotation was used
  43678. if (this.rotationQuaternion) {
  43679. var len = this.rotation.lengthSquared();
  43680. if (len) {
  43681. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43682. }
  43683. }
  43684. if (!this.noRotationConstraint) {
  43685. var limit = (Math.PI / 2) * 0.95;
  43686. if (this.rotation.x > limit)
  43687. this.rotation.x = limit;
  43688. if (this.rotation.x < -limit)
  43689. this.rotation.x = -limit;
  43690. }
  43691. }
  43692. // Inertia
  43693. if (needToMove) {
  43694. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43695. this.cameraDirection.x = 0;
  43696. }
  43697. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43698. this.cameraDirection.y = 0;
  43699. }
  43700. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43701. this.cameraDirection.z = 0;
  43702. }
  43703. this.cameraDirection.scaleInPlace(this.inertia);
  43704. }
  43705. if (needToRotate) {
  43706. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43707. this.cameraRotation.x = 0;
  43708. }
  43709. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43710. this.cameraRotation.y = 0;
  43711. }
  43712. this.cameraRotation.scaleInPlace(this.inertia);
  43713. }
  43714. _super.prototype._checkInputs.call(this);
  43715. };
  43716. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43717. if (this.rotationQuaternion) {
  43718. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43719. }
  43720. else {
  43721. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43722. }
  43723. //update the up vector!
  43724. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43725. };
  43726. TargetCamera.prototype._getViewMatrix = function () {
  43727. if (this.lockedTarget) {
  43728. this.setTarget(this._getLockedTargetPosition());
  43729. }
  43730. // Compute
  43731. this._updateCameraRotationMatrix();
  43732. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43733. // Computing target and final matrix
  43734. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43735. if (this.getScene().useRightHandedSystem) {
  43736. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43737. }
  43738. else {
  43739. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43740. }
  43741. return this._viewMatrix;
  43742. };
  43743. /**
  43744. * @override
  43745. * Override Camera.createRigCamera
  43746. */
  43747. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43748. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43749. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43750. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43751. if (!this.rotationQuaternion) {
  43752. this.rotationQuaternion = new BABYLON.Quaternion();
  43753. }
  43754. rigCamera._cameraRigParams = {};
  43755. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43756. }
  43757. return rigCamera;
  43758. }
  43759. return null;
  43760. };
  43761. /**
  43762. * @override
  43763. * Override Camera._updateRigCameras
  43764. */
  43765. TargetCamera.prototype._updateRigCameras = function () {
  43766. var camLeft = this._rigCameras[0];
  43767. var camRight = this._rigCameras[1];
  43768. switch (this.cameraRigMode) {
  43769. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43770. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43771. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43772. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43773. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43774. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43775. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43776. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43777. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43778. camLeft.setTarget(this.getTarget());
  43779. camRight.setTarget(this.getTarget());
  43780. break;
  43781. case BABYLON.Camera.RIG_MODE_VR:
  43782. if (camLeft.rotationQuaternion) {
  43783. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43784. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43785. }
  43786. else {
  43787. camLeft.rotation.copyFrom(this.rotation);
  43788. camRight.rotation.copyFrom(this.rotation);
  43789. }
  43790. camLeft.position.copyFrom(this.position);
  43791. camRight.position.copyFrom(this.position);
  43792. break;
  43793. }
  43794. _super.prototype._updateRigCameras.call(this);
  43795. };
  43796. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43797. if (!this._rigCamTransformMatrix) {
  43798. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43799. }
  43800. var target = this.getTarget();
  43801. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43802. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43803. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43804. };
  43805. TargetCamera.prototype.getClassName = function () {
  43806. return "TargetCamera";
  43807. };
  43808. __decorate([
  43809. BABYLON.serializeAsVector3()
  43810. ], TargetCamera.prototype, "rotation", void 0);
  43811. __decorate([
  43812. BABYLON.serialize()
  43813. ], TargetCamera.prototype, "speed", void 0);
  43814. __decorate([
  43815. BABYLON.serializeAsMeshReference("lockedTargetId")
  43816. ], TargetCamera.prototype, "lockedTarget", void 0);
  43817. return TargetCamera;
  43818. }(BABYLON.Camera));
  43819. BABYLON.TargetCamera = TargetCamera;
  43820. })(BABYLON || (BABYLON = {}));
  43821. //# sourceMappingURL=babylon.targetCamera.js.map
  43822. var BABYLON;
  43823. (function (BABYLON) {
  43824. var FreeCameraMouseInput = /** @class */ (function () {
  43825. function FreeCameraMouseInput(touchEnabled) {
  43826. if (touchEnabled === void 0) { touchEnabled = true; }
  43827. this.touchEnabled = touchEnabled;
  43828. this.buttons = [0, 1, 2];
  43829. this.angularSensibility = 2000.0;
  43830. this.previousPosition = null;
  43831. }
  43832. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43833. var _this = this;
  43834. var engine = this.camera.getEngine();
  43835. if (!this._pointerInput) {
  43836. this._pointerInput = function (p, s) {
  43837. var evt = p.event;
  43838. if (engine.isInVRExclusivePointerMode) {
  43839. return;
  43840. }
  43841. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43842. return;
  43843. }
  43844. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43845. return;
  43846. }
  43847. var srcElement = (evt.srcElement || evt.target);
  43848. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43849. try {
  43850. srcElement.setPointerCapture(evt.pointerId);
  43851. }
  43852. catch (e) {
  43853. //Nothing to do with the error. Execution will continue.
  43854. }
  43855. _this.previousPosition = {
  43856. x: evt.clientX,
  43857. y: evt.clientY
  43858. };
  43859. if (!noPreventDefault) {
  43860. evt.preventDefault();
  43861. element.focus();
  43862. }
  43863. }
  43864. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43865. try {
  43866. srcElement.releasePointerCapture(evt.pointerId);
  43867. }
  43868. catch (e) {
  43869. //Nothing to do with the error.
  43870. }
  43871. _this.previousPosition = null;
  43872. if (!noPreventDefault) {
  43873. evt.preventDefault();
  43874. }
  43875. }
  43876. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43877. if (!_this.previousPosition || engine.isPointerLock) {
  43878. return;
  43879. }
  43880. var offsetX = evt.clientX - _this.previousPosition.x;
  43881. var offsetY = evt.clientY - _this.previousPosition.y;
  43882. if (_this.camera.getScene().useRightHandedSystem) {
  43883. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43884. }
  43885. else {
  43886. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43887. }
  43888. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43889. _this.previousPosition = {
  43890. x: evt.clientX,
  43891. y: evt.clientY
  43892. };
  43893. if (!noPreventDefault) {
  43894. evt.preventDefault();
  43895. }
  43896. }
  43897. };
  43898. }
  43899. this._onMouseMove = function (evt) {
  43900. if (!engine.isPointerLock) {
  43901. return;
  43902. }
  43903. if (engine.isInVRExclusivePointerMode) {
  43904. return;
  43905. }
  43906. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43907. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43908. if (_this.camera.getScene().useRightHandedSystem) {
  43909. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43910. }
  43911. else {
  43912. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43913. }
  43914. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43915. _this.previousPosition = null;
  43916. if (!noPreventDefault) {
  43917. evt.preventDefault();
  43918. }
  43919. };
  43920. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43921. element.addEventListener("mousemove", this._onMouseMove, false);
  43922. };
  43923. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43924. if (this._observer && element) {
  43925. this.camera.getScene().onPointerObservable.remove(this._observer);
  43926. if (this._onMouseMove) {
  43927. element.removeEventListener("mousemove", this._onMouseMove);
  43928. }
  43929. this._observer = null;
  43930. this._onMouseMove = null;
  43931. this.previousPosition = null;
  43932. }
  43933. };
  43934. FreeCameraMouseInput.prototype.getClassName = function () {
  43935. return "FreeCameraMouseInput";
  43936. };
  43937. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43938. return "mouse";
  43939. };
  43940. __decorate([
  43941. BABYLON.serialize()
  43942. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43943. __decorate([
  43944. BABYLON.serialize()
  43945. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43946. return FreeCameraMouseInput;
  43947. }());
  43948. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43949. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43950. })(BABYLON || (BABYLON = {}));
  43951. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43952. var BABYLON;
  43953. (function (BABYLON) {
  43954. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43955. function FreeCameraKeyboardMoveInput() {
  43956. this._keys = new Array();
  43957. this.keysUp = [38];
  43958. this.keysDown = [40];
  43959. this.keysLeft = [37];
  43960. this.keysRight = [39];
  43961. }
  43962. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43963. var _this = this;
  43964. if (this._onCanvasBlurObserver) {
  43965. return;
  43966. }
  43967. this._scene = this.camera.getScene();
  43968. this._engine = this._scene.getEngine();
  43969. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43970. _this._keys = [];
  43971. });
  43972. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43973. var evt = info.event;
  43974. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43975. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43976. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43977. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43978. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43979. var index = _this._keys.indexOf(evt.keyCode);
  43980. if (index === -1) {
  43981. _this._keys.push(evt.keyCode);
  43982. }
  43983. if (!noPreventDefault) {
  43984. evt.preventDefault();
  43985. }
  43986. }
  43987. }
  43988. else {
  43989. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43990. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43991. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43992. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43993. var index = _this._keys.indexOf(evt.keyCode);
  43994. if (index >= 0) {
  43995. _this._keys.splice(index, 1);
  43996. }
  43997. if (!noPreventDefault) {
  43998. evt.preventDefault();
  43999. }
  44000. }
  44001. }
  44002. });
  44003. };
  44004. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44005. if (this._scene) {
  44006. if (this._onKeyboardObserver) {
  44007. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44008. }
  44009. if (this._onCanvasBlurObserver) {
  44010. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44011. }
  44012. this._onKeyboardObserver = null;
  44013. this._onCanvasBlurObserver = null;
  44014. }
  44015. this._keys = [];
  44016. };
  44017. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44018. if (this._onKeyboardObserver) {
  44019. var camera = this.camera;
  44020. // Keyboard
  44021. for (var index = 0; index < this._keys.length; index++) {
  44022. var keyCode = this._keys[index];
  44023. var speed = camera._computeLocalCameraSpeed();
  44024. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44025. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44026. }
  44027. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44028. camera._localDirection.copyFromFloats(0, 0, speed);
  44029. }
  44030. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44031. camera._localDirection.copyFromFloats(speed, 0, 0);
  44032. }
  44033. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44034. camera._localDirection.copyFromFloats(0, 0, -speed);
  44035. }
  44036. if (camera.getScene().useRightHandedSystem) {
  44037. camera._localDirection.z *= -1;
  44038. }
  44039. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44040. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44041. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44042. }
  44043. }
  44044. };
  44045. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44046. return "FreeCameraKeyboardMoveInput";
  44047. };
  44048. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44049. this._keys = [];
  44050. };
  44051. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44052. return "keyboard";
  44053. };
  44054. __decorate([
  44055. BABYLON.serialize()
  44056. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44057. __decorate([
  44058. BABYLON.serialize()
  44059. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44060. __decorate([
  44061. BABYLON.serialize()
  44062. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44063. __decorate([
  44064. BABYLON.serialize()
  44065. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44066. return FreeCameraKeyboardMoveInput;
  44067. }());
  44068. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44069. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44070. })(BABYLON || (BABYLON = {}));
  44071. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44072. var BABYLON;
  44073. (function (BABYLON) {
  44074. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44075. __extends(FreeCameraInputsManager, _super);
  44076. function FreeCameraInputsManager(camera) {
  44077. return _super.call(this, camera) || this;
  44078. }
  44079. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44080. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44081. return this;
  44082. };
  44083. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44084. if (touchEnabled === void 0) { touchEnabled = true; }
  44085. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44086. return this;
  44087. };
  44088. FreeCameraInputsManager.prototype.addGamepad = function () {
  44089. this.add(new BABYLON.FreeCameraGamepadInput());
  44090. return this;
  44091. };
  44092. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44093. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44094. return this;
  44095. };
  44096. FreeCameraInputsManager.prototype.addTouch = function () {
  44097. this.add(new BABYLON.FreeCameraTouchInput());
  44098. return this;
  44099. };
  44100. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44101. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44102. return this;
  44103. };
  44104. return FreeCameraInputsManager;
  44105. }(BABYLON.CameraInputsManager));
  44106. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44107. })(BABYLON || (BABYLON = {}));
  44108. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44109. var BABYLON;
  44110. (function (BABYLON) {
  44111. var FreeCamera = /** @class */ (function (_super) {
  44112. __extends(FreeCamera, _super);
  44113. function FreeCamera(name, position, scene) {
  44114. var _this = _super.call(this, name, position, scene) || this;
  44115. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44116. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44117. _this.checkCollisions = false;
  44118. _this.applyGravity = false;
  44119. _this._needMoveForGravity = false;
  44120. _this._oldPosition = BABYLON.Vector3.Zero();
  44121. _this._diffPosition = BABYLON.Vector3.Zero();
  44122. _this._newPosition = BABYLON.Vector3.Zero();
  44123. // Collisions
  44124. _this._collisionMask = -1;
  44125. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44126. if (collidedMesh === void 0) { collidedMesh = null; }
  44127. //TODO move this to the collision coordinator!
  44128. if (_this.getScene().workerCollisions)
  44129. newPosition.multiplyInPlace(_this._collider._radius);
  44130. var updatePosition = function (newPos) {
  44131. _this._newPosition.copyFrom(newPos);
  44132. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44133. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44134. _this.position.addInPlace(_this._diffPosition);
  44135. if (_this.onCollide && collidedMesh) {
  44136. _this.onCollide(collidedMesh);
  44137. }
  44138. }
  44139. };
  44140. updatePosition(newPosition);
  44141. };
  44142. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44143. _this.inputs.addKeyboard().addMouse();
  44144. return _this;
  44145. }
  44146. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44147. //-- begin properties for backward compatibility for inputs
  44148. /**
  44149. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44150. * Higher values reduce sensitivity.
  44151. */
  44152. get: function () {
  44153. var mouse = this.inputs.attached["mouse"];
  44154. if (mouse)
  44155. return mouse.angularSensibility;
  44156. return 0;
  44157. },
  44158. /**
  44159. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44160. * Higher values reduce sensitivity.
  44161. */
  44162. set: function (value) {
  44163. var mouse = this.inputs.attached["mouse"];
  44164. if (mouse)
  44165. mouse.angularSensibility = value;
  44166. },
  44167. enumerable: true,
  44168. configurable: true
  44169. });
  44170. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44171. get: function () {
  44172. var keyboard = this.inputs.attached["keyboard"];
  44173. if (keyboard)
  44174. return keyboard.keysUp;
  44175. return [];
  44176. },
  44177. set: function (value) {
  44178. var keyboard = this.inputs.attached["keyboard"];
  44179. if (keyboard)
  44180. keyboard.keysUp = value;
  44181. },
  44182. enumerable: true,
  44183. configurable: true
  44184. });
  44185. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44186. get: function () {
  44187. var keyboard = this.inputs.attached["keyboard"];
  44188. if (keyboard)
  44189. return keyboard.keysDown;
  44190. return [];
  44191. },
  44192. set: function (value) {
  44193. var keyboard = this.inputs.attached["keyboard"];
  44194. if (keyboard)
  44195. keyboard.keysDown = value;
  44196. },
  44197. enumerable: true,
  44198. configurable: true
  44199. });
  44200. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44201. get: function () {
  44202. var keyboard = this.inputs.attached["keyboard"];
  44203. if (keyboard)
  44204. return keyboard.keysLeft;
  44205. return [];
  44206. },
  44207. set: function (value) {
  44208. var keyboard = this.inputs.attached["keyboard"];
  44209. if (keyboard)
  44210. keyboard.keysLeft = value;
  44211. },
  44212. enumerable: true,
  44213. configurable: true
  44214. });
  44215. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44216. get: function () {
  44217. var keyboard = this.inputs.attached["keyboard"];
  44218. if (keyboard)
  44219. return keyboard.keysRight;
  44220. return [];
  44221. },
  44222. set: function (value) {
  44223. var keyboard = this.inputs.attached["keyboard"];
  44224. if (keyboard)
  44225. keyboard.keysRight = value;
  44226. },
  44227. enumerable: true,
  44228. configurable: true
  44229. });
  44230. // Controls
  44231. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44232. this.inputs.attachElement(element, noPreventDefault);
  44233. };
  44234. FreeCamera.prototype.detachControl = function (element) {
  44235. this.inputs.detachElement(element);
  44236. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44237. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44238. };
  44239. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44240. get: function () {
  44241. return this._collisionMask;
  44242. },
  44243. set: function (mask) {
  44244. this._collisionMask = !isNaN(mask) ? mask : -1;
  44245. },
  44246. enumerable: true,
  44247. configurable: true
  44248. });
  44249. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44250. var globalPosition;
  44251. if (this.parent) {
  44252. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44253. }
  44254. else {
  44255. globalPosition = this.position;
  44256. }
  44257. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44258. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44259. if (!this._collider) {
  44260. this._collider = new BABYLON.Collider();
  44261. }
  44262. this._collider._radius = this.ellipsoid;
  44263. this._collider.collisionMask = this._collisionMask;
  44264. //no need for clone, as long as gravity is not on.
  44265. var actualDisplacement = displacement;
  44266. //add gravity to the direction to prevent the dual-collision checking
  44267. if (this.applyGravity) {
  44268. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44269. actualDisplacement = displacement.add(this.getScene().gravity);
  44270. }
  44271. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44272. };
  44273. FreeCamera.prototype._checkInputs = function () {
  44274. if (!this._localDirection) {
  44275. this._localDirection = BABYLON.Vector3.Zero();
  44276. this._transformedDirection = BABYLON.Vector3.Zero();
  44277. }
  44278. this.inputs.checkInputs();
  44279. _super.prototype._checkInputs.call(this);
  44280. };
  44281. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44282. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44283. };
  44284. FreeCamera.prototype._updatePosition = function () {
  44285. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44286. this._collideWithWorld(this.cameraDirection);
  44287. }
  44288. else {
  44289. _super.prototype._updatePosition.call(this);
  44290. }
  44291. };
  44292. FreeCamera.prototype.dispose = function () {
  44293. this.inputs.clear();
  44294. _super.prototype.dispose.call(this);
  44295. };
  44296. FreeCamera.prototype.getClassName = function () {
  44297. return "FreeCamera";
  44298. };
  44299. __decorate([
  44300. BABYLON.serializeAsVector3()
  44301. ], FreeCamera.prototype, "ellipsoid", void 0);
  44302. __decorate([
  44303. BABYLON.serializeAsVector3()
  44304. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44305. __decorate([
  44306. BABYLON.serialize()
  44307. ], FreeCamera.prototype, "checkCollisions", void 0);
  44308. __decorate([
  44309. BABYLON.serialize()
  44310. ], FreeCamera.prototype, "applyGravity", void 0);
  44311. return FreeCamera;
  44312. }(BABYLON.TargetCamera));
  44313. BABYLON.FreeCamera = FreeCamera;
  44314. })(BABYLON || (BABYLON = {}));
  44315. //# sourceMappingURL=babylon.freeCamera.js.map
  44316. var BABYLON;
  44317. (function (BABYLON) {
  44318. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44319. function ArcRotateCameraKeyboardMoveInput() {
  44320. this._keys = new Array();
  44321. this.keysUp = [38];
  44322. this.keysDown = [40];
  44323. this.keysLeft = [37];
  44324. this.keysRight = [39];
  44325. this.keysReset = [220];
  44326. this.panningSensibility = 50.0;
  44327. this.zoomingSensibility = 25.0;
  44328. this.useAltToZoom = true;
  44329. }
  44330. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44331. var _this = this;
  44332. if (this._onCanvasBlurObserver) {
  44333. return;
  44334. }
  44335. this._scene = this.camera.getScene();
  44336. this._engine = this._scene.getEngine();
  44337. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44338. _this._keys = [];
  44339. });
  44340. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44341. var evt = info.event;
  44342. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44343. _this._ctrlPressed = evt.ctrlKey;
  44344. _this._altPressed = evt.altKey;
  44345. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44346. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44347. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44348. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44349. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44350. var index = _this._keys.indexOf(evt.keyCode);
  44351. if (index === -1) {
  44352. _this._keys.push(evt.keyCode);
  44353. }
  44354. if (evt.preventDefault) {
  44355. if (!noPreventDefault) {
  44356. evt.preventDefault();
  44357. }
  44358. }
  44359. }
  44360. }
  44361. else {
  44362. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44363. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44364. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44365. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44366. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44367. var index = _this._keys.indexOf(evt.keyCode);
  44368. if (index >= 0) {
  44369. _this._keys.splice(index, 1);
  44370. }
  44371. if (evt.preventDefault) {
  44372. if (!noPreventDefault) {
  44373. evt.preventDefault();
  44374. }
  44375. }
  44376. }
  44377. }
  44378. });
  44379. };
  44380. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44381. if (this._scene) {
  44382. if (this._onKeyboardObserver) {
  44383. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44384. }
  44385. if (this._onCanvasBlurObserver) {
  44386. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44387. }
  44388. this._onKeyboardObserver = null;
  44389. this._onCanvasBlurObserver = null;
  44390. }
  44391. this._keys = [];
  44392. };
  44393. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44394. if (this._onKeyboardObserver) {
  44395. var camera = this.camera;
  44396. for (var index = 0; index < this._keys.length; index++) {
  44397. var keyCode = this._keys[index];
  44398. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44399. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44400. camera.inertialPanningX -= 1 / this.panningSensibility;
  44401. }
  44402. else {
  44403. camera.inertialAlphaOffset -= 0.01;
  44404. }
  44405. }
  44406. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44407. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44408. camera.inertialPanningY += 1 / this.panningSensibility;
  44409. }
  44410. else if (this._altPressed && this.useAltToZoom) {
  44411. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44412. }
  44413. else {
  44414. camera.inertialBetaOffset -= 0.01;
  44415. }
  44416. }
  44417. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44418. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44419. camera.inertialPanningX += 1 / this.panningSensibility;
  44420. }
  44421. else {
  44422. camera.inertialAlphaOffset += 0.01;
  44423. }
  44424. }
  44425. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44426. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44427. camera.inertialPanningY -= 1 / this.panningSensibility;
  44428. }
  44429. else if (this._altPressed && this.useAltToZoom) {
  44430. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44431. }
  44432. else {
  44433. camera.inertialBetaOffset += 0.01;
  44434. }
  44435. }
  44436. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44437. camera.restoreState();
  44438. }
  44439. }
  44440. }
  44441. };
  44442. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44443. return "ArcRotateCameraKeyboardMoveInput";
  44444. };
  44445. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44446. return "keyboard";
  44447. };
  44448. __decorate([
  44449. BABYLON.serialize()
  44450. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44451. __decorate([
  44452. BABYLON.serialize()
  44453. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44454. __decorate([
  44455. BABYLON.serialize()
  44456. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44457. __decorate([
  44458. BABYLON.serialize()
  44459. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44460. __decorate([
  44461. BABYLON.serialize()
  44462. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44463. __decorate([
  44464. BABYLON.serialize()
  44465. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44466. __decorate([
  44467. BABYLON.serialize()
  44468. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44469. __decorate([
  44470. BABYLON.serialize()
  44471. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44472. return ArcRotateCameraKeyboardMoveInput;
  44473. }());
  44474. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44475. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44476. })(BABYLON || (BABYLON = {}));
  44477. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44478. var BABYLON;
  44479. (function (BABYLON) {
  44480. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44481. function ArcRotateCameraMouseWheelInput() {
  44482. this.wheelPrecision = 3.0;
  44483. /**
  44484. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44485. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44486. */
  44487. this.wheelDeltaPercentage = 0;
  44488. }
  44489. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44490. var _this = this;
  44491. this._wheel = function (p, s) {
  44492. //sanity check - this should be a PointerWheel event.
  44493. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44494. return;
  44495. var event = p.event;
  44496. var delta = 0;
  44497. if (event.wheelDelta) {
  44498. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44499. }
  44500. else if (event.detail) {
  44501. delta = -event.detail / _this.wheelPrecision;
  44502. }
  44503. if (delta)
  44504. _this.camera.inertialRadiusOffset += delta;
  44505. if (event.preventDefault) {
  44506. if (!noPreventDefault) {
  44507. event.preventDefault();
  44508. }
  44509. }
  44510. };
  44511. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44512. };
  44513. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44514. if (this._observer && element) {
  44515. this.camera.getScene().onPointerObservable.remove(this._observer);
  44516. this._observer = null;
  44517. this._wheel = null;
  44518. }
  44519. };
  44520. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44521. return "ArcRotateCameraMouseWheelInput";
  44522. };
  44523. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44524. return "mousewheel";
  44525. };
  44526. __decorate([
  44527. BABYLON.serialize()
  44528. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44529. __decorate([
  44530. BABYLON.serialize()
  44531. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44532. return ArcRotateCameraMouseWheelInput;
  44533. }());
  44534. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44535. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44536. })(BABYLON || (BABYLON = {}));
  44537. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44538. var BABYLON;
  44539. (function (BABYLON) {
  44540. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44541. function ArcRotateCameraPointersInput() {
  44542. this.buttons = [0, 1, 2];
  44543. this.angularSensibilityX = 1000.0;
  44544. this.angularSensibilityY = 1000.0;
  44545. this.pinchPrecision = 12.0;
  44546. /**
  44547. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44548. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44549. */
  44550. this.pinchDeltaPercentage = 0;
  44551. this.panningSensibility = 1000.0;
  44552. this.multiTouchPanning = true;
  44553. this.multiTouchPanAndZoom = true;
  44554. this._isPanClick = false;
  44555. this.pinchInwards = true;
  44556. }
  44557. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44558. var _this = this;
  44559. var engine = this.camera.getEngine();
  44560. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44561. var pointA = null;
  44562. var pointB = null;
  44563. var previousPinchSquaredDistance = 0;
  44564. var initialDistance = 0;
  44565. var twoFingerActivityCount = 0;
  44566. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44567. this._pointerInput = function (p, s) {
  44568. var evt = p.event;
  44569. var isTouch = p.event.pointerType === "touch";
  44570. if (engine.isInVRExclusivePointerMode) {
  44571. return;
  44572. }
  44573. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44574. return;
  44575. }
  44576. var srcElement = (evt.srcElement || evt.target);
  44577. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44578. try {
  44579. srcElement.setPointerCapture(evt.pointerId);
  44580. }
  44581. catch (e) {
  44582. //Nothing to do with the error. Execution will continue.
  44583. }
  44584. // Manage panning with pan button click
  44585. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44586. // manage pointers
  44587. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44588. if (pointA === null) {
  44589. pointA = cacheSoloPointer;
  44590. }
  44591. else if (pointB === null) {
  44592. pointB = cacheSoloPointer;
  44593. }
  44594. if (!noPreventDefault) {
  44595. evt.preventDefault();
  44596. element.focus();
  44597. }
  44598. }
  44599. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44600. _this.camera.restoreState();
  44601. }
  44602. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44603. try {
  44604. srcElement.releasePointerCapture(evt.pointerId);
  44605. }
  44606. catch (e) {
  44607. //Nothing to do with the error.
  44608. }
  44609. cacheSoloPointer = null;
  44610. previousPinchSquaredDistance = 0;
  44611. previousMultiTouchPanPosition.isPaning = false;
  44612. previousMultiTouchPanPosition.isPinching = false;
  44613. twoFingerActivityCount = 0;
  44614. initialDistance = 0;
  44615. if (!isTouch) {
  44616. pointB = null; // Mouse and pen are mono pointer
  44617. }
  44618. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44619. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44620. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44621. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44622. if (engine.badOS) {
  44623. pointA = pointB = null;
  44624. }
  44625. else {
  44626. //only remove the impacted pointer in case of multitouch allowing on most
  44627. //platforms switching from rotate to zoom and pan seamlessly.
  44628. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44629. pointA = pointB;
  44630. pointB = null;
  44631. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44632. }
  44633. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44634. pointB = null;
  44635. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44636. }
  44637. else {
  44638. pointA = pointB = null;
  44639. }
  44640. }
  44641. if (!noPreventDefault) {
  44642. evt.preventDefault();
  44643. }
  44644. }
  44645. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44646. if (!noPreventDefault) {
  44647. evt.preventDefault();
  44648. }
  44649. // One button down
  44650. if (pointA && pointB === null && cacheSoloPointer) {
  44651. if (_this.panningSensibility !== 0 &&
  44652. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44653. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44654. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44655. }
  44656. else {
  44657. var offsetX = evt.clientX - cacheSoloPointer.x;
  44658. var offsetY = evt.clientY - cacheSoloPointer.y;
  44659. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44660. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44661. }
  44662. cacheSoloPointer.x = evt.clientX;
  44663. cacheSoloPointer.y = evt.clientY;
  44664. }
  44665. else if (pointA && pointB) {
  44666. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44667. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44668. ed.x = evt.clientX;
  44669. ed.y = evt.clientY;
  44670. var direction = _this.pinchInwards ? 1 : -1;
  44671. var distX = pointA.x - pointB.x;
  44672. var distY = pointA.y - pointB.y;
  44673. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44674. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44675. if (previousPinchSquaredDistance === 0) {
  44676. initialDistance = pinchDistance;
  44677. previousPinchSquaredDistance = pinchSquaredDistance;
  44678. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44679. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44680. return;
  44681. }
  44682. if (_this.multiTouchPanAndZoom) {
  44683. if (_this.pinchDeltaPercentage) {
  44684. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44685. }
  44686. else {
  44687. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44688. (_this.pinchPrecision *
  44689. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44690. direction);
  44691. }
  44692. if (_this.panningSensibility !== 0) {
  44693. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44694. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44695. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44696. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44697. previousMultiTouchPanPosition.x = pointersCenterX;
  44698. previousMultiTouchPanPosition.y = pointersCenterY;
  44699. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44700. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44701. }
  44702. }
  44703. else {
  44704. twoFingerActivityCount++;
  44705. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44706. if (_this.pinchDeltaPercentage) {
  44707. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44708. }
  44709. else {
  44710. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44711. (_this.pinchPrecision *
  44712. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44713. direction);
  44714. }
  44715. previousMultiTouchPanPosition.isPaning = false;
  44716. previousMultiTouchPanPosition.isPinching = true;
  44717. }
  44718. else {
  44719. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44720. if (!previousMultiTouchPanPosition.isPaning) {
  44721. previousMultiTouchPanPosition.isPaning = true;
  44722. previousMultiTouchPanPosition.isPinching = false;
  44723. previousMultiTouchPanPosition.x = ed.x;
  44724. previousMultiTouchPanPosition.y = ed.y;
  44725. return;
  44726. }
  44727. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44728. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44729. }
  44730. }
  44731. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44732. previousMultiTouchPanPosition.x = ed.x;
  44733. previousMultiTouchPanPosition.y = ed.y;
  44734. }
  44735. }
  44736. previousPinchSquaredDistance = pinchSquaredDistance;
  44737. }
  44738. }
  44739. };
  44740. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44741. this._onContextMenu = function (evt) {
  44742. evt.preventDefault();
  44743. };
  44744. if (!this.camera._useCtrlForPanning) {
  44745. element.addEventListener("contextmenu", this._onContextMenu, false);
  44746. }
  44747. this._onLostFocus = function () {
  44748. //this._keys = [];
  44749. pointA = pointB = null;
  44750. previousPinchSquaredDistance = 0;
  44751. previousMultiTouchPanPosition.isPaning = false;
  44752. previousMultiTouchPanPosition.isPinching = false;
  44753. twoFingerActivityCount = 0;
  44754. cacheSoloPointer = null;
  44755. initialDistance = 0;
  44756. };
  44757. this._onMouseMove = function (evt) {
  44758. if (!engine.isPointerLock) {
  44759. return;
  44760. }
  44761. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44762. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44763. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44764. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44765. if (!noPreventDefault) {
  44766. evt.preventDefault();
  44767. }
  44768. };
  44769. this._onGestureStart = function (e) {
  44770. if (window.MSGesture === undefined) {
  44771. return;
  44772. }
  44773. if (!_this._MSGestureHandler) {
  44774. _this._MSGestureHandler = new MSGesture();
  44775. _this._MSGestureHandler.target = element;
  44776. }
  44777. _this._MSGestureHandler.addPointer(e.pointerId);
  44778. };
  44779. this._onGesture = function (e) {
  44780. _this.camera.radius *= e.scale;
  44781. if (e.preventDefault) {
  44782. if (!noPreventDefault) {
  44783. e.stopPropagation();
  44784. e.preventDefault();
  44785. }
  44786. }
  44787. };
  44788. element.addEventListener("mousemove", this._onMouseMove, false);
  44789. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44790. element.addEventListener("MSGestureChange", this._onGesture, false);
  44791. BABYLON.Tools.RegisterTopRootEvents([
  44792. { name: "blur", handler: this._onLostFocus }
  44793. ]);
  44794. };
  44795. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44796. if (this._onLostFocus) {
  44797. BABYLON.Tools.UnregisterTopRootEvents([
  44798. { name: "blur", handler: this._onLostFocus }
  44799. ]);
  44800. }
  44801. if (element && this._observer) {
  44802. this.camera.getScene().onPointerObservable.remove(this._observer);
  44803. this._observer = null;
  44804. if (this._onContextMenu) {
  44805. element.removeEventListener("contextmenu", this._onContextMenu);
  44806. }
  44807. if (this._onMouseMove) {
  44808. element.removeEventListener("mousemove", this._onMouseMove);
  44809. }
  44810. if (this._onGestureStart) {
  44811. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44812. }
  44813. if (this._onGesture) {
  44814. element.removeEventListener("MSGestureChange", this._onGesture);
  44815. }
  44816. this._isPanClick = false;
  44817. this.pinchInwards = true;
  44818. this._onMouseMove = null;
  44819. this._onGestureStart = null;
  44820. this._onGesture = null;
  44821. this._MSGestureHandler = null;
  44822. this._onLostFocus = null;
  44823. this._onContextMenu = null;
  44824. }
  44825. };
  44826. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44827. return "ArcRotateCameraPointersInput";
  44828. };
  44829. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44830. return "pointers";
  44831. };
  44832. __decorate([
  44833. BABYLON.serialize()
  44834. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44835. __decorate([
  44836. BABYLON.serialize()
  44837. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44838. __decorate([
  44839. BABYLON.serialize()
  44840. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44841. __decorate([
  44842. BABYLON.serialize()
  44843. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44844. __decorate([
  44845. BABYLON.serialize()
  44846. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44847. __decorate([
  44848. BABYLON.serialize()
  44849. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44850. __decorate([
  44851. BABYLON.serialize()
  44852. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44853. __decorate([
  44854. BABYLON.serialize()
  44855. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44856. return ArcRotateCameraPointersInput;
  44857. }());
  44858. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44859. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44860. })(BABYLON || (BABYLON = {}));
  44861. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44862. var BABYLON;
  44863. (function (BABYLON) {
  44864. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44865. __extends(ArcRotateCameraInputsManager, _super);
  44866. function ArcRotateCameraInputsManager(camera) {
  44867. return _super.call(this, camera) || this;
  44868. }
  44869. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44870. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44871. return this;
  44872. };
  44873. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44874. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44875. return this;
  44876. };
  44877. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44878. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44879. return this;
  44880. };
  44881. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44882. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44883. return this;
  44884. };
  44885. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44886. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44887. return this;
  44888. };
  44889. return ArcRotateCameraInputsManager;
  44890. }(BABYLON.CameraInputsManager));
  44891. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44892. })(BABYLON || (BABYLON = {}));
  44893. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44894. var BABYLON;
  44895. (function (BABYLON) {
  44896. var ArcRotateCamera = /** @class */ (function (_super) {
  44897. __extends(ArcRotateCamera, _super);
  44898. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44899. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44900. _this.inertialAlphaOffset = 0;
  44901. _this.inertialBetaOffset = 0;
  44902. _this.inertialRadiusOffset = 0;
  44903. _this.lowerAlphaLimit = null;
  44904. _this.upperAlphaLimit = null;
  44905. _this.lowerBetaLimit = 0.01;
  44906. _this.upperBetaLimit = Math.PI;
  44907. _this.lowerRadiusLimit = null;
  44908. _this.upperRadiusLimit = null;
  44909. _this.inertialPanningX = 0;
  44910. _this.inertialPanningY = 0;
  44911. _this.pinchToPanMaxDistance = 20;
  44912. _this.panningDistanceLimit = null;
  44913. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44914. _this.panningInertia = 0.9;
  44915. //-- end properties for backward compatibility for inputs
  44916. _this.zoomOnFactor = 1;
  44917. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44918. _this.allowUpsideDown = true;
  44919. _this._viewMatrix = new BABYLON.Matrix();
  44920. // Panning
  44921. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44922. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44923. _this.checkCollisions = false;
  44924. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44925. _this._previousPosition = BABYLON.Vector3.Zero();
  44926. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44927. _this._newPosition = BABYLON.Vector3.Zero();
  44928. _this._computationVector = BABYLON.Vector3.Zero();
  44929. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44930. if (collidedMesh === void 0) { collidedMesh = null; }
  44931. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44932. newPosition.multiplyInPlace(_this._collider._radius);
  44933. }
  44934. if (!collidedMesh) {
  44935. _this._previousPosition.copyFrom(_this.position);
  44936. }
  44937. else {
  44938. _this.setPosition(newPosition);
  44939. if (_this.onCollide) {
  44940. _this.onCollide(collidedMesh);
  44941. }
  44942. }
  44943. // Recompute because of constraints
  44944. var cosa = Math.cos(_this.alpha);
  44945. var sina = Math.sin(_this.alpha);
  44946. var cosb = Math.cos(_this.beta);
  44947. var sinb = Math.sin(_this.beta);
  44948. if (sinb === 0) {
  44949. sinb = 0.0001;
  44950. }
  44951. var target = _this._getTargetPosition();
  44952. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44953. target.addToRef(_this._computationVector, _this._newPosition);
  44954. _this.position.copyFrom(_this._newPosition);
  44955. var up = _this.upVector;
  44956. if (_this.allowUpsideDown && _this.beta < 0) {
  44957. up = up.clone();
  44958. up = up.negate();
  44959. }
  44960. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44961. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44962. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44963. _this._collisionTriggered = false;
  44964. };
  44965. _this._target = BABYLON.Vector3.Zero();
  44966. if (target) {
  44967. _this.setTarget(target);
  44968. }
  44969. _this.alpha = alpha;
  44970. _this.beta = beta;
  44971. _this.radius = radius;
  44972. _this.getViewMatrix();
  44973. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44974. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44975. return _this;
  44976. }
  44977. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44978. get: function () {
  44979. return this._target;
  44980. },
  44981. set: function (value) {
  44982. this.setTarget(value);
  44983. },
  44984. enumerable: true,
  44985. configurable: true
  44986. });
  44987. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44988. //-- begin properties for backward compatibility for inputs
  44989. get: function () {
  44990. var pointers = this.inputs.attached["pointers"];
  44991. if (pointers)
  44992. return pointers.angularSensibilityX;
  44993. return 0;
  44994. },
  44995. set: function (value) {
  44996. var pointers = this.inputs.attached["pointers"];
  44997. if (pointers) {
  44998. pointers.angularSensibilityX = value;
  44999. }
  45000. },
  45001. enumerable: true,
  45002. configurable: true
  45003. });
  45004. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45005. get: function () {
  45006. var pointers = this.inputs.attached["pointers"];
  45007. if (pointers)
  45008. return pointers.angularSensibilityY;
  45009. return 0;
  45010. },
  45011. set: function (value) {
  45012. var pointers = this.inputs.attached["pointers"];
  45013. if (pointers) {
  45014. pointers.angularSensibilityY = value;
  45015. }
  45016. },
  45017. enumerable: true,
  45018. configurable: true
  45019. });
  45020. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45021. get: function () {
  45022. var pointers = this.inputs.attached["pointers"];
  45023. if (pointers)
  45024. return pointers.pinchPrecision;
  45025. return 0;
  45026. },
  45027. set: function (value) {
  45028. var pointers = this.inputs.attached["pointers"];
  45029. if (pointers) {
  45030. pointers.pinchPrecision = value;
  45031. }
  45032. },
  45033. enumerable: true,
  45034. configurable: true
  45035. });
  45036. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45037. get: function () {
  45038. var pointers = this.inputs.attached["pointers"];
  45039. if (pointers)
  45040. return pointers.pinchDeltaPercentage;
  45041. return 0;
  45042. },
  45043. set: function (value) {
  45044. var pointers = this.inputs.attached["pointers"];
  45045. if (pointers) {
  45046. pointers.pinchDeltaPercentage = value;
  45047. }
  45048. },
  45049. enumerable: true,
  45050. configurable: true
  45051. });
  45052. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45053. get: function () {
  45054. var pointers = this.inputs.attached["pointers"];
  45055. if (pointers)
  45056. return pointers.panningSensibility;
  45057. return 0;
  45058. },
  45059. set: function (value) {
  45060. var pointers = this.inputs.attached["pointers"];
  45061. if (pointers) {
  45062. pointers.panningSensibility = value;
  45063. }
  45064. },
  45065. enumerable: true,
  45066. configurable: true
  45067. });
  45068. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45069. get: function () {
  45070. var keyboard = this.inputs.attached["keyboard"];
  45071. if (keyboard)
  45072. return keyboard.keysUp;
  45073. return [];
  45074. },
  45075. set: function (value) {
  45076. var keyboard = this.inputs.attached["keyboard"];
  45077. if (keyboard)
  45078. keyboard.keysUp = value;
  45079. },
  45080. enumerable: true,
  45081. configurable: true
  45082. });
  45083. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45084. get: function () {
  45085. var keyboard = this.inputs.attached["keyboard"];
  45086. if (keyboard)
  45087. return keyboard.keysDown;
  45088. return [];
  45089. },
  45090. set: function (value) {
  45091. var keyboard = this.inputs.attached["keyboard"];
  45092. if (keyboard)
  45093. keyboard.keysDown = value;
  45094. },
  45095. enumerable: true,
  45096. configurable: true
  45097. });
  45098. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45099. get: function () {
  45100. var keyboard = this.inputs.attached["keyboard"];
  45101. if (keyboard)
  45102. return keyboard.keysLeft;
  45103. return [];
  45104. },
  45105. set: function (value) {
  45106. var keyboard = this.inputs.attached["keyboard"];
  45107. if (keyboard)
  45108. keyboard.keysLeft = value;
  45109. },
  45110. enumerable: true,
  45111. configurable: true
  45112. });
  45113. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45114. get: function () {
  45115. var keyboard = this.inputs.attached["keyboard"];
  45116. if (keyboard)
  45117. return keyboard.keysRight;
  45118. return [];
  45119. },
  45120. set: function (value) {
  45121. var keyboard = this.inputs.attached["keyboard"];
  45122. if (keyboard)
  45123. keyboard.keysRight = value;
  45124. },
  45125. enumerable: true,
  45126. configurable: true
  45127. });
  45128. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45129. get: function () {
  45130. var mousewheel = this.inputs.attached["mousewheel"];
  45131. if (mousewheel)
  45132. return mousewheel.wheelPrecision;
  45133. return 0;
  45134. },
  45135. set: function (value) {
  45136. var mousewheel = this.inputs.attached["mousewheel"];
  45137. if (mousewheel)
  45138. mousewheel.wheelPrecision = value;
  45139. },
  45140. enumerable: true,
  45141. configurable: true
  45142. });
  45143. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45144. get: function () {
  45145. var mousewheel = this.inputs.attached["mousewheel"];
  45146. if (mousewheel)
  45147. return mousewheel.wheelDeltaPercentage;
  45148. return 0;
  45149. },
  45150. set: function (value) {
  45151. var mousewheel = this.inputs.attached["mousewheel"];
  45152. if (mousewheel)
  45153. mousewheel.wheelDeltaPercentage = value;
  45154. },
  45155. enumerable: true,
  45156. configurable: true
  45157. });
  45158. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45159. get: function () {
  45160. return this._bouncingBehavior;
  45161. },
  45162. enumerable: true,
  45163. configurable: true
  45164. });
  45165. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45166. get: function () {
  45167. return this._bouncingBehavior != null;
  45168. },
  45169. set: function (value) {
  45170. if (value === this.useBouncingBehavior) {
  45171. return;
  45172. }
  45173. if (value) {
  45174. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45175. this.addBehavior(this._bouncingBehavior);
  45176. }
  45177. else if (this._bouncingBehavior) {
  45178. this.removeBehavior(this._bouncingBehavior);
  45179. this._bouncingBehavior = null;
  45180. }
  45181. },
  45182. enumerable: true,
  45183. configurable: true
  45184. });
  45185. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45186. get: function () {
  45187. return this._framingBehavior;
  45188. },
  45189. enumerable: true,
  45190. configurable: true
  45191. });
  45192. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45193. get: function () {
  45194. return this._framingBehavior != null;
  45195. },
  45196. set: function (value) {
  45197. if (value === this.useFramingBehavior) {
  45198. return;
  45199. }
  45200. if (value) {
  45201. this._framingBehavior = new BABYLON.FramingBehavior();
  45202. this.addBehavior(this._framingBehavior);
  45203. }
  45204. else if (this._framingBehavior) {
  45205. this.removeBehavior(this._framingBehavior);
  45206. this._framingBehavior = null;
  45207. }
  45208. },
  45209. enumerable: true,
  45210. configurable: true
  45211. });
  45212. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45213. get: function () {
  45214. return this._autoRotationBehavior;
  45215. },
  45216. enumerable: true,
  45217. configurable: true
  45218. });
  45219. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45220. get: function () {
  45221. return this._autoRotationBehavior != null;
  45222. },
  45223. set: function (value) {
  45224. if (value === this.useAutoRotationBehavior) {
  45225. return;
  45226. }
  45227. if (value) {
  45228. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45229. this.addBehavior(this._autoRotationBehavior);
  45230. }
  45231. else if (this._autoRotationBehavior) {
  45232. this.removeBehavior(this._autoRotationBehavior);
  45233. this._autoRotationBehavior = null;
  45234. }
  45235. },
  45236. enumerable: true,
  45237. configurable: true
  45238. });
  45239. // Cache
  45240. ArcRotateCamera.prototype._initCache = function () {
  45241. _super.prototype._initCache.call(this);
  45242. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45243. this._cache.alpha = undefined;
  45244. this._cache.beta = undefined;
  45245. this._cache.radius = undefined;
  45246. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45247. };
  45248. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45249. if (!ignoreParentClass) {
  45250. _super.prototype._updateCache.call(this);
  45251. }
  45252. this._cache._target.copyFrom(this._getTargetPosition());
  45253. this._cache.alpha = this.alpha;
  45254. this._cache.beta = this.beta;
  45255. this._cache.radius = this.radius;
  45256. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45257. };
  45258. ArcRotateCamera.prototype._getTargetPosition = function () {
  45259. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45260. var pos = this._targetHost.getAbsolutePosition();
  45261. if (this._targetBoundingCenter) {
  45262. pos.addToRef(this._targetBoundingCenter, this._target);
  45263. }
  45264. else {
  45265. this._target.copyFrom(pos);
  45266. }
  45267. }
  45268. var lockedTargetPosition = this._getLockedTargetPosition();
  45269. if (lockedTargetPosition) {
  45270. return lockedTargetPosition;
  45271. }
  45272. return this._target;
  45273. };
  45274. ArcRotateCamera.prototype.storeState = function () {
  45275. this._storedAlpha = this.alpha;
  45276. this._storedBeta = this.beta;
  45277. this._storedRadius = this.radius;
  45278. this._storedTarget = this._getTargetPosition().clone();
  45279. return _super.prototype.storeState.call(this);
  45280. };
  45281. /**
  45282. * Restored camera state. You must call storeState() first
  45283. */
  45284. ArcRotateCamera.prototype._restoreStateValues = function () {
  45285. if (!_super.prototype._restoreStateValues.call(this)) {
  45286. return false;
  45287. }
  45288. this.alpha = this._storedAlpha;
  45289. this.beta = this._storedBeta;
  45290. this.radius = this._storedRadius;
  45291. this.setTarget(this._storedTarget.clone());
  45292. this.inertialAlphaOffset = 0;
  45293. this.inertialBetaOffset = 0;
  45294. this.inertialRadiusOffset = 0;
  45295. this.inertialPanningX = 0;
  45296. this.inertialPanningY = 0;
  45297. return true;
  45298. };
  45299. // Synchronized
  45300. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45301. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45302. return false;
  45303. return this._cache._target.equals(this._getTargetPosition())
  45304. && this._cache.alpha === this.alpha
  45305. && this._cache.beta === this.beta
  45306. && this._cache.radius === this.radius
  45307. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45308. };
  45309. // Methods
  45310. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45311. var _this = this;
  45312. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45313. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45314. this._useCtrlForPanning = useCtrlForPanning;
  45315. this._panningMouseButton = panningMouseButton;
  45316. this.inputs.attachElement(element, noPreventDefault);
  45317. this._reset = function () {
  45318. _this.inertialAlphaOffset = 0;
  45319. _this.inertialBetaOffset = 0;
  45320. _this.inertialRadiusOffset = 0;
  45321. _this.inertialPanningX = 0;
  45322. _this.inertialPanningY = 0;
  45323. };
  45324. };
  45325. ArcRotateCamera.prototype.detachControl = function (element) {
  45326. this.inputs.detachElement(element);
  45327. if (this._reset) {
  45328. this._reset();
  45329. }
  45330. };
  45331. ArcRotateCamera.prototype._checkInputs = function () {
  45332. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45333. if (this._collisionTriggered) {
  45334. return;
  45335. }
  45336. this.inputs.checkInputs();
  45337. // Inertia
  45338. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45339. if (this.getScene().useRightHandedSystem) {
  45340. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45341. }
  45342. else {
  45343. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45344. }
  45345. this.beta += this.inertialBetaOffset;
  45346. this.radius -= this.inertialRadiusOffset;
  45347. this.inertialAlphaOffset *= this.inertia;
  45348. this.inertialBetaOffset *= this.inertia;
  45349. this.inertialRadiusOffset *= this.inertia;
  45350. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45351. this.inertialAlphaOffset = 0;
  45352. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45353. this.inertialBetaOffset = 0;
  45354. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45355. this.inertialRadiusOffset = 0;
  45356. }
  45357. // Panning inertia
  45358. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45359. if (!this._localDirection) {
  45360. this._localDirection = BABYLON.Vector3.Zero();
  45361. this._transformedDirection = BABYLON.Vector3.Zero();
  45362. }
  45363. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45364. this._localDirection.multiplyInPlace(this.panningAxis);
  45365. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45366. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45367. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45368. if (!this.panningAxis.y) {
  45369. this._transformedDirection.y = 0;
  45370. }
  45371. if (!this._targetHost) {
  45372. if (this.panningDistanceLimit) {
  45373. this._transformedDirection.addInPlace(this._target);
  45374. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45375. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45376. this._target.copyFrom(this._transformedDirection);
  45377. }
  45378. }
  45379. else {
  45380. this._target.addInPlace(this._transformedDirection);
  45381. }
  45382. }
  45383. this.inertialPanningX *= this.panningInertia;
  45384. this.inertialPanningY *= this.panningInertia;
  45385. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45386. this.inertialPanningX = 0;
  45387. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45388. this.inertialPanningY = 0;
  45389. }
  45390. // Limits
  45391. this._checkLimits();
  45392. _super.prototype._checkInputs.call(this);
  45393. };
  45394. ArcRotateCamera.prototype._checkLimits = function () {
  45395. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45396. if (this.allowUpsideDown && this.beta > Math.PI) {
  45397. this.beta = this.beta - (2 * Math.PI);
  45398. }
  45399. }
  45400. else {
  45401. if (this.beta < this.lowerBetaLimit) {
  45402. this.beta = this.lowerBetaLimit;
  45403. }
  45404. }
  45405. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45406. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45407. this.beta = this.beta + (2 * Math.PI);
  45408. }
  45409. }
  45410. else {
  45411. if (this.beta > this.upperBetaLimit) {
  45412. this.beta = this.upperBetaLimit;
  45413. }
  45414. }
  45415. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45416. this.alpha = this.lowerAlphaLimit;
  45417. }
  45418. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45419. this.alpha = this.upperAlphaLimit;
  45420. }
  45421. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45422. this.radius = this.lowerRadiusLimit;
  45423. }
  45424. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45425. this.radius = this.upperRadiusLimit;
  45426. }
  45427. };
  45428. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45429. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45430. this.radius = this._computationVector.length();
  45431. if (this.radius === 0) {
  45432. this.radius = 0.0001; // Just to avoid division by zero
  45433. }
  45434. // Alpha
  45435. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45436. if (this._computationVector.z < 0) {
  45437. this.alpha = 2 * Math.PI - this.alpha;
  45438. }
  45439. // Beta
  45440. this.beta = Math.acos(this._computationVector.y / this.radius);
  45441. this._checkLimits();
  45442. };
  45443. ArcRotateCamera.prototype.setPosition = function (position) {
  45444. if (this.position.equals(position)) {
  45445. return;
  45446. }
  45447. this.position.copyFrom(position);
  45448. this.rebuildAnglesAndRadius();
  45449. };
  45450. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45451. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45452. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45453. if (target.getBoundingInfo) {
  45454. if (toBoundingCenter) {
  45455. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45456. }
  45457. else {
  45458. this._targetBoundingCenter = null;
  45459. }
  45460. this._targetHost = target;
  45461. this._target = this._getTargetPosition();
  45462. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45463. }
  45464. else {
  45465. var newTarget = target;
  45466. var currentTarget = this._getTargetPosition();
  45467. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45468. return;
  45469. }
  45470. this._targetHost = null;
  45471. this._target = newTarget;
  45472. this._targetBoundingCenter = null;
  45473. this.onMeshTargetChangedObservable.notifyObservers(null);
  45474. }
  45475. this.rebuildAnglesAndRadius();
  45476. };
  45477. ArcRotateCamera.prototype._getViewMatrix = function () {
  45478. // Compute
  45479. var cosa = Math.cos(this.alpha);
  45480. var sina = Math.sin(this.alpha);
  45481. var cosb = Math.cos(this.beta);
  45482. var sinb = Math.sin(this.beta);
  45483. if (sinb === 0) {
  45484. sinb = 0.0001;
  45485. }
  45486. var target = this._getTargetPosition();
  45487. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45488. target.addToRef(this._computationVector, this._newPosition);
  45489. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45490. if (!this._collider) {
  45491. this._collider = new BABYLON.Collider();
  45492. }
  45493. this._collider._radius = this.collisionRadius;
  45494. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45495. this._collisionTriggered = true;
  45496. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45497. }
  45498. else {
  45499. this.position.copyFrom(this._newPosition);
  45500. var up = this.upVector;
  45501. if (this.allowUpsideDown && sinb < 0) {
  45502. up = up.clone();
  45503. up = up.negate();
  45504. }
  45505. if (this.getScene().useRightHandedSystem) {
  45506. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45507. }
  45508. else {
  45509. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45510. }
  45511. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45512. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45513. }
  45514. this._currentTarget = target;
  45515. return this._viewMatrix;
  45516. };
  45517. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45518. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45519. meshes = meshes || this.getScene().meshes;
  45520. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45521. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45522. this.radius = distance * this.zoomOnFactor;
  45523. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45524. };
  45525. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45526. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45527. var meshesOrMinMaxVector;
  45528. var distance;
  45529. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45530. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45531. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45532. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45533. }
  45534. else {
  45535. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45536. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45537. distance = minMaxVectorAndDistance.distance;
  45538. }
  45539. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45540. if (!doNotUpdateMaxZ) {
  45541. this.maxZ = distance * 2;
  45542. }
  45543. };
  45544. /**
  45545. * @override
  45546. * Override Camera.createRigCamera
  45547. */
  45548. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45549. var alphaShift = 0;
  45550. switch (this.cameraRigMode) {
  45551. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45552. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45553. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45554. case BABYLON.Camera.RIG_MODE_VR:
  45555. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45556. break;
  45557. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45558. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45559. break;
  45560. }
  45561. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45562. rigCam._cameraRigParams = {};
  45563. return rigCam;
  45564. };
  45565. /**
  45566. * @override
  45567. * Override Camera._updateRigCameras
  45568. */
  45569. ArcRotateCamera.prototype._updateRigCameras = function () {
  45570. var camLeft = this._rigCameras[0];
  45571. var camRight = this._rigCameras[1];
  45572. camLeft.beta = camRight.beta = this.beta;
  45573. camLeft.radius = camRight.radius = this.radius;
  45574. switch (this.cameraRigMode) {
  45575. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45576. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45577. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45578. case BABYLON.Camera.RIG_MODE_VR:
  45579. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45580. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45581. break;
  45582. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45583. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45584. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45585. break;
  45586. }
  45587. _super.prototype._updateRigCameras.call(this);
  45588. };
  45589. ArcRotateCamera.prototype.dispose = function () {
  45590. this.inputs.clear();
  45591. _super.prototype.dispose.call(this);
  45592. };
  45593. ArcRotateCamera.prototype.getClassName = function () {
  45594. return "ArcRotateCamera";
  45595. };
  45596. __decorate([
  45597. BABYLON.serialize()
  45598. ], ArcRotateCamera.prototype, "alpha", void 0);
  45599. __decorate([
  45600. BABYLON.serialize()
  45601. ], ArcRotateCamera.prototype, "beta", void 0);
  45602. __decorate([
  45603. BABYLON.serialize()
  45604. ], ArcRotateCamera.prototype, "radius", void 0);
  45605. __decorate([
  45606. BABYLON.serializeAsVector3("target")
  45607. ], ArcRotateCamera.prototype, "_target", void 0);
  45608. __decorate([
  45609. BABYLON.serialize()
  45610. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45611. __decorate([
  45612. BABYLON.serialize()
  45613. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45614. __decorate([
  45615. BABYLON.serialize()
  45616. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45617. __decorate([
  45618. BABYLON.serialize()
  45619. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45620. __decorate([
  45621. BABYLON.serialize()
  45622. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45623. __decorate([
  45624. BABYLON.serialize()
  45625. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45626. __decorate([
  45627. BABYLON.serialize()
  45628. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45629. __decorate([
  45630. BABYLON.serialize()
  45631. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45632. __decorate([
  45633. BABYLON.serialize()
  45634. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45635. __decorate([
  45636. BABYLON.serialize()
  45637. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45638. __decorate([
  45639. BABYLON.serialize()
  45640. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45641. __decorate([
  45642. BABYLON.serialize()
  45643. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45644. __decorate([
  45645. BABYLON.serialize()
  45646. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45647. __decorate([
  45648. BABYLON.serializeAsVector3()
  45649. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45650. __decorate([
  45651. BABYLON.serialize()
  45652. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45653. __decorate([
  45654. BABYLON.serialize()
  45655. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45656. __decorate([
  45657. BABYLON.serialize()
  45658. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45659. return ArcRotateCamera;
  45660. }(BABYLON.TargetCamera));
  45661. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45662. })(BABYLON || (BABYLON = {}));
  45663. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45664. var BABYLON;
  45665. (function (BABYLON) {
  45666. /**
  45667. * The HemisphericLight simulates the ambient environment light,
  45668. * so the passed direction is the light reflection direction, not the incoming direction.
  45669. */
  45670. var HemisphericLight = /** @class */ (function (_super) {
  45671. __extends(HemisphericLight, _super);
  45672. /**
  45673. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45674. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45675. * The HemisphericLight can't cast shadows.
  45676. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45677. * @param name The friendly name of the light
  45678. * @param direction The direction of the light reflection
  45679. * @param scene The scene the light belongs to
  45680. */
  45681. function HemisphericLight(name, direction, scene) {
  45682. var _this = _super.call(this, name, scene) || this;
  45683. /**
  45684. * The groundColor is the light in the opposite direction to the one specified during creation.
  45685. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  45686. */
  45687. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45688. _this.direction = direction || BABYLON.Vector3.Up();
  45689. return _this;
  45690. }
  45691. HemisphericLight.prototype._buildUniformLayout = function () {
  45692. this._uniformBuffer.addUniform("vLightData", 4);
  45693. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45694. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45695. this._uniformBuffer.addUniform("vLightGround", 3);
  45696. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45697. this._uniformBuffer.addUniform("depthValues", 2);
  45698. this._uniformBuffer.create();
  45699. };
  45700. /**
  45701. * Returns the string "HemisphericLight".
  45702. * @return The class name
  45703. */
  45704. HemisphericLight.prototype.getClassName = function () {
  45705. return "HemisphericLight";
  45706. };
  45707. /**
  45708. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45709. * Returns the updated direction.
  45710. * @param target The target the direction should point to
  45711. * @return The computed direction
  45712. */
  45713. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45714. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45715. return this.direction;
  45716. };
  45717. /**
  45718. * Returns the shadow generator associated to the light.
  45719. * @returns Always null for hemispheric lights because it does not support shadows.
  45720. */
  45721. HemisphericLight.prototype.getShadowGenerator = function () {
  45722. return null;
  45723. };
  45724. /**
  45725. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45726. * @param effect The effect to update
  45727. * @param lightIndex The index of the light in the effect to update
  45728. * @returns The hemispheric light
  45729. */
  45730. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45731. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45732. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45733. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45734. return this;
  45735. };
  45736. /**
  45737. * @ignore internal use only.
  45738. */
  45739. HemisphericLight.prototype._getWorldMatrix = function () {
  45740. if (!this._worldMatrix) {
  45741. this._worldMatrix = BABYLON.Matrix.Identity();
  45742. }
  45743. return this._worldMatrix;
  45744. };
  45745. /**
  45746. * Returns the integer 3.
  45747. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45748. */
  45749. HemisphericLight.prototype.getTypeID = function () {
  45750. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45751. };
  45752. __decorate([
  45753. BABYLON.serializeAsColor3()
  45754. ], HemisphericLight.prototype, "groundColor", void 0);
  45755. __decorate([
  45756. BABYLON.serializeAsVector3()
  45757. ], HemisphericLight.prototype, "direction", void 0);
  45758. return HemisphericLight;
  45759. }(BABYLON.Light));
  45760. BABYLON.HemisphericLight = HemisphericLight;
  45761. })(BABYLON || (BABYLON = {}));
  45762. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45763. var BABYLON;
  45764. (function (BABYLON) {
  45765. /**
  45766. * Base implementation of @see IShadowLight
  45767. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45768. */
  45769. var ShadowLight = /** @class */ (function (_super) {
  45770. __extends(ShadowLight, _super);
  45771. function ShadowLight() {
  45772. var _this = _super !== null && _super.apply(this, arguments) || this;
  45773. _this._needProjectionMatrixCompute = true;
  45774. return _this;
  45775. }
  45776. ShadowLight.prototype._setPosition = function (value) {
  45777. this._position = value;
  45778. };
  45779. Object.defineProperty(ShadowLight.prototype, "position", {
  45780. /**
  45781. * Sets the position the shadow will be casted from. Also use as the light position for both
  45782. * point and spot lights.
  45783. */
  45784. get: function () {
  45785. return this._position;
  45786. },
  45787. /**
  45788. * Sets the position the shadow will be casted from. Also use as the light position for both
  45789. * point and spot lights.
  45790. */
  45791. set: function (value) {
  45792. this._setPosition(value);
  45793. },
  45794. enumerable: true,
  45795. configurable: true
  45796. });
  45797. ShadowLight.prototype._setDirection = function (value) {
  45798. this._direction = value;
  45799. };
  45800. Object.defineProperty(ShadowLight.prototype, "direction", {
  45801. /**
  45802. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45803. * Also use as the light direction on spot and directional lights.
  45804. */
  45805. get: function () {
  45806. return this._direction;
  45807. },
  45808. /**
  45809. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45810. * Also use as the light direction on spot and directional lights.
  45811. */
  45812. set: function (value) {
  45813. this._setDirection(value);
  45814. },
  45815. enumerable: true,
  45816. configurable: true
  45817. });
  45818. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45819. /**
  45820. * Gets the shadow projection clipping minimum z value.
  45821. */
  45822. get: function () {
  45823. return this._shadowMinZ;
  45824. },
  45825. /**
  45826. * Sets the shadow projection clipping minimum z value.
  45827. */
  45828. set: function (value) {
  45829. this._shadowMinZ = value;
  45830. this.forceProjectionMatrixCompute();
  45831. },
  45832. enumerable: true,
  45833. configurable: true
  45834. });
  45835. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45836. /**
  45837. * Sets the shadow projection clipping maximum z value.
  45838. */
  45839. get: function () {
  45840. return this._shadowMaxZ;
  45841. },
  45842. /**
  45843. * Gets the shadow projection clipping maximum z value.
  45844. */
  45845. set: function (value) {
  45846. this._shadowMaxZ = value;
  45847. this.forceProjectionMatrixCompute();
  45848. },
  45849. enumerable: true,
  45850. configurable: true
  45851. });
  45852. /**
  45853. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45854. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45855. */
  45856. ShadowLight.prototype.computeTransformedInformation = function () {
  45857. if (this.parent && this.parent.getWorldMatrix) {
  45858. if (!this.transformedPosition) {
  45859. this.transformedPosition = BABYLON.Vector3.Zero();
  45860. }
  45861. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45862. // In case the direction is present.
  45863. if (this.direction) {
  45864. if (!this.transformedDirection) {
  45865. this.transformedDirection = BABYLON.Vector3.Zero();
  45866. }
  45867. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45868. }
  45869. return true;
  45870. }
  45871. return false;
  45872. };
  45873. /**
  45874. * Return the depth scale used for the shadow map.
  45875. * @returns the depth scale.
  45876. */
  45877. ShadowLight.prototype.getDepthScale = function () {
  45878. return 50.0;
  45879. };
  45880. /**
  45881. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45882. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45883. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45884. */
  45885. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45886. return this.transformedDirection ? this.transformedDirection : this.direction;
  45887. };
  45888. /**
  45889. * Returns the ShadowLight absolute position in the World.
  45890. * @returns the position vector in world space
  45891. */
  45892. ShadowLight.prototype.getAbsolutePosition = function () {
  45893. return this.transformedPosition ? this.transformedPosition : this.position;
  45894. };
  45895. /**
  45896. * Sets the ShadowLight direction toward the passed target.
  45897. * @param target The point tot target in local space
  45898. * @returns the updated ShadowLight direction
  45899. */
  45900. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45901. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45902. return this.direction;
  45903. };
  45904. /**
  45905. * Returns the light rotation in euler definition.
  45906. * @returns the x y z rotation in local space.
  45907. */
  45908. ShadowLight.prototype.getRotation = function () {
  45909. this.direction.normalize();
  45910. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45911. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45912. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45913. };
  45914. /**
  45915. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45916. * @returns true if a cube texture needs to be use
  45917. */
  45918. ShadowLight.prototype.needCube = function () {
  45919. return false;
  45920. };
  45921. /**
  45922. * Detects if the projection matrix requires to be recomputed this frame.
  45923. * @returns true if it requires to be recomputed otherwise, false.
  45924. */
  45925. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45926. return this._needProjectionMatrixCompute;
  45927. };
  45928. /**
  45929. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45930. */
  45931. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45932. this._needProjectionMatrixCompute = true;
  45933. };
  45934. /**
  45935. * Get the world matrix of the sahdow lights.
  45936. * @ignore Internal Use Only
  45937. */
  45938. ShadowLight.prototype._getWorldMatrix = function () {
  45939. if (!this._worldMatrix) {
  45940. this._worldMatrix = BABYLON.Matrix.Identity();
  45941. }
  45942. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45943. return this._worldMatrix;
  45944. };
  45945. /**
  45946. * Gets the minZ used for shadow according to both the scene and the light.
  45947. * @param activeCamera The camera we are returning the min for
  45948. * @returns the depth min z
  45949. */
  45950. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45951. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45952. };
  45953. /**
  45954. * Gets the maxZ used for shadow according to both the scene and the light.
  45955. * @param activeCamera The camera we are returning the max for
  45956. * @returns the depth max z
  45957. */
  45958. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45959. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45960. };
  45961. /**
  45962. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45963. * @param matrix The materix to updated with the projection information
  45964. * @param viewMatrix The transform matrix of the light
  45965. * @param renderList The list of mesh to render in the map
  45966. * @returns The current light
  45967. */
  45968. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45969. if (this.customProjectionMatrixBuilder) {
  45970. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45971. }
  45972. else {
  45973. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45974. }
  45975. return this;
  45976. };
  45977. __decorate([
  45978. BABYLON.serializeAsVector3()
  45979. ], ShadowLight.prototype, "position", null);
  45980. __decorate([
  45981. BABYLON.serializeAsVector3()
  45982. ], ShadowLight.prototype, "direction", null);
  45983. __decorate([
  45984. BABYLON.serialize()
  45985. ], ShadowLight.prototype, "shadowMinZ", null);
  45986. __decorate([
  45987. BABYLON.serialize()
  45988. ], ShadowLight.prototype, "shadowMaxZ", null);
  45989. return ShadowLight;
  45990. }(BABYLON.Light));
  45991. BABYLON.ShadowLight = ShadowLight;
  45992. })(BABYLON || (BABYLON = {}));
  45993. //# sourceMappingURL=babylon.shadowLight.js.map
  45994. var BABYLON;
  45995. (function (BABYLON) {
  45996. /**
  45997. * A point light is a light defined by an unique point in world space.
  45998. * The light is emitted in every direction from this point.
  45999. * A good example of a point light is a standard light bulb.
  46000. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46001. */
  46002. var PointLight = /** @class */ (function (_super) {
  46003. __extends(PointLight, _super);
  46004. /**
  46005. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46006. * A PointLight emits the light in every direction.
  46007. * It can cast shadows.
  46008. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46009. * ```javascript
  46010. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46011. * ```
  46012. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46013. * @param name The light friendly name
  46014. * @param position The position of the point light in the scene
  46015. * @param scene The scene the lights belongs to
  46016. */
  46017. function PointLight(name, position, scene) {
  46018. var _this = _super.call(this, name, scene) || this;
  46019. _this._shadowAngle = Math.PI / 2;
  46020. _this.position = position;
  46021. return _this;
  46022. }
  46023. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46024. /**
  46025. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46026. * This specifies what angle the shadow will use to be created.
  46027. *
  46028. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46029. */
  46030. get: function () {
  46031. return this._shadowAngle;
  46032. },
  46033. /**
  46034. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46035. * This specifies what angle the shadow will use to be created.
  46036. *
  46037. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46038. */
  46039. set: function (value) {
  46040. this._shadowAngle = value;
  46041. this.forceProjectionMatrixCompute();
  46042. },
  46043. enumerable: true,
  46044. configurable: true
  46045. });
  46046. Object.defineProperty(PointLight.prototype, "direction", {
  46047. /**
  46048. * Gets the direction if it has been set.
  46049. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46050. */
  46051. get: function () {
  46052. return this._direction;
  46053. },
  46054. /**
  46055. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46056. */
  46057. set: function (value) {
  46058. var previousNeedCube = this.needCube();
  46059. this._direction = value;
  46060. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46061. this._shadowGenerator.recreateShadowMap();
  46062. }
  46063. },
  46064. enumerable: true,
  46065. configurable: true
  46066. });
  46067. /**
  46068. * Returns the string "PointLight"
  46069. * @returns the class name
  46070. */
  46071. PointLight.prototype.getClassName = function () {
  46072. return "PointLight";
  46073. };
  46074. /**
  46075. * Returns the integer 0.
  46076. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46077. */
  46078. PointLight.prototype.getTypeID = function () {
  46079. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46080. };
  46081. /**
  46082. * Specifies wether or not the shadowmap should be a cube texture.
  46083. * @returns true if the shadowmap needs to be a cube texture.
  46084. */
  46085. PointLight.prototype.needCube = function () {
  46086. return !this.direction;
  46087. };
  46088. /**
  46089. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46090. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46091. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46092. */
  46093. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46094. if (this.direction) {
  46095. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46096. }
  46097. else {
  46098. switch (faceIndex) {
  46099. case 0:
  46100. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46101. case 1:
  46102. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46103. case 2:
  46104. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46105. case 3:
  46106. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46107. case 4:
  46108. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46109. case 5:
  46110. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46111. }
  46112. }
  46113. return BABYLON.Vector3.Zero();
  46114. };
  46115. /**
  46116. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46117. * - fov = PI / 2
  46118. * - aspect ratio : 1.0
  46119. * - z-near and far equal to the active camera minZ and maxZ.
  46120. * Returns the PointLight.
  46121. */
  46122. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46123. var activeCamera = this.getScene().activeCamera;
  46124. if (!activeCamera) {
  46125. return;
  46126. }
  46127. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46128. };
  46129. PointLight.prototype._buildUniformLayout = function () {
  46130. this._uniformBuffer.addUniform("vLightData", 4);
  46131. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46132. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46133. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46134. this._uniformBuffer.addUniform("depthValues", 2);
  46135. this._uniformBuffer.create();
  46136. };
  46137. /**
  46138. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46139. * @param effect The effect to update
  46140. * @param lightIndex The index of the light in the effect to update
  46141. * @returns The point light
  46142. */
  46143. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46144. if (this.computeTransformedInformation()) {
  46145. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46146. return this;
  46147. }
  46148. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46149. return this;
  46150. };
  46151. __decorate([
  46152. BABYLON.serialize()
  46153. ], PointLight.prototype, "shadowAngle", null);
  46154. return PointLight;
  46155. }(BABYLON.ShadowLight));
  46156. BABYLON.PointLight = PointLight;
  46157. })(BABYLON || (BABYLON = {}));
  46158. //# sourceMappingURL=babylon.pointLight.js.map
  46159. var BABYLON;
  46160. (function (BABYLON) {
  46161. /**
  46162. * A directional light is defined by a direction (what a surprise!).
  46163. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46164. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  46165. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46166. */
  46167. var DirectionalLight = /** @class */ (function (_super) {
  46168. __extends(DirectionalLight, _super);
  46169. /**
  46170. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46171. * The directional light is emitted from everywhere in the given direction.
  46172. * It can cast shawdows.
  46173. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46174. * @param name The friendly name of the light
  46175. * @param direction The direction of the light
  46176. * @param scene The scene the light belongs to
  46177. */
  46178. function DirectionalLight(name, direction, scene) {
  46179. var _this = _super.call(this, name, scene) || this;
  46180. _this._shadowFrustumSize = 0;
  46181. _this._shadowOrthoScale = 0.1;
  46182. /**
  46183. * Automatically compute the projection matrix to best fit (including all the casters)
  46184. * on each frame.
  46185. */
  46186. _this.autoUpdateExtends = true;
  46187. // Cache
  46188. _this._orthoLeft = Number.MAX_VALUE;
  46189. _this._orthoRight = Number.MIN_VALUE;
  46190. _this._orthoTop = Number.MIN_VALUE;
  46191. _this._orthoBottom = Number.MAX_VALUE;
  46192. _this.position = direction.scale(-1.0);
  46193. _this.direction = direction;
  46194. return _this;
  46195. }
  46196. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46197. /**
  46198. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46199. */
  46200. get: function () {
  46201. return this._shadowFrustumSize;
  46202. },
  46203. /**
  46204. * Specifies a fix frustum size for the shadow generation.
  46205. */
  46206. set: function (value) {
  46207. this._shadowFrustumSize = value;
  46208. this.forceProjectionMatrixCompute();
  46209. },
  46210. enumerable: true,
  46211. configurable: true
  46212. });
  46213. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46214. /**
  46215. * Gets the shadow projection scale against the optimal computed one.
  46216. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46217. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46218. */
  46219. get: function () {
  46220. return this._shadowOrthoScale;
  46221. },
  46222. /**
  46223. * Sets the shadow projection scale against the optimal computed one.
  46224. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46225. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46226. */
  46227. set: function (value) {
  46228. this._shadowOrthoScale = value;
  46229. this.forceProjectionMatrixCompute();
  46230. },
  46231. enumerable: true,
  46232. configurable: true
  46233. });
  46234. /**
  46235. * Returns the string "DirectionalLight".
  46236. * @return The class name
  46237. */
  46238. DirectionalLight.prototype.getClassName = function () {
  46239. return "DirectionalLight";
  46240. };
  46241. /**
  46242. * Returns the integer 1.
  46243. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46244. */
  46245. DirectionalLight.prototype.getTypeID = function () {
  46246. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46247. };
  46248. /**
  46249. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46250. * Returns the DirectionalLight Shadow projection matrix.
  46251. */
  46252. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46253. if (this.shadowFrustumSize > 0) {
  46254. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46255. }
  46256. else {
  46257. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46258. }
  46259. };
  46260. /**
  46261. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46262. * Returns the DirectionalLight Shadow projection matrix.
  46263. */
  46264. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46265. var activeCamera = this.getScene().activeCamera;
  46266. if (!activeCamera) {
  46267. return;
  46268. }
  46269. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46270. };
  46271. /**
  46272. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46273. * Returns the DirectionalLight Shadow projection matrix.
  46274. */
  46275. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46276. var activeCamera = this.getScene().activeCamera;
  46277. if (!activeCamera) {
  46278. return;
  46279. }
  46280. // Check extends
  46281. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46282. var tempVector3 = BABYLON.Vector3.Zero();
  46283. this._orthoLeft = Number.MAX_VALUE;
  46284. this._orthoRight = Number.MIN_VALUE;
  46285. this._orthoTop = Number.MIN_VALUE;
  46286. this._orthoBottom = Number.MAX_VALUE;
  46287. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46288. var mesh = renderList[meshIndex];
  46289. if (!mesh) {
  46290. continue;
  46291. }
  46292. var boundingInfo = mesh.getBoundingInfo();
  46293. var boundingBox = boundingInfo.boundingBox;
  46294. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46295. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46296. if (tempVector3.x < this._orthoLeft)
  46297. this._orthoLeft = tempVector3.x;
  46298. if (tempVector3.y < this._orthoBottom)
  46299. this._orthoBottom = tempVector3.y;
  46300. if (tempVector3.x > this._orthoRight)
  46301. this._orthoRight = tempVector3.x;
  46302. if (tempVector3.y > this._orthoTop)
  46303. this._orthoTop = tempVector3.y;
  46304. }
  46305. }
  46306. }
  46307. var xOffset = this._orthoRight - this._orthoLeft;
  46308. var yOffset = this._orthoTop - this._orthoBottom;
  46309. 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);
  46310. };
  46311. DirectionalLight.prototype._buildUniformLayout = function () {
  46312. this._uniformBuffer.addUniform("vLightData", 4);
  46313. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46314. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46315. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46316. this._uniformBuffer.addUniform("depthValues", 2);
  46317. this._uniformBuffer.create();
  46318. };
  46319. /**
  46320. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46321. * @param effect The effect to update
  46322. * @param lightIndex The index of the light in the effect to update
  46323. * @returns The directional light
  46324. */
  46325. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46326. if (this.computeTransformedInformation()) {
  46327. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46328. return this;
  46329. }
  46330. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46331. return this;
  46332. };
  46333. /**
  46334. * Gets the minZ used for shadow according to both the scene and the light.
  46335. *
  46336. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46337. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46338. * @param activeCamera The camera we are returning the min for
  46339. * @returns the depth min z
  46340. */
  46341. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46342. return 1;
  46343. };
  46344. /**
  46345. * Gets the maxZ used for shadow according to both the scene and the light.
  46346. *
  46347. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46348. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46349. * @param activeCamera The camera we are returning the max for
  46350. * @returns the depth max z
  46351. */
  46352. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46353. return 1;
  46354. };
  46355. __decorate([
  46356. BABYLON.serialize()
  46357. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46358. __decorate([
  46359. BABYLON.serialize()
  46360. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46361. __decorate([
  46362. BABYLON.serialize()
  46363. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46364. return DirectionalLight;
  46365. }(BABYLON.ShadowLight));
  46366. BABYLON.DirectionalLight = DirectionalLight;
  46367. })(BABYLON || (BABYLON = {}));
  46368. //# sourceMappingURL=babylon.directionalLight.js.map
  46369. var BABYLON;
  46370. (function (BABYLON) {
  46371. /**
  46372. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46373. * These values define a cone of light starting from the position, emitting toward the direction.
  46374. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46375. * and the exponent defines the speed of the decay of the light with distance (reach).
  46376. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46377. */
  46378. var SpotLight = /** @class */ (function (_super) {
  46379. __extends(SpotLight, _super);
  46380. /**
  46381. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46382. * It can cast shadows.
  46383. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46384. * @param name The light friendly name
  46385. * @param position The position of the spot light in the scene
  46386. * @param direction The direction of the light in the scene
  46387. * @param angle The cone angle of the light in Radians
  46388. * @param exponent The light decay speed with the distance from the emission spot
  46389. * @param scene The scene the lights belongs to
  46390. */
  46391. function SpotLight(name, position, direction, angle, exponent, scene) {
  46392. var _this = _super.call(this, name, scene) || this;
  46393. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46394. _this._projectionTextureLightNear = 1e-6;
  46395. _this._projectionTextureLightFar = 1000.0;
  46396. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46397. _this._projectionTextureViewLightDirty = true;
  46398. _this._projectionTextureProjectionLightDirty = true;
  46399. _this._projectionTextureDirty = true;
  46400. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46401. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46402. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46403. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  46404. _this.position = position;
  46405. _this.direction = direction;
  46406. _this.angle = angle;
  46407. _this.exponent = exponent;
  46408. return _this;
  46409. }
  46410. Object.defineProperty(SpotLight.prototype, "angle", {
  46411. /**
  46412. * Gets the cone angle of the spot light in Radians.
  46413. */
  46414. get: function () {
  46415. return this._angle;
  46416. },
  46417. /**
  46418. * Sets the cone angle of the spot light in Radians.
  46419. */
  46420. set: function (value) {
  46421. this._angle = value;
  46422. this._projectionTextureProjectionLightDirty = true;
  46423. this.forceProjectionMatrixCompute();
  46424. },
  46425. enumerable: true,
  46426. configurable: true
  46427. });
  46428. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46429. /**
  46430. * Allows scaling the angle of the light for shadow generation only.
  46431. */
  46432. get: function () {
  46433. return this._shadowAngleScale;
  46434. },
  46435. /**
  46436. * Allows scaling the angle of the light for shadow generation only.
  46437. */
  46438. set: function (value) {
  46439. this._shadowAngleScale = value;
  46440. this.forceProjectionMatrixCompute();
  46441. },
  46442. enumerable: true,
  46443. configurable: true
  46444. });
  46445. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46446. /**
  46447. * Allows reading the projecton texture
  46448. */
  46449. get: function () {
  46450. return this._projectionTextureMatrix;
  46451. },
  46452. enumerable: true,
  46453. configurable: true
  46454. });
  46455. ;
  46456. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46457. /**
  46458. * Gets the near clip of the Spotlight for texture projection.
  46459. */
  46460. get: function () {
  46461. return this._projectionTextureLightNear;
  46462. },
  46463. /**
  46464. * Sets the near clip of the Spotlight for texture projection.
  46465. */
  46466. set: function (value) {
  46467. this._projectionTextureLightNear = value;
  46468. this._projectionTextureProjectionLightDirty = true;
  46469. },
  46470. enumerable: true,
  46471. configurable: true
  46472. });
  46473. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46474. /**
  46475. * Gets the far clip of the Spotlight for texture projection.
  46476. */
  46477. get: function () {
  46478. return this._projectionTextureLightFar;
  46479. },
  46480. /**
  46481. * Sets the far clip of the Spotlight for texture projection.
  46482. */
  46483. set: function (value) {
  46484. this._projectionTextureLightFar = value;
  46485. this._projectionTextureProjectionLightDirty = true;
  46486. },
  46487. enumerable: true,
  46488. configurable: true
  46489. });
  46490. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46491. /**
  46492. * Gets the Up vector of the Spotlight for texture projection.
  46493. */
  46494. get: function () {
  46495. return this._projectionTextureUpDirection;
  46496. },
  46497. /**
  46498. * Sets the Up vector of the Spotlight for texture projection.
  46499. */
  46500. set: function (value) {
  46501. this._projectionTextureUpDirection = value;
  46502. this._projectionTextureProjectionLightDirty = true;
  46503. },
  46504. enumerable: true,
  46505. configurable: true
  46506. });
  46507. ;
  46508. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46509. /**
  46510. * Gets the projection texture of the light.
  46511. */
  46512. get: function () {
  46513. return this._projectionTexture;
  46514. },
  46515. /**
  46516. * Sets the projection texture of the light.
  46517. */
  46518. set: function (value) {
  46519. this._projectionTexture = value;
  46520. this._projectionTextureDirty = true;
  46521. },
  46522. enumerable: true,
  46523. configurable: true
  46524. });
  46525. /**
  46526. * Returns the string "SpotLight".
  46527. * @returns the class name
  46528. */
  46529. SpotLight.prototype.getClassName = function () {
  46530. return "SpotLight";
  46531. };
  46532. /**
  46533. * Returns the integer 2.
  46534. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46535. */
  46536. SpotLight.prototype.getTypeID = function () {
  46537. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46538. };
  46539. /**
  46540. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46541. */
  46542. SpotLight.prototype._setDirection = function (value) {
  46543. _super.prototype._setDirection.call(this, value);
  46544. this._projectionTextureViewLightDirty = true;
  46545. };
  46546. /**
  46547. * Overrides the position setter to recompute the projection texture view light Matrix.
  46548. */
  46549. SpotLight.prototype._setPosition = function (value) {
  46550. _super.prototype._setPosition.call(this, value);
  46551. this._projectionTextureViewLightDirty = true;
  46552. };
  46553. /**
  46554. * 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.
  46555. * Returns the SpotLight.
  46556. */
  46557. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46558. var activeCamera = this.getScene().activeCamera;
  46559. if (!activeCamera) {
  46560. return;
  46561. }
  46562. this._shadowAngleScale = this._shadowAngleScale || 1;
  46563. var angle = this._shadowAngleScale * this._angle;
  46564. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46565. };
  46566. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46567. this._projectionTextureViewLightDirty = false;
  46568. this._projectionTextureDirty = true;
  46569. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46570. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46571. };
  46572. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46573. this._projectionTextureProjectionLightDirty = false;
  46574. this._projectionTextureDirty = true;
  46575. var light_far = this.projectionTextureLightFar;
  46576. var light_near = this.projectionTextureLightNear;
  46577. var P = light_far / (light_far - light_near);
  46578. var Q = -P * light_near;
  46579. var S = 1.0 / Math.tan(this._angle / 2.0);
  46580. var A = 1.0;
  46581. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  46582. };
  46583. /**
  46584. * Main function for light texture projection matrix computing.
  46585. */
  46586. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46587. this._projectionTextureDirty = false;
  46588. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46589. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46590. };
  46591. SpotLight.prototype._buildUniformLayout = function () {
  46592. this._uniformBuffer.addUniform("vLightData", 4);
  46593. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46594. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46595. this._uniformBuffer.addUniform("vLightDirection", 3);
  46596. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46597. this._uniformBuffer.addUniform("depthValues", 2);
  46598. this._uniformBuffer.create();
  46599. };
  46600. /**
  46601. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46602. * @param effect The effect to update
  46603. * @param lightIndex The index of the light in the effect to update
  46604. * @returns The spot light
  46605. */
  46606. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46607. var normalizeDirection;
  46608. if (this.computeTransformedInformation()) {
  46609. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46610. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46611. }
  46612. else {
  46613. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46614. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46615. }
  46616. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46617. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46618. if (this._projectionTextureViewLightDirty) {
  46619. this._computeProjectionTextureViewLightMatrix();
  46620. }
  46621. if (this._projectionTextureProjectionLightDirty) {
  46622. this._computeProjectionTextureProjectionLightMatrix();
  46623. }
  46624. if (this._projectionTextureDirty) {
  46625. this._computeProjectionTextureMatrix();
  46626. }
  46627. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46628. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46629. }
  46630. return this;
  46631. };
  46632. /**
  46633. * Disposes the light and the associated resources.
  46634. */
  46635. SpotLight.prototype.dispose = function () {
  46636. _super.prototype.dispose.call(this);
  46637. if (this._projectionTexture) {
  46638. this._projectionTexture.dispose();
  46639. }
  46640. };
  46641. __decorate([
  46642. BABYLON.serialize()
  46643. ], SpotLight.prototype, "angle", null);
  46644. __decorate([
  46645. BABYLON.serialize()
  46646. ], SpotLight.prototype, "shadowAngleScale", null);
  46647. __decorate([
  46648. BABYLON.serialize()
  46649. ], SpotLight.prototype, "exponent", void 0);
  46650. __decorate([
  46651. BABYLON.serialize()
  46652. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46653. __decorate([
  46654. BABYLON.serialize()
  46655. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46656. __decorate([
  46657. BABYLON.serialize()
  46658. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46659. __decorate([
  46660. BABYLON.serializeAsTexture("projectedLightTexture")
  46661. ], SpotLight.prototype, "_projectionTexture", void 0);
  46662. return SpotLight;
  46663. }(BABYLON.ShadowLight));
  46664. BABYLON.SpotLight = SpotLight;
  46665. })(BABYLON || (BABYLON = {}));
  46666. //# sourceMappingURL=babylon.spotLight.js.map
  46667. var BABYLON;
  46668. (function (BABYLON) {
  46669. /**
  46670. * Class used to override all child animations of a given target
  46671. */
  46672. var AnimationPropertiesOverride = /** @class */ (function () {
  46673. function AnimationPropertiesOverride() {
  46674. /**
  46675. * Gets or sets a value indicating if animation blending must be used
  46676. */
  46677. this.enableBlending = false;
  46678. /**
  46679. * Gets or sets the blending speed to use when enableBlending is true
  46680. */
  46681. this.blendingSpeed = 0.01;
  46682. /**
  46683. * Gets or sets the default loop mode to use
  46684. */
  46685. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46686. }
  46687. return AnimationPropertiesOverride;
  46688. }());
  46689. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46690. })(BABYLON || (BABYLON = {}));
  46691. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46692. var BABYLON;
  46693. (function (BABYLON) {
  46694. var AnimationRange = /** @class */ (function () {
  46695. function AnimationRange(name, from, to) {
  46696. this.name = name;
  46697. this.from = from;
  46698. this.to = to;
  46699. }
  46700. AnimationRange.prototype.clone = function () {
  46701. return new AnimationRange(this.name, this.from, this.to);
  46702. };
  46703. return AnimationRange;
  46704. }());
  46705. BABYLON.AnimationRange = AnimationRange;
  46706. /**
  46707. * Composed of a frame, and an action function
  46708. */
  46709. var AnimationEvent = /** @class */ (function () {
  46710. function AnimationEvent(frame, action, onlyOnce) {
  46711. this.frame = frame;
  46712. this.action = action;
  46713. this.onlyOnce = onlyOnce;
  46714. this.isDone = false;
  46715. }
  46716. return AnimationEvent;
  46717. }());
  46718. BABYLON.AnimationEvent = AnimationEvent;
  46719. var PathCursor = /** @class */ (function () {
  46720. function PathCursor(path) {
  46721. this.path = path;
  46722. this._onchange = new Array();
  46723. this.value = 0;
  46724. this.animations = new Array();
  46725. }
  46726. PathCursor.prototype.getPoint = function () {
  46727. var point = this.path.getPointAtLengthPosition(this.value);
  46728. return new BABYLON.Vector3(point.x, 0, point.y);
  46729. };
  46730. PathCursor.prototype.moveAhead = function (step) {
  46731. if (step === void 0) { step = 0.002; }
  46732. this.move(step);
  46733. return this;
  46734. };
  46735. PathCursor.prototype.moveBack = function (step) {
  46736. if (step === void 0) { step = 0.002; }
  46737. this.move(-step);
  46738. return this;
  46739. };
  46740. PathCursor.prototype.move = function (step) {
  46741. if (Math.abs(step) > 1) {
  46742. throw "step size should be less than 1.";
  46743. }
  46744. this.value += step;
  46745. this.ensureLimits();
  46746. this.raiseOnChange();
  46747. return this;
  46748. };
  46749. PathCursor.prototype.ensureLimits = function () {
  46750. while (this.value > 1) {
  46751. this.value -= 1;
  46752. }
  46753. while (this.value < 0) {
  46754. this.value += 1;
  46755. }
  46756. return this;
  46757. };
  46758. // used by animation engine
  46759. PathCursor.prototype.raiseOnChange = function () {
  46760. var _this = this;
  46761. this._onchange.forEach(function (f) { return f(_this); });
  46762. return this;
  46763. };
  46764. PathCursor.prototype.onchange = function (f) {
  46765. this._onchange.push(f);
  46766. return this;
  46767. };
  46768. return PathCursor;
  46769. }());
  46770. BABYLON.PathCursor = PathCursor;
  46771. var AnimationKeyInterpolation;
  46772. (function (AnimationKeyInterpolation) {
  46773. /**
  46774. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46775. */
  46776. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46777. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46778. var Animation = /** @class */ (function () {
  46779. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46780. this.name = name;
  46781. this.targetProperty = targetProperty;
  46782. this.framePerSecond = framePerSecond;
  46783. this.dataType = dataType;
  46784. this.loopMode = loopMode;
  46785. this.enableBlending = enableBlending;
  46786. this._runtimeAnimations = new Array();
  46787. // The set of event that will be linked to this animation
  46788. this._events = new Array();
  46789. this.blendingSpeed = 0.01;
  46790. this._ranges = {};
  46791. this.targetPropertyPath = targetProperty.split(".");
  46792. this.dataType = dataType;
  46793. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46794. }
  46795. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46796. var dataType = undefined;
  46797. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46798. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46799. }
  46800. else if (from instanceof BABYLON.Quaternion) {
  46801. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46802. }
  46803. else if (from instanceof BABYLON.Vector3) {
  46804. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46805. }
  46806. else if (from instanceof BABYLON.Vector2) {
  46807. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46808. }
  46809. else if (from instanceof BABYLON.Color3) {
  46810. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46811. }
  46812. else if (from instanceof BABYLON.Size) {
  46813. dataType = Animation.ANIMATIONTYPE_SIZE;
  46814. }
  46815. if (dataType == undefined) {
  46816. return null;
  46817. }
  46818. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46819. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46820. animation.setKeys(keys);
  46821. if (easingFunction !== undefined) {
  46822. animation.setEasingFunction(easingFunction);
  46823. }
  46824. return animation;
  46825. };
  46826. /**
  46827. * Sets up an animation.
  46828. * @param property the property to animate
  46829. * @param animationType the animation type to apply
  46830. * @param easingFunction the easing function used in the animation
  46831. * @returns The created animation
  46832. */
  46833. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46834. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46835. animation.setEasingFunction(easingFunction);
  46836. return animation;
  46837. };
  46838. /**
  46839. * Create and start an animation on a node
  46840. * @param {string} name defines the name of the global animation that will be run on all nodes
  46841. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46842. * @param {string} targetProperty defines property to animate
  46843. * @param {number} framePerSecond defines the number of frame per second yo use
  46844. * @param {number} totalFrame defines the number of frames in total
  46845. * @param {any} from defines the initial value
  46846. * @param {any} to defines the final value
  46847. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46848. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46849. * @param onAnimationEnd defines the callback to call when animation end
  46850. * @returns the animatable created for this animation
  46851. */
  46852. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46853. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46854. if (!animation) {
  46855. return null;
  46856. }
  46857. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46858. };
  46859. /**
  46860. * Create and start an animation on a node and its descendants
  46861. * @param {string} name defines the name of the global animation that will be run on all nodes
  46862. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46863. * @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.
  46864. * @param {string} targetProperty defines property to animate
  46865. * @param {number} framePerSecond defines the number of frame per second yo use
  46866. * @param {number} totalFrame defines the number of frames in total
  46867. * @param {any} from defines the initial value
  46868. * @param {any} to defines the final value
  46869. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46870. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46871. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46872. * @returns the list of animatables created for all nodes
  46873. * @example https://www.babylonjs-playground.com/#MH0VLI
  46874. */
  46875. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46876. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46877. if (!animation) {
  46878. return null;
  46879. }
  46880. var scene = node.getScene();
  46881. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46882. };
  46883. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46884. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46885. if (!animation) {
  46886. return null;
  46887. }
  46888. node.animations.push(animation);
  46889. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46890. };
  46891. /**
  46892. * Transition property of the Camera to the target Value.
  46893. * @param property The property to transition
  46894. * @param targetValue The target Value of the property
  46895. * @param host The object where the property to animate belongs
  46896. * @param scene Scene used to run the animation
  46897. * @param frameRate Framerate (in frame/s) to use
  46898. * @param transition The transition type we want to use
  46899. * @param duration The duration of the animation, in milliseconds
  46900. * @param onAnimationEnd Call back trigger at the end of the animation.
  46901. */
  46902. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46903. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46904. if (duration <= 0) {
  46905. host[property] = targetValue;
  46906. if (onAnimationEnd) {
  46907. onAnimationEnd();
  46908. }
  46909. return null;
  46910. }
  46911. var endFrame = frameRate * (duration / 1000);
  46912. transition.setKeys([{
  46913. frame: 0,
  46914. value: host[property].clone ? host[property].clone() : host[property]
  46915. },
  46916. {
  46917. frame: endFrame,
  46918. value: targetValue
  46919. }]);
  46920. if (!host.animations) {
  46921. host.animations = [];
  46922. }
  46923. host.animations.push(transition);
  46924. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46925. animation.onAnimationEnd = onAnimationEnd;
  46926. return animation;
  46927. };
  46928. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46929. /**
  46930. * Return the array of runtime animations currently using this animation
  46931. */
  46932. get: function () {
  46933. return this._runtimeAnimations;
  46934. },
  46935. enumerable: true,
  46936. configurable: true
  46937. });
  46938. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46939. get: function () {
  46940. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46941. var runtimeAnimation = _a[_i];
  46942. if (!runtimeAnimation.isStopped) {
  46943. return true;
  46944. }
  46945. }
  46946. return false;
  46947. },
  46948. enumerable: true,
  46949. configurable: true
  46950. });
  46951. // Methods
  46952. /**
  46953. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46954. */
  46955. Animation.prototype.toString = function (fullDetails) {
  46956. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46957. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46958. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46959. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46960. if (fullDetails) {
  46961. ret += ", Ranges: {";
  46962. var first = true;
  46963. for (var name in this._ranges) {
  46964. if (first) {
  46965. ret += ", ";
  46966. first = false;
  46967. }
  46968. ret += name;
  46969. }
  46970. ret += "}";
  46971. }
  46972. return ret;
  46973. };
  46974. /**
  46975. * Add an event to this animation.
  46976. */
  46977. Animation.prototype.addEvent = function (event) {
  46978. this._events.push(event);
  46979. };
  46980. /**
  46981. * Remove all events found at the given frame
  46982. * @param frame
  46983. */
  46984. Animation.prototype.removeEvents = function (frame) {
  46985. for (var index = 0; index < this._events.length; index++) {
  46986. if (this._events[index].frame === frame) {
  46987. this._events.splice(index, 1);
  46988. index--;
  46989. }
  46990. }
  46991. };
  46992. Animation.prototype.getEvents = function () {
  46993. return this._events;
  46994. };
  46995. Animation.prototype.createRange = function (name, from, to) {
  46996. // check name not already in use; could happen for bones after serialized
  46997. if (!this._ranges[name]) {
  46998. this._ranges[name] = new AnimationRange(name, from, to);
  46999. }
  47000. };
  47001. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47002. if (deleteFrames === void 0) { deleteFrames = true; }
  47003. var range = this._ranges[name];
  47004. if (!range) {
  47005. return;
  47006. }
  47007. if (deleteFrames) {
  47008. var from = range.from;
  47009. var to = range.to;
  47010. // this loop MUST go high to low for multiple splices to work
  47011. for (var key = this._keys.length - 1; key >= 0; key--) {
  47012. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47013. this._keys.splice(key, 1);
  47014. }
  47015. }
  47016. }
  47017. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47018. };
  47019. Animation.prototype.getRange = function (name) {
  47020. return this._ranges[name];
  47021. };
  47022. Animation.prototype.getKeys = function () {
  47023. return this._keys;
  47024. };
  47025. Animation.prototype.getHighestFrame = function () {
  47026. var ret = 0;
  47027. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47028. if (ret < this._keys[key].frame) {
  47029. ret = this._keys[key].frame;
  47030. }
  47031. }
  47032. return ret;
  47033. };
  47034. Animation.prototype.getEasingFunction = function () {
  47035. return this._easingFunction;
  47036. };
  47037. Animation.prototype.setEasingFunction = function (easingFunction) {
  47038. this._easingFunction = easingFunction;
  47039. };
  47040. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47041. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47042. };
  47043. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47044. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47045. };
  47046. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47047. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47048. };
  47049. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47050. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47051. };
  47052. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47053. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47054. };
  47055. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47056. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47057. };
  47058. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47059. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47060. };
  47061. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47062. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47063. };
  47064. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47065. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47066. };
  47067. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47068. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47069. };
  47070. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47071. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47072. };
  47073. Animation.prototype.clone = function () {
  47074. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47075. clone.enableBlending = this.enableBlending;
  47076. clone.blendingSpeed = this.blendingSpeed;
  47077. if (this._keys) {
  47078. clone.setKeys(this._keys);
  47079. }
  47080. if (this._ranges) {
  47081. clone._ranges = {};
  47082. for (var name in this._ranges) {
  47083. var range = this._ranges[name];
  47084. if (!range) {
  47085. continue;
  47086. }
  47087. clone._ranges[name] = range.clone();
  47088. }
  47089. }
  47090. return clone;
  47091. };
  47092. Animation.prototype.setKeys = function (values) {
  47093. this._keys = values.slice(0);
  47094. };
  47095. Animation.prototype.serialize = function () {
  47096. var serializationObject = {};
  47097. serializationObject.name = this.name;
  47098. serializationObject.property = this.targetProperty;
  47099. serializationObject.framePerSecond = this.framePerSecond;
  47100. serializationObject.dataType = this.dataType;
  47101. serializationObject.loopBehavior = this.loopMode;
  47102. serializationObject.enableBlending = this.enableBlending;
  47103. serializationObject.blendingSpeed = this.blendingSpeed;
  47104. var dataType = this.dataType;
  47105. serializationObject.keys = [];
  47106. var keys = this.getKeys();
  47107. for (var index = 0; index < keys.length; index++) {
  47108. var animationKey = keys[index];
  47109. var key = {};
  47110. key.frame = animationKey.frame;
  47111. switch (dataType) {
  47112. case Animation.ANIMATIONTYPE_FLOAT:
  47113. key.values = [animationKey.value];
  47114. break;
  47115. case Animation.ANIMATIONTYPE_QUATERNION:
  47116. case Animation.ANIMATIONTYPE_MATRIX:
  47117. case Animation.ANIMATIONTYPE_VECTOR3:
  47118. case Animation.ANIMATIONTYPE_COLOR3:
  47119. key.values = animationKey.value.asArray();
  47120. break;
  47121. }
  47122. serializationObject.keys.push(key);
  47123. }
  47124. serializationObject.ranges = [];
  47125. for (var name in this._ranges) {
  47126. var source = this._ranges[name];
  47127. if (!source) {
  47128. continue;
  47129. }
  47130. var range = {};
  47131. range.name = name;
  47132. range.from = source.from;
  47133. range.to = source.to;
  47134. serializationObject.ranges.push(range);
  47135. }
  47136. return serializationObject;
  47137. };
  47138. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47139. get: function () {
  47140. return Animation._ANIMATIONTYPE_FLOAT;
  47141. },
  47142. enumerable: true,
  47143. configurable: true
  47144. });
  47145. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47146. get: function () {
  47147. return Animation._ANIMATIONTYPE_VECTOR3;
  47148. },
  47149. enumerable: true,
  47150. configurable: true
  47151. });
  47152. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47153. get: function () {
  47154. return Animation._ANIMATIONTYPE_VECTOR2;
  47155. },
  47156. enumerable: true,
  47157. configurable: true
  47158. });
  47159. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47160. get: function () {
  47161. return Animation._ANIMATIONTYPE_SIZE;
  47162. },
  47163. enumerable: true,
  47164. configurable: true
  47165. });
  47166. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47167. get: function () {
  47168. return Animation._ANIMATIONTYPE_QUATERNION;
  47169. },
  47170. enumerable: true,
  47171. configurable: true
  47172. });
  47173. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47174. get: function () {
  47175. return Animation._ANIMATIONTYPE_MATRIX;
  47176. },
  47177. enumerable: true,
  47178. configurable: true
  47179. });
  47180. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47181. get: function () {
  47182. return Animation._ANIMATIONTYPE_COLOR3;
  47183. },
  47184. enumerable: true,
  47185. configurable: true
  47186. });
  47187. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47188. get: function () {
  47189. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47190. },
  47191. enumerable: true,
  47192. configurable: true
  47193. });
  47194. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47195. get: function () {
  47196. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47197. },
  47198. enumerable: true,
  47199. configurable: true
  47200. });
  47201. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47202. get: function () {
  47203. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47204. },
  47205. enumerable: true,
  47206. configurable: true
  47207. });
  47208. Animation.Parse = function (parsedAnimation) {
  47209. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47210. var dataType = parsedAnimation.dataType;
  47211. var keys = [];
  47212. var data;
  47213. var index;
  47214. if (parsedAnimation.enableBlending) {
  47215. animation.enableBlending = parsedAnimation.enableBlending;
  47216. }
  47217. if (parsedAnimation.blendingSpeed) {
  47218. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47219. }
  47220. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47221. var key = parsedAnimation.keys[index];
  47222. var inTangent;
  47223. var outTangent;
  47224. switch (dataType) {
  47225. case Animation.ANIMATIONTYPE_FLOAT:
  47226. data = key.values[0];
  47227. if (key.values.length >= 1) {
  47228. inTangent = key.values[1];
  47229. }
  47230. if (key.values.length >= 2) {
  47231. outTangent = key.values[2];
  47232. }
  47233. break;
  47234. case Animation.ANIMATIONTYPE_QUATERNION:
  47235. data = BABYLON.Quaternion.FromArray(key.values);
  47236. if (key.values.length >= 8) {
  47237. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47238. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47239. inTangent = _inTangent;
  47240. }
  47241. }
  47242. if (key.values.length >= 12) {
  47243. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47244. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47245. outTangent = _outTangent;
  47246. }
  47247. }
  47248. break;
  47249. case Animation.ANIMATIONTYPE_MATRIX:
  47250. data = BABYLON.Matrix.FromArray(key.values);
  47251. break;
  47252. case Animation.ANIMATIONTYPE_COLOR3:
  47253. data = BABYLON.Color3.FromArray(key.values);
  47254. break;
  47255. case Animation.ANIMATIONTYPE_VECTOR3:
  47256. default:
  47257. data = BABYLON.Vector3.FromArray(key.values);
  47258. break;
  47259. }
  47260. var keyData = {};
  47261. keyData.frame = key.frame;
  47262. keyData.value = data;
  47263. if (inTangent != undefined) {
  47264. keyData.inTangent = inTangent;
  47265. }
  47266. if (outTangent != undefined) {
  47267. keyData.outTangent = outTangent;
  47268. }
  47269. keys.push(keyData);
  47270. }
  47271. animation.setKeys(keys);
  47272. if (parsedAnimation.ranges) {
  47273. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47274. data = parsedAnimation.ranges[index];
  47275. animation.createRange(data.name, data.from, data.to);
  47276. }
  47277. }
  47278. return animation;
  47279. };
  47280. Animation.AppendSerializedAnimations = function (source, destination) {
  47281. if (source.animations) {
  47282. destination.animations = [];
  47283. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47284. var animation = source.animations[animationIndex];
  47285. destination.animations.push(animation.serialize());
  47286. }
  47287. }
  47288. };
  47289. Animation.AllowMatricesInterpolation = false;
  47290. // Statics
  47291. Animation._ANIMATIONTYPE_FLOAT = 0;
  47292. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47293. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47294. Animation._ANIMATIONTYPE_MATRIX = 3;
  47295. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47296. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47297. Animation._ANIMATIONTYPE_SIZE = 6;
  47298. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47299. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47300. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47301. return Animation;
  47302. }());
  47303. BABYLON.Animation = Animation;
  47304. })(BABYLON || (BABYLON = {}));
  47305. //# sourceMappingURL=babylon.animation.js.map
  47306. var BABYLON;
  47307. (function (BABYLON) {
  47308. /**
  47309. * This class defines the direct association between an animation and a target
  47310. */
  47311. var TargetedAnimation = /** @class */ (function () {
  47312. function TargetedAnimation() {
  47313. }
  47314. return TargetedAnimation;
  47315. }());
  47316. BABYLON.TargetedAnimation = TargetedAnimation;
  47317. /**
  47318. * Use this class to create coordinated animations on multiple targets
  47319. */
  47320. var AnimationGroup = /** @class */ (function () {
  47321. function AnimationGroup(name, scene) {
  47322. if (scene === void 0) { scene = null; }
  47323. this.name = name;
  47324. this._targetedAnimations = new Array();
  47325. this._animatables = new Array();
  47326. this._from = Number.MAX_VALUE;
  47327. this._to = -Number.MAX_VALUE;
  47328. this._speedRatio = 1;
  47329. this.onAnimationEndObservable = new BABYLON.Observable();
  47330. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47331. this._scene.animationGroups.push(this);
  47332. }
  47333. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47334. /**
  47335. * Define if the animations are started
  47336. */
  47337. get: function () {
  47338. return this._isStarted;
  47339. },
  47340. enumerable: true,
  47341. configurable: true
  47342. });
  47343. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47344. /**
  47345. * Gets or sets the speed ratio to use for all animations
  47346. */
  47347. get: function () {
  47348. return this._speedRatio;
  47349. },
  47350. /**
  47351. * Gets or sets the speed ratio to use for all animations
  47352. */
  47353. set: function (value) {
  47354. if (this._speedRatio === value) {
  47355. return;
  47356. }
  47357. this._speedRatio = value;
  47358. for (var index = 0; index < this._animatables.length; index++) {
  47359. var animatable = this._animatables[index];
  47360. animatable.speedRatio = this._speedRatio;
  47361. }
  47362. },
  47363. enumerable: true,
  47364. configurable: true
  47365. });
  47366. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47367. /**
  47368. * Gets the targeted animations for this animation group
  47369. */
  47370. get: function () {
  47371. return this._targetedAnimations;
  47372. },
  47373. enumerable: true,
  47374. configurable: true
  47375. });
  47376. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47377. /**
  47378. * returning the list of animatables controlled by this animation group.
  47379. */
  47380. get: function () {
  47381. return this._animatables;
  47382. },
  47383. enumerable: true,
  47384. configurable: true
  47385. });
  47386. /**
  47387. * Add an animation (with its target) in the group
  47388. * @param animation defines the animation we want to add
  47389. * @param target defines the target of the animation
  47390. * @returns the {BABYLON.TargetedAnimation} object
  47391. */
  47392. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47393. var targetedAnimation = {
  47394. animation: animation,
  47395. target: target
  47396. };
  47397. var keys = animation.getKeys();
  47398. if (this._from > keys[0].frame) {
  47399. this._from = keys[0].frame;
  47400. }
  47401. if (this._to < keys[keys.length - 1].frame) {
  47402. this._to = keys[keys.length - 1].frame;
  47403. }
  47404. this._targetedAnimations.push(targetedAnimation);
  47405. return targetedAnimation;
  47406. };
  47407. /**
  47408. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47409. * It can add constant keys at begin or end
  47410. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47411. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47412. */
  47413. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47414. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47415. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47416. beginFrame = Math.max(beginFrame, this._from);
  47417. endFrame = Math.min(endFrame, this._to);
  47418. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47419. var targetedAnimation = this._targetedAnimations[index];
  47420. var keys = targetedAnimation.animation.getKeys();
  47421. var startKey = keys[0];
  47422. var endKey = keys[keys.length - 1];
  47423. if (startKey.frame > beginFrame) {
  47424. var newKey = {
  47425. frame: beginFrame,
  47426. value: startKey.value,
  47427. inTangent: startKey.inTangent,
  47428. outTangent: startKey.outTangent,
  47429. interpolation: startKey.interpolation
  47430. };
  47431. keys.splice(0, 0, newKey);
  47432. }
  47433. if (endKey.frame < endFrame) {
  47434. var newKey = {
  47435. frame: endFrame,
  47436. value: endKey.value,
  47437. inTangent: endKey.outTangent,
  47438. outTangent: endKey.outTangent,
  47439. interpolation: endKey.interpolation
  47440. };
  47441. keys.push(newKey);
  47442. }
  47443. }
  47444. return this;
  47445. };
  47446. /**
  47447. * Start all animations on given targets
  47448. * @param loop defines if animations must loop
  47449. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47450. */
  47451. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47452. var _this = this;
  47453. if (loop === void 0) { loop = false; }
  47454. if (speedRatio === void 0) { speedRatio = 1; }
  47455. if (this._isStarted || this._targetedAnimations.length === 0) {
  47456. return this;
  47457. }
  47458. var _loop_1 = function () {
  47459. var targetedAnimation = this_1._targetedAnimations[index];
  47460. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47461. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47462. }));
  47463. };
  47464. var this_1 = this;
  47465. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47466. _loop_1();
  47467. }
  47468. this._speedRatio = speedRatio;
  47469. this._isStarted = true;
  47470. return this;
  47471. };
  47472. /**
  47473. * Pause all animations
  47474. */
  47475. AnimationGroup.prototype.pause = function () {
  47476. if (!this._isStarted) {
  47477. return this;
  47478. }
  47479. for (var index = 0; index < this._animatables.length; index++) {
  47480. var animatable = this._animatables[index];
  47481. animatable.pause();
  47482. }
  47483. return this;
  47484. };
  47485. /**
  47486. * Play all animations to initial state
  47487. * This function will start() the animations if they were not started or will restart() them if they were paused
  47488. * @param loop defines if animations must loop
  47489. */
  47490. AnimationGroup.prototype.play = function (loop) {
  47491. if (this.isStarted) {
  47492. if (loop !== undefined) {
  47493. for (var index = 0; index < this._animatables.length; index++) {
  47494. var animatable = this._animatables[index];
  47495. animatable.loopAnimation = loop;
  47496. }
  47497. }
  47498. this.restart();
  47499. }
  47500. else {
  47501. this.start(loop, this._speedRatio);
  47502. }
  47503. return this;
  47504. };
  47505. /**
  47506. * Reset all animations to initial state
  47507. */
  47508. AnimationGroup.prototype.reset = function () {
  47509. if (!this._isStarted) {
  47510. return this;
  47511. }
  47512. for (var index = 0; index < this._animatables.length; index++) {
  47513. var animatable = this._animatables[index];
  47514. animatable.reset();
  47515. }
  47516. return this;
  47517. };
  47518. /**
  47519. * Restart animations from key 0
  47520. */
  47521. AnimationGroup.prototype.restart = function () {
  47522. if (!this._isStarted) {
  47523. return this;
  47524. }
  47525. for (var index = 0; index < this._animatables.length; index++) {
  47526. var animatable = this._animatables[index];
  47527. animatable.restart();
  47528. }
  47529. return this;
  47530. };
  47531. /**
  47532. * Stop all animations
  47533. */
  47534. AnimationGroup.prototype.stop = function () {
  47535. if (!this._isStarted) {
  47536. return this;
  47537. }
  47538. for (var index = 0; index < this._animatables.length; index++) {
  47539. var animatable = this._animatables[index];
  47540. animatable.stop();
  47541. }
  47542. this._isStarted = false;
  47543. return this;
  47544. };
  47545. /**
  47546. * Goes to a specific frame in this animation group
  47547. *
  47548. * @param frame the frame number to go to
  47549. * @return the animationGroup
  47550. */
  47551. AnimationGroup.prototype.goToFrame = function (frame) {
  47552. if (!this._isStarted) {
  47553. return this;
  47554. }
  47555. for (var index = 0; index < this._animatables.length; index++) {
  47556. var animatable = this._animatables[index];
  47557. animatable.goToFrame(frame);
  47558. }
  47559. return this;
  47560. };
  47561. /**
  47562. * Dispose all associated resources
  47563. */
  47564. AnimationGroup.prototype.dispose = function () {
  47565. this._targetedAnimations = [];
  47566. this._animatables = [];
  47567. var index = this._scene.animationGroups.indexOf(this);
  47568. if (index > -1) {
  47569. this._scene.animationGroups.splice(index, 1);
  47570. }
  47571. };
  47572. return AnimationGroup;
  47573. }());
  47574. BABYLON.AnimationGroup = AnimationGroup;
  47575. })(BABYLON || (BABYLON = {}));
  47576. //# sourceMappingURL=babylon.animationGroup.js.map
  47577. var BABYLON;
  47578. (function (BABYLON) {
  47579. var RuntimeAnimation = /** @class */ (function () {
  47580. /**
  47581. * Create a new RuntimeAnimation object
  47582. * @param target defines the target of the animation
  47583. * @param animation defines the source {BABYLON.Animation} object
  47584. * @param scene defines the hosting scene
  47585. */
  47586. function RuntimeAnimation(target, animation, scene) {
  47587. this._offsetsCache = {};
  47588. this._highLimitsCache = {};
  47589. this._stopped = false;
  47590. this._blendingFactor = 0;
  47591. this._weight = 1.0;
  47592. this._ratioOffset = 0;
  47593. this._animation = animation;
  47594. this._target = target;
  47595. this._scene = scene;
  47596. animation._runtimeAnimations.push(this);
  47597. }
  47598. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47599. /**
  47600. * Gets the weight of the runtime animation
  47601. */
  47602. get: function () {
  47603. return this._weight;
  47604. },
  47605. enumerable: true,
  47606. configurable: true
  47607. });
  47608. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47609. /**
  47610. * Gets the original value of the runtime animation
  47611. */
  47612. get: function () {
  47613. return this._originalValue;
  47614. },
  47615. enumerable: true,
  47616. configurable: true
  47617. });
  47618. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47619. /**
  47620. * Gets the current value of the runtime animation
  47621. */
  47622. get: function () {
  47623. return this._currentValue;
  47624. },
  47625. enumerable: true,
  47626. configurable: true
  47627. });
  47628. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47629. /**
  47630. * Gets the path where to store the animated value in the target
  47631. */
  47632. get: function () {
  47633. return this._targetPath;
  47634. },
  47635. enumerable: true,
  47636. configurable: true
  47637. });
  47638. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47639. /**
  47640. * Gets the actual target of the runtime animation
  47641. */
  47642. get: function () {
  47643. return this._activeTarget;
  47644. },
  47645. enumerable: true,
  47646. configurable: true
  47647. });
  47648. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47649. get: function () {
  47650. return this._animation;
  47651. },
  47652. enumerable: true,
  47653. configurable: true
  47654. });
  47655. RuntimeAnimation.prototype.reset = function () {
  47656. this._offsetsCache = {};
  47657. this._highLimitsCache = {};
  47658. this.currentFrame = 0;
  47659. this._blendingFactor = 0;
  47660. this._originalValue = null;
  47661. };
  47662. RuntimeAnimation.prototype.isStopped = function () {
  47663. return this._stopped;
  47664. };
  47665. RuntimeAnimation.prototype.dispose = function () {
  47666. var index = this._animation.runtimeAnimations.indexOf(this);
  47667. if (index > -1) {
  47668. this._animation.runtimeAnimations.splice(index, 1);
  47669. }
  47670. };
  47671. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47672. if (typeof value === "function") {
  47673. return value();
  47674. }
  47675. return value;
  47676. };
  47677. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47678. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47679. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47680. }
  47681. this.currentFrame = currentFrame;
  47682. var keys = this._animation.getKeys();
  47683. // Try to get a hash to find the right key
  47684. 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));
  47685. if (keys[startKeyIndex].frame >= currentFrame) {
  47686. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47687. startKeyIndex--;
  47688. }
  47689. }
  47690. for (var key = startKeyIndex; key < keys.length; key++) {
  47691. var endKey = keys[key + 1];
  47692. if (endKey.frame >= currentFrame) {
  47693. var startKey = keys[key];
  47694. var startValue = this._getKeyValue(startKey.value);
  47695. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47696. return startValue;
  47697. }
  47698. var endValue = this._getKeyValue(endKey.value);
  47699. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47700. var frameDelta = endKey.frame - startKey.frame;
  47701. // gradient : percent of currentFrame between the frame inf and the frame sup
  47702. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47703. // check for easingFunction and correction of gradient
  47704. var easingFunction = this._animation.getEasingFunction();
  47705. if (easingFunction != null) {
  47706. gradient = easingFunction.ease(gradient);
  47707. }
  47708. switch (this._animation.dataType) {
  47709. // Float
  47710. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47711. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47712. switch (loopMode) {
  47713. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47714. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47715. return floatValue;
  47716. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47717. return offsetValue * repeatCount + floatValue;
  47718. }
  47719. break;
  47720. // Quaternion
  47721. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47722. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47723. switch (loopMode) {
  47724. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47725. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47726. return quatValue;
  47727. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47728. return quatValue.add(offsetValue.scale(repeatCount));
  47729. }
  47730. return quatValue;
  47731. // Vector3
  47732. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47733. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47734. switch (loopMode) {
  47735. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47736. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47737. return vec3Value;
  47738. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47739. return vec3Value.add(offsetValue.scale(repeatCount));
  47740. }
  47741. // Vector2
  47742. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47743. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47744. switch (loopMode) {
  47745. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47746. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47747. return vec2Value;
  47748. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47749. return vec2Value.add(offsetValue.scale(repeatCount));
  47750. }
  47751. // Size
  47752. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47753. switch (loopMode) {
  47754. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47755. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47756. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47757. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47758. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47759. }
  47760. // Color3
  47761. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47762. switch (loopMode) {
  47763. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47764. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47765. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47766. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47767. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47768. }
  47769. // Matrix
  47770. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47771. switch (loopMode) {
  47772. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47773. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47774. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47775. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47776. }
  47777. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47778. return startValue;
  47779. }
  47780. default:
  47781. break;
  47782. }
  47783. break;
  47784. }
  47785. }
  47786. return this._getKeyValue(keys[keys.length - 1].value);
  47787. };
  47788. /**
  47789. * Affect the interpolated value to the target
  47790. * @param currentValue defines the value computed by the animation
  47791. * @param weight defines the weight to apply to this value
  47792. */
  47793. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47794. if (weight === void 0) { weight = 1.0; }
  47795. // Set value
  47796. var path;
  47797. var destination;
  47798. var targetPropertyPath = this._animation.targetPropertyPath;
  47799. if (targetPropertyPath.length > 1) {
  47800. var property = this._target[targetPropertyPath[0]];
  47801. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47802. property = property[targetPropertyPath[index]];
  47803. }
  47804. path = [targetPropertyPath.length - 1];
  47805. destination = property;
  47806. }
  47807. else {
  47808. path = targetPropertyPath[0];
  47809. destination = this._target;
  47810. }
  47811. this._targetPath = path;
  47812. this._activeTarget = destination;
  47813. this._weight = weight;
  47814. // Blending
  47815. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47816. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47817. if (enableBlending && this._blendingFactor <= 1.0 || weight !== -1.0) {
  47818. if (!this._originalValue) {
  47819. var originalValue = void 0;
  47820. if (destination.getRestPose) {
  47821. originalValue = destination.getRestPose();
  47822. }
  47823. else {
  47824. originalValue = destination[path];
  47825. }
  47826. if (originalValue.clone) {
  47827. this._originalValue = originalValue.clone();
  47828. }
  47829. else {
  47830. this._originalValue = originalValue;
  47831. }
  47832. }
  47833. }
  47834. if (enableBlending && this._blendingFactor <= 1.0) {
  47835. if (this._originalValue.prototype) {
  47836. if (this._originalValue.prototype.Lerp) {
  47837. this._currentValue = this._originalValue.construtor.prototype.Lerp(currentValue, this._originalValue, this._blendingFactor);
  47838. }
  47839. else {
  47840. this._currentValue = currentValue;
  47841. }
  47842. }
  47843. else if (this._originalValue.m) {
  47844. this._currentValue = BABYLON.Matrix.Lerp(this._originalValue, currentValue, this._blendingFactor);
  47845. }
  47846. else {
  47847. this._currentValue = this._originalValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47848. }
  47849. this._blendingFactor += blendingSpeed;
  47850. destination[path] = this._currentValue;
  47851. }
  47852. else {
  47853. this._currentValue = currentValue;
  47854. if (weight !== -1.0) {
  47855. this._scene._registerTargetForLateAnimationBinding(this);
  47856. }
  47857. else {
  47858. destination[path] = this._currentValue;
  47859. }
  47860. }
  47861. if (this._target.markAsDirty) {
  47862. this._target.markAsDirty(this._animation.targetProperty);
  47863. }
  47864. };
  47865. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47866. if (this._target && this._target.animationPropertiesOverride) {
  47867. return this._target.animationPropertiesOverride.loopMode;
  47868. }
  47869. return this._animation.loopMode;
  47870. };
  47871. /**
  47872. * Move the current animation to a given frame
  47873. * @param frame defines the frame to move to
  47874. */
  47875. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47876. var keys = this._animation.getKeys();
  47877. if (frame < keys[0].frame) {
  47878. frame = keys[0].frame;
  47879. }
  47880. else if (frame > keys[keys.length - 1].frame) {
  47881. frame = keys[keys.length - 1].frame;
  47882. }
  47883. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47884. this.setValue(currentValue, -1);
  47885. };
  47886. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47887. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47888. this._ratioOffset = this._previousRatio - newRatio;
  47889. };
  47890. /**
  47891. * Execute the current animation
  47892. * @param delay defines the delay to add to the current frame
  47893. * @param from defines the lower bound of the animation range
  47894. * @param to defines the upper bound of the animation range
  47895. * @param loop defines if the current animation must loop
  47896. * @param speedRatio defines the current speed ratio
  47897. * @param weight defines the weight of the animation (default is -1 so no weight)
  47898. * @returns a boolean indicating if the animation has ended
  47899. */
  47900. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  47901. if (weight === void 0) { weight = -1.0; }
  47902. var targetPropertyPath = this._animation.targetPropertyPath;
  47903. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47904. this._stopped = true;
  47905. return false;
  47906. }
  47907. var returnValue = true;
  47908. var keys = this._animation.getKeys();
  47909. // Adding a start key at frame 0 if missing
  47910. if (keys[0].frame !== 0) {
  47911. var newKey = { frame: 0, value: keys[0].value };
  47912. keys.splice(0, 0, newKey);
  47913. }
  47914. // Check limits
  47915. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47916. from = keys[0].frame;
  47917. }
  47918. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47919. to = keys[keys.length - 1].frame;
  47920. }
  47921. //to and from cannot be the same key
  47922. if (from === to) {
  47923. if (from > keys[0].frame) {
  47924. from--;
  47925. }
  47926. else if (to < keys[keys.length - 1].frame) {
  47927. to++;
  47928. }
  47929. }
  47930. // Compute ratio
  47931. var range = to - from;
  47932. var offsetValue;
  47933. // ratio represents the frame delta between from and to
  47934. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47935. var highLimitValue = 0;
  47936. this._previousDelay = delay;
  47937. this._previousRatio = ratio;
  47938. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47939. returnValue = false;
  47940. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47941. }
  47942. else {
  47943. // Get max value if required
  47944. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47945. var keyOffset = to.toString() + from.toString();
  47946. if (!this._offsetsCache[keyOffset]) {
  47947. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47948. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47949. switch (this._animation.dataType) {
  47950. // Float
  47951. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47952. this._offsetsCache[keyOffset] = toValue - fromValue;
  47953. break;
  47954. // Quaternion
  47955. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47956. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47957. break;
  47958. // Vector3
  47959. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47960. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47961. // Vector2
  47962. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47963. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47964. // Size
  47965. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47966. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47967. // Color3
  47968. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47969. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47970. default:
  47971. break;
  47972. }
  47973. this._highLimitsCache[keyOffset] = toValue;
  47974. }
  47975. highLimitValue = this._highLimitsCache[keyOffset];
  47976. offsetValue = this._offsetsCache[keyOffset];
  47977. }
  47978. }
  47979. if (offsetValue === undefined) {
  47980. switch (this._animation.dataType) {
  47981. // Float
  47982. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47983. offsetValue = 0;
  47984. break;
  47985. // Quaternion
  47986. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47987. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47988. break;
  47989. // Vector3
  47990. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47991. offsetValue = BABYLON.Vector3.Zero();
  47992. break;
  47993. // Vector2
  47994. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47995. offsetValue = BABYLON.Vector2.Zero();
  47996. break;
  47997. // Size
  47998. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47999. offsetValue = BABYLON.Size.Zero();
  48000. break;
  48001. // Color3
  48002. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48003. offsetValue = BABYLON.Color3.Black();
  48004. }
  48005. }
  48006. // Compute value
  48007. var repeatCount = (ratio / range) >> 0;
  48008. var currentFrame = returnValue ? from + ratio % range : to;
  48009. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48010. // Set value
  48011. this.setValue(currentValue, weight);
  48012. // Check events
  48013. var events = this._animation.getEvents();
  48014. for (var index = 0; index < events.length; index++) {
  48015. // Make sure current frame has passed event frame and that event frame is within the current range
  48016. // Also, handle both forward and reverse animations
  48017. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48018. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48019. var event = events[index];
  48020. if (!event.isDone) {
  48021. // If event should be done only once, remove it.
  48022. if (event.onlyOnce) {
  48023. events.splice(index, 1);
  48024. index--;
  48025. }
  48026. event.isDone = true;
  48027. event.action();
  48028. } // Don't do anything if the event has already be done.
  48029. }
  48030. else if (events[index].isDone && !events[index].onlyOnce) {
  48031. // reset event, the animation is looping
  48032. events[index].isDone = false;
  48033. }
  48034. }
  48035. if (!returnValue) {
  48036. this._stopped = true;
  48037. }
  48038. return returnValue;
  48039. };
  48040. return RuntimeAnimation;
  48041. }());
  48042. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48043. })(BABYLON || (BABYLON = {}));
  48044. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48045. var BABYLON;
  48046. (function (BABYLON) {
  48047. var Animatable = /** @class */ (function () {
  48048. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48049. if (fromFrame === void 0) { fromFrame = 0; }
  48050. if (toFrame === void 0) { toFrame = 100; }
  48051. if (loopAnimation === void 0) { loopAnimation = false; }
  48052. if (speedRatio === void 0) { speedRatio = 1.0; }
  48053. this.target = target;
  48054. this.fromFrame = fromFrame;
  48055. this.toFrame = toFrame;
  48056. this.loopAnimation = loopAnimation;
  48057. this.onAnimationEnd = onAnimationEnd;
  48058. this._localDelayOffset = null;
  48059. this._pausedDelay = null;
  48060. this._runtimeAnimations = new Array();
  48061. this._paused = false;
  48062. this._speedRatio = 1;
  48063. this._weight = -1.0;
  48064. this.animationStarted = false;
  48065. if (animations) {
  48066. this.appendAnimations(target, animations);
  48067. }
  48068. this._speedRatio = speedRatio;
  48069. this._scene = scene;
  48070. scene._activeAnimatables.push(this);
  48071. }
  48072. Object.defineProperty(Animatable.prototype, "weight", {
  48073. /**
  48074. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48075. */
  48076. get: function () {
  48077. return this._weight;
  48078. },
  48079. set: function (value) {
  48080. if (value === -1) {
  48081. this._weight = -1;
  48082. return;
  48083. }
  48084. // Else weight must be in [0, 1] range
  48085. this._weight = Math.min(Math.max(value, 0), 1.0);
  48086. },
  48087. enumerable: true,
  48088. configurable: true
  48089. });
  48090. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48091. /**
  48092. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48093. */
  48094. get: function () {
  48095. return this._speedRatio;
  48096. },
  48097. set: function (value) {
  48098. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48099. var animation = this._runtimeAnimations[index];
  48100. animation._prepareForSpeedRatioChange(value);
  48101. }
  48102. this._speedRatio = value;
  48103. },
  48104. enumerable: true,
  48105. configurable: true
  48106. });
  48107. // Methods
  48108. Animatable.prototype.getAnimations = function () {
  48109. return this._runtimeAnimations;
  48110. };
  48111. Animatable.prototype.appendAnimations = function (target, animations) {
  48112. for (var index = 0; index < animations.length; index++) {
  48113. var animation = animations[index];
  48114. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene));
  48115. }
  48116. };
  48117. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48118. var runtimeAnimations = this._runtimeAnimations;
  48119. for (var index = 0; index < runtimeAnimations.length; index++) {
  48120. if (runtimeAnimations[index].animation.targetProperty === property) {
  48121. return runtimeAnimations[index].animation;
  48122. }
  48123. }
  48124. return null;
  48125. };
  48126. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48127. var runtimeAnimations = this._runtimeAnimations;
  48128. for (var index = 0; index < runtimeAnimations.length; index++) {
  48129. if (runtimeAnimations[index].animation.targetProperty === property) {
  48130. return runtimeAnimations[index];
  48131. }
  48132. }
  48133. return null;
  48134. };
  48135. Animatable.prototype.reset = function () {
  48136. var runtimeAnimations = this._runtimeAnimations;
  48137. for (var index = 0; index < runtimeAnimations.length; index++) {
  48138. runtimeAnimations[index].reset();
  48139. }
  48140. // Reset to original value
  48141. for (index = 0; index < runtimeAnimations.length; index++) {
  48142. var animation = runtimeAnimations[index];
  48143. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48144. }
  48145. this._localDelayOffset = null;
  48146. this._pausedDelay = null;
  48147. };
  48148. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48149. var runtimeAnimations = this._runtimeAnimations;
  48150. for (var index = 0; index < runtimeAnimations.length; index++) {
  48151. runtimeAnimations[index].animation.enableBlending = true;
  48152. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48153. }
  48154. };
  48155. Animatable.prototype.disableBlending = function () {
  48156. var runtimeAnimations = this._runtimeAnimations;
  48157. for (var index = 0; index < runtimeAnimations.length; index++) {
  48158. runtimeAnimations[index].animation.enableBlending = false;
  48159. }
  48160. };
  48161. Animatable.prototype.goToFrame = function (frame) {
  48162. var runtimeAnimations = this._runtimeAnimations;
  48163. if (runtimeAnimations[0]) {
  48164. var fps = runtimeAnimations[0].animation.framePerSecond;
  48165. var currentFrame = runtimeAnimations[0].currentFrame;
  48166. var adjustTime = frame - currentFrame;
  48167. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48168. if (this._localDelayOffset === null) {
  48169. this._localDelayOffset = 0;
  48170. }
  48171. this._localDelayOffset -= delay;
  48172. }
  48173. for (var index = 0; index < runtimeAnimations.length; index++) {
  48174. runtimeAnimations[index].goToFrame(frame);
  48175. }
  48176. };
  48177. Animatable.prototype.pause = function () {
  48178. if (this._paused) {
  48179. return;
  48180. }
  48181. this._paused = true;
  48182. };
  48183. Animatable.prototype.restart = function () {
  48184. this._paused = false;
  48185. };
  48186. Animatable.prototype.stop = function (animationName) {
  48187. if (animationName) {
  48188. var idx = this._scene._activeAnimatables.indexOf(this);
  48189. if (idx > -1) {
  48190. var runtimeAnimations = this._runtimeAnimations;
  48191. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48192. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48193. continue;
  48194. }
  48195. runtimeAnimations[index].dispose();
  48196. runtimeAnimations.splice(index, 1);
  48197. }
  48198. if (runtimeAnimations.length == 0) {
  48199. this._scene._activeAnimatables.splice(idx, 1);
  48200. if (this.onAnimationEnd) {
  48201. this.onAnimationEnd();
  48202. }
  48203. }
  48204. }
  48205. }
  48206. else {
  48207. var index = this._scene._activeAnimatables.indexOf(this);
  48208. if (index > -1) {
  48209. this._scene._activeAnimatables.splice(index, 1);
  48210. var runtimeAnimations = this._runtimeAnimations;
  48211. for (var index = 0; index < runtimeAnimations.length; index++) {
  48212. runtimeAnimations[index].dispose();
  48213. }
  48214. if (this.onAnimationEnd) {
  48215. this.onAnimationEnd();
  48216. }
  48217. }
  48218. }
  48219. };
  48220. Animatable.prototype._animate = function (delay) {
  48221. if (this._paused) {
  48222. this.animationStarted = false;
  48223. if (this._pausedDelay === null) {
  48224. this._pausedDelay = delay;
  48225. }
  48226. return true;
  48227. }
  48228. if (this._localDelayOffset === null) {
  48229. this._localDelayOffset = delay;
  48230. this._pausedDelay = null;
  48231. }
  48232. else if (this._pausedDelay !== null) {
  48233. this._localDelayOffset += delay - this._pausedDelay;
  48234. this._pausedDelay = null;
  48235. }
  48236. // Animating
  48237. var running = false;
  48238. var runtimeAnimations = this._runtimeAnimations;
  48239. var index;
  48240. for (index = 0; index < runtimeAnimations.length; index++) {
  48241. var animation = runtimeAnimations[index];
  48242. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48243. running = running || isRunning;
  48244. }
  48245. this.animationStarted = running;
  48246. if (!running) {
  48247. // Remove from active animatables
  48248. index = this._scene._activeAnimatables.indexOf(this);
  48249. this._scene._activeAnimatables.splice(index, 1);
  48250. // Dispose all runtime animations
  48251. for (index = 0; index < runtimeAnimations.length; index++) {
  48252. runtimeAnimations[index].dispose();
  48253. }
  48254. }
  48255. if (!running && this.onAnimationEnd) {
  48256. this.onAnimationEnd();
  48257. this.onAnimationEnd = null;
  48258. }
  48259. return running;
  48260. };
  48261. return Animatable;
  48262. }());
  48263. BABYLON.Animatable = Animatable;
  48264. })(BABYLON || (BABYLON = {}));
  48265. //# sourceMappingURL=babylon.animatable.js.map
  48266. var BABYLON;
  48267. (function (BABYLON) {
  48268. var EasingFunction = /** @class */ (function () {
  48269. function EasingFunction() {
  48270. // Properties
  48271. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48272. }
  48273. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48274. get: function () {
  48275. return EasingFunction._EASINGMODE_EASEIN;
  48276. },
  48277. enumerable: true,
  48278. configurable: true
  48279. });
  48280. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48281. get: function () {
  48282. return EasingFunction._EASINGMODE_EASEOUT;
  48283. },
  48284. enumerable: true,
  48285. configurable: true
  48286. });
  48287. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48288. get: function () {
  48289. return EasingFunction._EASINGMODE_EASEINOUT;
  48290. },
  48291. enumerable: true,
  48292. configurable: true
  48293. });
  48294. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48295. var n = Math.min(Math.max(easingMode, 0), 2);
  48296. this._easingMode = n;
  48297. };
  48298. EasingFunction.prototype.getEasingMode = function () {
  48299. return this._easingMode;
  48300. };
  48301. EasingFunction.prototype.easeInCore = function (gradient) {
  48302. throw new Error('You must implement this method');
  48303. };
  48304. EasingFunction.prototype.ease = function (gradient) {
  48305. switch (this._easingMode) {
  48306. case EasingFunction.EASINGMODE_EASEIN:
  48307. return this.easeInCore(gradient);
  48308. case EasingFunction.EASINGMODE_EASEOUT:
  48309. return (1 - this.easeInCore(1 - gradient));
  48310. }
  48311. if (gradient >= 0.5) {
  48312. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48313. }
  48314. return (this.easeInCore(gradient * 2) * 0.5);
  48315. };
  48316. //Statics
  48317. EasingFunction._EASINGMODE_EASEIN = 0;
  48318. EasingFunction._EASINGMODE_EASEOUT = 1;
  48319. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48320. return EasingFunction;
  48321. }());
  48322. BABYLON.EasingFunction = EasingFunction;
  48323. var CircleEase = /** @class */ (function (_super) {
  48324. __extends(CircleEase, _super);
  48325. function CircleEase() {
  48326. return _super !== null && _super.apply(this, arguments) || this;
  48327. }
  48328. CircleEase.prototype.easeInCore = function (gradient) {
  48329. gradient = Math.max(0, Math.min(1, gradient));
  48330. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48331. };
  48332. return CircleEase;
  48333. }(EasingFunction));
  48334. BABYLON.CircleEase = CircleEase;
  48335. var BackEase = /** @class */ (function (_super) {
  48336. __extends(BackEase, _super);
  48337. function BackEase(amplitude) {
  48338. if (amplitude === void 0) { amplitude = 1; }
  48339. var _this = _super.call(this) || this;
  48340. _this.amplitude = amplitude;
  48341. return _this;
  48342. }
  48343. BackEase.prototype.easeInCore = function (gradient) {
  48344. var num = Math.max(0, this.amplitude);
  48345. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48346. };
  48347. return BackEase;
  48348. }(EasingFunction));
  48349. BABYLON.BackEase = BackEase;
  48350. var BounceEase = /** @class */ (function (_super) {
  48351. __extends(BounceEase, _super);
  48352. function BounceEase(bounces, bounciness) {
  48353. if (bounces === void 0) { bounces = 3; }
  48354. if (bounciness === void 0) { bounciness = 2; }
  48355. var _this = _super.call(this) || this;
  48356. _this.bounces = bounces;
  48357. _this.bounciness = bounciness;
  48358. return _this;
  48359. }
  48360. BounceEase.prototype.easeInCore = function (gradient) {
  48361. var y = Math.max(0.0, this.bounces);
  48362. var bounciness = this.bounciness;
  48363. if (bounciness <= 1.0) {
  48364. bounciness = 1.001;
  48365. }
  48366. var num9 = Math.pow(bounciness, y);
  48367. var num5 = 1.0 - bounciness;
  48368. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48369. var num15 = gradient * num4;
  48370. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48371. var num3 = Math.floor(num65);
  48372. var num13 = num3 + 1.0;
  48373. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48374. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48375. var num7 = (num8 + num12) * 0.5;
  48376. var num6 = gradient - num7;
  48377. var num2 = num7 - num8;
  48378. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48379. };
  48380. return BounceEase;
  48381. }(EasingFunction));
  48382. BABYLON.BounceEase = BounceEase;
  48383. var CubicEase = /** @class */ (function (_super) {
  48384. __extends(CubicEase, _super);
  48385. function CubicEase() {
  48386. return _super !== null && _super.apply(this, arguments) || this;
  48387. }
  48388. CubicEase.prototype.easeInCore = function (gradient) {
  48389. return (gradient * gradient * gradient);
  48390. };
  48391. return CubicEase;
  48392. }(EasingFunction));
  48393. BABYLON.CubicEase = CubicEase;
  48394. var ElasticEase = /** @class */ (function (_super) {
  48395. __extends(ElasticEase, _super);
  48396. function ElasticEase(oscillations, springiness) {
  48397. if (oscillations === void 0) { oscillations = 3; }
  48398. if (springiness === void 0) { springiness = 3; }
  48399. var _this = _super.call(this) || this;
  48400. _this.oscillations = oscillations;
  48401. _this.springiness = springiness;
  48402. return _this;
  48403. }
  48404. ElasticEase.prototype.easeInCore = function (gradient) {
  48405. var num2;
  48406. var num3 = Math.max(0.0, this.oscillations);
  48407. var num = Math.max(0.0, this.springiness);
  48408. if (num == 0) {
  48409. num2 = gradient;
  48410. }
  48411. else {
  48412. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48413. }
  48414. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48415. };
  48416. return ElasticEase;
  48417. }(EasingFunction));
  48418. BABYLON.ElasticEase = ElasticEase;
  48419. var ExponentialEase = /** @class */ (function (_super) {
  48420. __extends(ExponentialEase, _super);
  48421. function ExponentialEase(exponent) {
  48422. if (exponent === void 0) { exponent = 2; }
  48423. var _this = _super.call(this) || this;
  48424. _this.exponent = exponent;
  48425. return _this;
  48426. }
  48427. ExponentialEase.prototype.easeInCore = function (gradient) {
  48428. if (this.exponent <= 0) {
  48429. return gradient;
  48430. }
  48431. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48432. };
  48433. return ExponentialEase;
  48434. }(EasingFunction));
  48435. BABYLON.ExponentialEase = ExponentialEase;
  48436. var PowerEase = /** @class */ (function (_super) {
  48437. __extends(PowerEase, _super);
  48438. function PowerEase(power) {
  48439. if (power === void 0) { power = 2; }
  48440. var _this = _super.call(this) || this;
  48441. _this.power = power;
  48442. return _this;
  48443. }
  48444. PowerEase.prototype.easeInCore = function (gradient) {
  48445. var y = Math.max(0.0, this.power);
  48446. return Math.pow(gradient, y);
  48447. };
  48448. return PowerEase;
  48449. }(EasingFunction));
  48450. BABYLON.PowerEase = PowerEase;
  48451. var QuadraticEase = /** @class */ (function (_super) {
  48452. __extends(QuadraticEase, _super);
  48453. function QuadraticEase() {
  48454. return _super !== null && _super.apply(this, arguments) || this;
  48455. }
  48456. QuadraticEase.prototype.easeInCore = function (gradient) {
  48457. return (gradient * gradient);
  48458. };
  48459. return QuadraticEase;
  48460. }(EasingFunction));
  48461. BABYLON.QuadraticEase = QuadraticEase;
  48462. var QuarticEase = /** @class */ (function (_super) {
  48463. __extends(QuarticEase, _super);
  48464. function QuarticEase() {
  48465. return _super !== null && _super.apply(this, arguments) || this;
  48466. }
  48467. QuarticEase.prototype.easeInCore = function (gradient) {
  48468. return (gradient * gradient * gradient * gradient);
  48469. };
  48470. return QuarticEase;
  48471. }(EasingFunction));
  48472. BABYLON.QuarticEase = QuarticEase;
  48473. var QuinticEase = /** @class */ (function (_super) {
  48474. __extends(QuinticEase, _super);
  48475. function QuinticEase() {
  48476. return _super !== null && _super.apply(this, arguments) || this;
  48477. }
  48478. QuinticEase.prototype.easeInCore = function (gradient) {
  48479. return (gradient * gradient * gradient * gradient * gradient);
  48480. };
  48481. return QuinticEase;
  48482. }(EasingFunction));
  48483. BABYLON.QuinticEase = QuinticEase;
  48484. var SineEase = /** @class */ (function (_super) {
  48485. __extends(SineEase, _super);
  48486. function SineEase() {
  48487. return _super !== null && _super.apply(this, arguments) || this;
  48488. }
  48489. SineEase.prototype.easeInCore = function (gradient) {
  48490. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48491. };
  48492. return SineEase;
  48493. }(EasingFunction));
  48494. BABYLON.SineEase = SineEase;
  48495. var BezierCurveEase = /** @class */ (function (_super) {
  48496. __extends(BezierCurveEase, _super);
  48497. function BezierCurveEase(x1, y1, x2, y2) {
  48498. if (x1 === void 0) { x1 = 0; }
  48499. if (y1 === void 0) { y1 = 0; }
  48500. if (x2 === void 0) { x2 = 1; }
  48501. if (y2 === void 0) { y2 = 1; }
  48502. var _this = _super.call(this) || this;
  48503. _this.x1 = x1;
  48504. _this.y1 = y1;
  48505. _this.x2 = x2;
  48506. _this.y2 = y2;
  48507. return _this;
  48508. }
  48509. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48510. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48511. };
  48512. return BezierCurveEase;
  48513. }(EasingFunction));
  48514. BABYLON.BezierCurveEase = BezierCurveEase;
  48515. })(BABYLON || (BABYLON = {}));
  48516. //# sourceMappingURL=babylon.easing.js.map
  48517. var BABYLON;
  48518. (function (BABYLON) {
  48519. var Condition = /** @class */ (function () {
  48520. function Condition(actionManager) {
  48521. this._actionManager = actionManager;
  48522. }
  48523. Condition.prototype.isValid = function () {
  48524. return true;
  48525. };
  48526. Condition.prototype._getProperty = function (propertyPath) {
  48527. return this._actionManager._getProperty(propertyPath);
  48528. };
  48529. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48530. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48531. };
  48532. Condition.prototype.serialize = function () {
  48533. };
  48534. Condition.prototype._serialize = function (serializedCondition) {
  48535. return {
  48536. type: 2,
  48537. children: [],
  48538. name: serializedCondition.name,
  48539. properties: serializedCondition.properties
  48540. };
  48541. };
  48542. return Condition;
  48543. }());
  48544. BABYLON.Condition = Condition;
  48545. var ValueCondition = /** @class */ (function (_super) {
  48546. __extends(ValueCondition, _super);
  48547. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48548. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48549. var _this = _super.call(this, actionManager) || this;
  48550. _this.propertyPath = propertyPath;
  48551. _this.value = value;
  48552. _this.operator = operator;
  48553. _this._target = target;
  48554. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48555. _this._property = _this._getProperty(_this.propertyPath);
  48556. return _this;
  48557. }
  48558. Object.defineProperty(ValueCondition, "IsEqual", {
  48559. get: function () {
  48560. return ValueCondition._IsEqual;
  48561. },
  48562. enumerable: true,
  48563. configurable: true
  48564. });
  48565. Object.defineProperty(ValueCondition, "IsDifferent", {
  48566. get: function () {
  48567. return ValueCondition._IsDifferent;
  48568. },
  48569. enumerable: true,
  48570. configurable: true
  48571. });
  48572. Object.defineProperty(ValueCondition, "IsGreater", {
  48573. get: function () {
  48574. return ValueCondition._IsGreater;
  48575. },
  48576. enumerable: true,
  48577. configurable: true
  48578. });
  48579. Object.defineProperty(ValueCondition, "IsLesser", {
  48580. get: function () {
  48581. return ValueCondition._IsLesser;
  48582. },
  48583. enumerable: true,
  48584. configurable: true
  48585. });
  48586. // Methods
  48587. ValueCondition.prototype.isValid = function () {
  48588. switch (this.operator) {
  48589. case ValueCondition.IsGreater:
  48590. return this._effectiveTarget[this._property] > this.value;
  48591. case ValueCondition.IsLesser:
  48592. return this._effectiveTarget[this._property] < this.value;
  48593. case ValueCondition.IsEqual:
  48594. case ValueCondition.IsDifferent:
  48595. var check;
  48596. if (this.value.equals) {
  48597. check = this.value.equals(this._effectiveTarget[this._property]);
  48598. }
  48599. else {
  48600. check = this.value === this._effectiveTarget[this._property];
  48601. }
  48602. return this.operator === ValueCondition.IsEqual ? check : !check;
  48603. }
  48604. return false;
  48605. };
  48606. ValueCondition.prototype.serialize = function () {
  48607. return this._serialize({
  48608. name: "ValueCondition",
  48609. properties: [
  48610. BABYLON.Action._GetTargetProperty(this._target),
  48611. { name: "propertyPath", value: this.propertyPath },
  48612. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48613. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48614. ]
  48615. });
  48616. };
  48617. ValueCondition.GetOperatorName = function (operator) {
  48618. switch (operator) {
  48619. case ValueCondition._IsEqual: return "IsEqual";
  48620. case ValueCondition._IsDifferent: return "IsDifferent";
  48621. case ValueCondition._IsGreater: return "IsGreater";
  48622. case ValueCondition._IsLesser: return "IsLesser";
  48623. default: return "";
  48624. }
  48625. };
  48626. // Statics
  48627. ValueCondition._IsEqual = 0;
  48628. ValueCondition._IsDifferent = 1;
  48629. ValueCondition._IsGreater = 2;
  48630. ValueCondition._IsLesser = 3;
  48631. return ValueCondition;
  48632. }(Condition));
  48633. BABYLON.ValueCondition = ValueCondition;
  48634. var PredicateCondition = /** @class */ (function (_super) {
  48635. __extends(PredicateCondition, _super);
  48636. function PredicateCondition(actionManager, predicate) {
  48637. var _this = _super.call(this, actionManager) || this;
  48638. _this.predicate = predicate;
  48639. return _this;
  48640. }
  48641. PredicateCondition.prototype.isValid = function () {
  48642. return this.predicate();
  48643. };
  48644. return PredicateCondition;
  48645. }(Condition));
  48646. BABYLON.PredicateCondition = PredicateCondition;
  48647. var StateCondition = /** @class */ (function (_super) {
  48648. __extends(StateCondition, _super);
  48649. function StateCondition(actionManager, target, value) {
  48650. var _this = _super.call(this, actionManager) || this;
  48651. _this.value = value;
  48652. _this._target = target;
  48653. return _this;
  48654. }
  48655. // Methods
  48656. StateCondition.prototype.isValid = function () {
  48657. return this._target.state === this.value;
  48658. };
  48659. StateCondition.prototype.serialize = function () {
  48660. return this._serialize({
  48661. name: "StateCondition",
  48662. properties: [
  48663. BABYLON.Action._GetTargetProperty(this._target),
  48664. { name: "value", value: this.value }
  48665. ]
  48666. });
  48667. };
  48668. return StateCondition;
  48669. }(Condition));
  48670. BABYLON.StateCondition = StateCondition;
  48671. })(BABYLON || (BABYLON = {}));
  48672. //# sourceMappingURL=babylon.condition.js.map
  48673. var BABYLON;
  48674. (function (BABYLON) {
  48675. var Action = /** @class */ (function () {
  48676. function Action(triggerOptions, condition) {
  48677. this.triggerOptions = triggerOptions;
  48678. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48679. if (triggerOptions.parameter) {
  48680. this.trigger = triggerOptions.trigger;
  48681. this._triggerParameter = triggerOptions.parameter;
  48682. }
  48683. else {
  48684. this.trigger = triggerOptions;
  48685. }
  48686. this._nextActiveAction = this;
  48687. this._condition = condition;
  48688. }
  48689. // Methods
  48690. Action.prototype._prepare = function () {
  48691. };
  48692. Action.prototype.getTriggerParameter = function () {
  48693. return this._triggerParameter;
  48694. };
  48695. Action.prototype._executeCurrent = function (evt) {
  48696. if (this._nextActiveAction._condition) {
  48697. var condition = this._nextActiveAction._condition;
  48698. var currentRenderId = this._actionManager.getScene().getRenderId();
  48699. // We cache the current evaluation for the current frame
  48700. if (condition._evaluationId === currentRenderId) {
  48701. if (!condition._currentResult) {
  48702. return;
  48703. }
  48704. }
  48705. else {
  48706. condition._evaluationId = currentRenderId;
  48707. if (!condition.isValid()) {
  48708. condition._currentResult = false;
  48709. return;
  48710. }
  48711. condition._currentResult = true;
  48712. }
  48713. }
  48714. this.onBeforeExecuteObservable.notifyObservers(this);
  48715. this._nextActiveAction.execute(evt);
  48716. this.skipToNextActiveAction();
  48717. };
  48718. Action.prototype.execute = function (evt) {
  48719. };
  48720. Action.prototype.skipToNextActiveAction = function () {
  48721. if (this._nextActiveAction._child) {
  48722. if (!this._nextActiveAction._child._actionManager) {
  48723. this._nextActiveAction._child._actionManager = this._actionManager;
  48724. }
  48725. this._nextActiveAction = this._nextActiveAction._child;
  48726. }
  48727. else {
  48728. this._nextActiveAction = this;
  48729. }
  48730. };
  48731. Action.prototype.then = function (action) {
  48732. this._child = action;
  48733. action._actionManager = this._actionManager;
  48734. action._prepare();
  48735. return action;
  48736. };
  48737. Action.prototype._getProperty = function (propertyPath) {
  48738. return this._actionManager._getProperty(propertyPath);
  48739. };
  48740. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48741. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48742. };
  48743. Action.prototype.serialize = function (parent) {
  48744. };
  48745. // Called by BABYLON.Action objects in serialize(...). Internal use
  48746. Action.prototype._serialize = function (serializedAction, parent) {
  48747. var serializationObject = {
  48748. type: 1,
  48749. children: [],
  48750. name: serializedAction.name,
  48751. properties: serializedAction.properties || []
  48752. };
  48753. // Serialize child
  48754. if (this._child) {
  48755. this._child.serialize(serializationObject);
  48756. }
  48757. // Check if "this" has a condition
  48758. if (this._condition) {
  48759. var serializedCondition = this._condition.serialize();
  48760. serializedCondition.children.push(serializationObject);
  48761. if (parent) {
  48762. parent.children.push(serializedCondition);
  48763. }
  48764. return serializedCondition;
  48765. }
  48766. if (parent) {
  48767. parent.children.push(serializationObject);
  48768. }
  48769. return serializationObject;
  48770. };
  48771. Action._SerializeValueAsString = function (value) {
  48772. if (typeof value === "number") {
  48773. return value.toString();
  48774. }
  48775. if (typeof value === "boolean") {
  48776. return value ? "true" : "false";
  48777. }
  48778. if (value instanceof BABYLON.Vector2) {
  48779. return value.x + ", " + value.y;
  48780. }
  48781. if (value instanceof BABYLON.Vector3) {
  48782. return value.x + ", " + value.y + ", " + value.z;
  48783. }
  48784. if (value instanceof BABYLON.Color3) {
  48785. return value.r + ", " + value.g + ", " + value.b;
  48786. }
  48787. if (value instanceof BABYLON.Color4) {
  48788. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48789. }
  48790. return value; // string
  48791. };
  48792. Action._GetTargetProperty = function (target) {
  48793. return {
  48794. name: "target",
  48795. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48796. : target instanceof BABYLON.Light ? "LightProperties"
  48797. : target instanceof BABYLON.Camera ? "CameraProperties"
  48798. : "SceneProperties",
  48799. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48800. };
  48801. };
  48802. return Action;
  48803. }());
  48804. BABYLON.Action = Action;
  48805. })(BABYLON || (BABYLON = {}));
  48806. //# sourceMappingURL=babylon.action.js.map
  48807. var BABYLON;
  48808. (function (BABYLON) {
  48809. /**
  48810. * ActionEvent is the event beint sent when an action is triggered.
  48811. */
  48812. var ActionEvent = /** @class */ (function () {
  48813. /**
  48814. * @param source The mesh or sprite that triggered the action.
  48815. * @param pointerX The X mouse cursor position at the time of the event
  48816. * @param pointerY The Y mouse cursor position at the time of the event
  48817. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48818. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48819. */
  48820. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48821. this.source = source;
  48822. this.pointerX = pointerX;
  48823. this.pointerY = pointerY;
  48824. this.meshUnderPointer = meshUnderPointer;
  48825. this.sourceEvent = sourceEvent;
  48826. this.additionalData = additionalData;
  48827. }
  48828. /**
  48829. * Helper function to auto-create an ActionEvent from a source mesh.
  48830. * @param source The source mesh that triggered the event
  48831. * @param evt {Event} The original (browser) event
  48832. */
  48833. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48834. var scene = source.getScene();
  48835. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48836. };
  48837. /**
  48838. * Helper function to auto-create an ActionEvent from a source mesh.
  48839. * @param source The source sprite that triggered the event
  48840. * @param scene Scene associated with the sprite
  48841. * @param evt {Event} The original (browser) event
  48842. */
  48843. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48844. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48845. };
  48846. /**
  48847. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48848. * @param scene the scene where the event occurred
  48849. * @param evt {Event} The original (browser) event
  48850. */
  48851. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48852. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48853. };
  48854. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48855. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48856. };
  48857. return ActionEvent;
  48858. }());
  48859. BABYLON.ActionEvent = ActionEvent;
  48860. /**
  48861. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48862. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48863. */
  48864. var ActionManager = /** @class */ (function () {
  48865. function ActionManager(scene) {
  48866. // Members
  48867. this.actions = new Array();
  48868. this.hoverCursor = '';
  48869. this._scene = scene;
  48870. scene._actionManagers.push(this);
  48871. }
  48872. Object.defineProperty(ActionManager, "NothingTrigger", {
  48873. get: function () {
  48874. return ActionManager._NothingTrigger;
  48875. },
  48876. enumerable: true,
  48877. configurable: true
  48878. });
  48879. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48880. get: function () {
  48881. return ActionManager._OnPickTrigger;
  48882. },
  48883. enumerable: true,
  48884. configurable: true
  48885. });
  48886. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48887. get: function () {
  48888. return ActionManager._OnLeftPickTrigger;
  48889. },
  48890. enumerable: true,
  48891. configurable: true
  48892. });
  48893. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48894. get: function () {
  48895. return ActionManager._OnRightPickTrigger;
  48896. },
  48897. enumerable: true,
  48898. configurable: true
  48899. });
  48900. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48901. get: function () {
  48902. return ActionManager._OnCenterPickTrigger;
  48903. },
  48904. enumerable: true,
  48905. configurable: true
  48906. });
  48907. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48908. get: function () {
  48909. return ActionManager._OnPickDownTrigger;
  48910. },
  48911. enumerable: true,
  48912. configurable: true
  48913. });
  48914. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48915. get: function () {
  48916. return ActionManager._OnDoublePickTrigger;
  48917. },
  48918. enumerable: true,
  48919. configurable: true
  48920. });
  48921. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48922. get: function () {
  48923. return ActionManager._OnPickUpTrigger;
  48924. },
  48925. enumerable: true,
  48926. configurable: true
  48927. });
  48928. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48929. /// This trigger will only be raised if you also declared a OnPickDown
  48930. get: function () {
  48931. return ActionManager._OnPickOutTrigger;
  48932. },
  48933. enumerable: true,
  48934. configurable: true
  48935. });
  48936. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48937. get: function () {
  48938. return ActionManager._OnLongPressTrigger;
  48939. },
  48940. enumerable: true,
  48941. configurable: true
  48942. });
  48943. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48944. get: function () {
  48945. return ActionManager._OnPointerOverTrigger;
  48946. },
  48947. enumerable: true,
  48948. configurable: true
  48949. });
  48950. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48951. get: function () {
  48952. return ActionManager._OnPointerOutTrigger;
  48953. },
  48954. enumerable: true,
  48955. configurable: true
  48956. });
  48957. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48958. get: function () {
  48959. return ActionManager._OnEveryFrameTrigger;
  48960. },
  48961. enumerable: true,
  48962. configurable: true
  48963. });
  48964. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48965. get: function () {
  48966. return ActionManager._OnIntersectionEnterTrigger;
  48967. },
  48968. enumerable: true,
  48969. configurable: true
  48970. });
  48971. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48972. get: function () {
  48973. return ActionManager._OnIntersectionExitTrigger;
  48974. },
  48975. enumerable: true,
  48976. configurable: true
  48977. });
  48978. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48979. get: function () {
  48980. return ActionManager._OnKeyDownTrigger;
  48981. },
  48982. enumerable: true,
  48983. configurable: true
  48984. });
  48985. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48986. get: function () {
  48987. return ActionManager._OnKeyUpTrigger;
  48988. },
  48989. enumerable: true,
  48990. configurable: true
  48991. });
  48992. // Methods
  48993. ActionManager.prototype.dispose = function () {
  48994. var index = this._scene._actionManagers.indexOf(this);
  48995. for (var i = 0; i < this.actions.length; i++) {
  48996. var action = this.actions[i];
  48997. ActionManager.Triggers[action.trigger]--;
  48998. if (ActionManager.Triggers[action.trigger] === 0) {
  48999. delete ActionManager.Triggers[action.trigger];
  49000. }
  49001. }
  49002. if (index > -1) {
  49003. this._scene._actionManagers.splice(index, 1);
  49004. }
  49005. };
  49006. ActionManager.prototype.getScene = function () {
  49007. return this._scene;
  49008. };
  49009. /**
  49010. * Does this action manager handles actions of any of the given triggers
  49011. * @param {number[]} triggers - the triggers to be tested
  49012. * @return {boolean} whether one (or more) of the triggers is handeled
  49013. */
  49014. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49015. for (var index = 0; index < this.actions.length; index++) {
  49016. var action = this.actions[index];
  49017. if (triggers.indexOf(action.trigger) > -1) {
  49018. return true;
  49019. }
  49020. }
  49021. return false;
  49022. };
  49023. /**
  49024. * Does this action manager handles actions of a given trigger
  49025. * @param {number} trigger - the trigger to be tested
  49026. * @return {boolean} whether the trigger is handeled
  49027. */
  49028. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49029. for (var index = 0; index < this.actions.length; index++) {
  49030. var action = this.actions[index];
  49031. if (action.trigger === trigger) {
  49032. return true;
  49033. }
  49034. }
  49035. return false;
  49036. };
  49037. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49038. /**
  49039. * Does this action manager has pointer triggers
  49040. * @return {boolean} whether or not it has pointer triggers
  49041. */
  49042. get: function () {
  49043. for (var index = 0; index < this.actions.length; index++) {
  49044. var action = this.actions[index];
  49045. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49046. return true;
  49047. }
  49048. }
  49049. return false;
  49050. },
  49051. enumerable: true,
  49052. configurable: true
  49053. });
  49054. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49055. /**
  49056. * Does this action manager has pick triggers
  49057. * @return {boolean} whether or not it has pick triggers
  49058. */
  49059. get: function () {
  49060. for (var index = 0; index < this.actions.length; index++) {
  49061. var action = this.actions[index];
  49062. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49063. return true;
  49064. }
  49065. }
  49066. return false;
  49067. },
  49068. enumerable: true,
  49069. configurable: true
  49070. });
  49071. Object.defineProperty(ActionManager, "HasTriggers", {
  49072. /**
  49073. * Does exist one action manager with at least one trigger
  49074. * @return {boolean} whether or not it exists one action manager with one trigger
  49075. **/
  49076. get: function () {
  49077. for (var t in ActionManager.Triggers) {
  49078. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49079. return true;
  49080. }
  49081. }
  49082. return false;
  49083. },
  49084. enumerable: true,
  49085. configurable: true
  49086. });
  49087. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49088. /**
  49089. * Does exist one action manager with at least one pick trigger
  49090. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49091. **/
  49092. get: function () {
  49093. for (var t in ActionManager.Triggers) {
  49094. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49095. var t_int = parseInt(t);
  49096. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49097. return true;
  49098. }
  49099. }
  49100. }
  49101. return false;
  49102. },
  49103. enumerable: true,
  49104. configurable: true
  49105. });
  49106. /**
  49107. * Does exist one action manager that handles actions of a given trigger
  49108. * @param {number} trigger - the trigger to be tested
  49109. * @return {boolean} whether the trigger is handeled by at least one action manager
  49110. **/
  49111. ActionManager.HasSpecificTrigger = function (trigger) {
  49112. for (var t in ActionManager.Triggers) {
  49113. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49114. var t_int = parseInt(t);
  49115. if (t_int === trigger) {
  49116. return true;
  49117. }
  49118. }
  49119. }
  49120. return false;
  49121. };
  49122. /**
  49123. * Registers an action to this action manager
  49124. * @param {BABYLON.Action} action - the action to be registered
  49125. * @return {BABYLON.Action} the action amended (prepared) after registration
  49126. */
  49127. ActionManager.prototype.registerAction = function (action) {
  49128. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49129. if (this.getScene().actionManager !== this) {
  49130. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49131. return null;
  49132. }
  49133. }
  49134. this.actions.push(action);
  49135. if (ActionManager.Triggers[action.trigger]) {
  49136. ActionManager.Triggers[action.trigger]++;
  49137. }
  49138. else {
  49139. ActionManager.Triggers[action.trigger] = 1;
  49140. }
  49141. action._actionManager = this;
  49142. action._prepare();
  49143. return action;
  49144. };
  49145. /**
  49146. * Unregisters an action to this action manager
  49147. * @param action The action to be unregistered
  49148. * @return whether the action has been unregistered
  49149. */
  49150. ActionManager.prototype.unregisterAction = function (action) {
  49151. var index = this.actions.indexOf(action);
  49152. if (index !== -1) {
  49153. this.actions.splice(index, 1);
  49154. ActionManager.Triggers[action.trigger] -= 1;
  49155. if (ActionManager.Triggers[action.trigger] === 0) {
  49156. delete ActionManager.Triggers[action.trigger];
  49157. }
  49158. delete action._actionManager;
  49159. return true;
  49160. }
  49161. return false;
  49162. };
  49163. /**
  49164. * Process a specific trigger
  49165. * @param {number} trigger - the trigger to process
  49166. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49167. */
  49168. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49169. for (var index = 0; index < this.actions.length; index++) {
  49170. var action = this.actions[index];
  49171. if (action.trigger === trigger) {
  49172. if (evt) {
  49173. if (trigger === ActionManager.OnKeyUpTrigger
  49174. || trigger === ActionManager.OnKeyDownTrigger) {
  49175. var parameter = action.getTriggerParameter();
  49176. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49177. if (!parameter.toLowerCase) {
  49178. continue;
  49179. }
  49180. var lowerCase = parameter.toLowerCase();
  49181. if (lowerCase !== evt.sourceEvent.key) {
  49182. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49183. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49184. if (actualkey !== lowerCase) {
  49185. continue;
  49186. }
  49187. }
  49188. }
  49189. }
  49190. }
  49191. action._executeCurrent(evt);
  49192. }
  49193. }
  49194. };
  49195. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49196. var properties = propertyPath.split(".");
  49197. for (var index = 0; index < properties.length - 1; index++) {
  49198. target = target[properties[index]];
  49199. }
  49200. return target;
  49201. };
  49202. ActionManager.prototype._getProperty = function (propertyPath) {
  49203. var properties = propertyPath.split(".");
  49204. return properties[properties.length - 1];
  49205. };
  49206. ActionManager.prototype.serialize = function (name) {
  49207. var root = {
  49208. children: new Array(),
  49209. name: name,
  49210. type: 3,
  49211. properties: new Array() // Empty for root but required
  49212. };
  49213. for (var i = 0; i < this.actions.length; i++) {
  49214. var triggerObject = {
  49215. type: 0,
  49216. children: new Array(),
  49217. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49218. properties: new Array()
  49219. };
  49220. var triggerOptions = this.actions[i].triggerOptions;
  49221. if (triggerOptions && typeof triggerOptions !== "number") {
  49222. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49223. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49224. }
  49225. else {
  49226. var parameter = {};
  49227. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49228. if (triggerOptions.parameter.mesh) {
  49229. parameter._meshId = triggerOptions.parameter.mesh.id;
  49230. }
  49231. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49232. }
  49233. }
  49234. // Serialize child action, recursively
  49235. this.actions[i].serialize(triggerObject);
  49236. // Add serialized trigger
  49237. root.children.push(triggerObject);
  49238. }
  49239. return root;
  49240. };
  49241. ActionManager.Parse = function (parsedActions, object, scene) {
  49242. var actionManager = new ActionManager(scene);
  49243. if (object === null)
  49244. scene.actionManager = actionManager;
  49245. else
  49246. object.actionManager = actionManager;
  49247. // instanciate a new object
  49248. var instanciate = function (name, params) {
  49249. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49250. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49251. newInstance.constructor.apply(newInstance, params);
  49252. return newInstance;
  49253. };
  49254. var parseParameter = function (name, value, target, propertyPath) {
  49255. if (propertyPath === null) {
  49256. // String, boolean or float
  49257. var floatValue = parseFloat(value);
  49258. if (value === "true" || value === "false")
  49259. return value === "true";
  49260. else
  49261. return isNaN(floatValue) ? value : floatValue;
  49262. }
  49263. var effectiveTarget = propertyPath.split(".");
  49264. var values = value.split(",");
  49265. // Get effective Target
  49266. for (var i = 0; i < effectiveTarget.length; i++) {
  49267. target = target[effectiveTarget[i]];
  49268. }
  49269. // Return appropriate value with its type
  49270. if (typeof (target) === "boolean")
  49271. return values[0] === "true";
  49272. if (typeof (target) === "string")
  49273. return values[0];
  49274. // Parameters with multiple values such as Vector3 etc.
  49275. var split = new Array();
  49276. for (var i = 0; i < values.length; i++)
  49277. split.push(parseFloat(values[i]));
  49278. if (target instanceof BABYLON.Vector3)
  49279. return BABYLON.Vector3.FromArray(split);
  49280. if (target instanceof BABYLON.Vector4)
  49281. return BABYLON.Vector4.FromArray(split);
  49282. if (target instanceof BABYLON.Color3)
  49283. return BABYLON.Color3.FromArray(split);
  49284. if (target instanceof BABYLON.Color4)
  49285. return BABYLON.Color4.FromArray(split);
  49286. return parseFloat(values[0]);
  49287. };
  49288. // traverse graph per trigger
  49289. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49290. if (combineArray === void 0) { combineArray = null; }
  49291. if (parsedAction.detached)
  49292. return;
  49293. var parameters = new Array();
  49294. var target = null;
  49295. var propertyPath = null;
  49296. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49297. // Parameters
  49298. if (parsedAction.type === 2)
  49299. parameters.push(actionManager);
  49300. else
  49301. parameters.push(trigger);
  49302. if (combine) {
  49303. var actions = new Array();
  49304. for (var j = 0; j < parsedAction.combine.length; j++) {
  49305. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49306. }
  49307. parameters.push(actions);
  49308. }
  49309. else {
  49310. for (var i = 0; i < parsedAction.properties.length; i++) {
  49311. var value = parsedAction.properties[i].value;
  49312. var name = parsedAction.properties[i].name;
  49313. var targetType = parsedAction.properties[i].targetType;
  49314. if (name === "target")
  49315. if (targetType !== null && targetType === "SceneProperties")
  49316. value = target = scene;
  49317. else
  49318. value = target = scene.getNodeByName(value);
  49319. else if (name === "parent")
  49320. value = scene.getNodeByName(value);
  49321. else if (name === "sound")
  49322. value = scene.getSoundByName(value);
  49323. else if (name !== "propertyPath") {
  49324. if (parsedAction.type === 2 && name === "operator")
  49325. value = BABYLON.ValueCondition[value];
  49326. else
  49327. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49328. }
  49329. else {
  49330. propertyPath = value;
  49331. }
  49332. parameters.push(value);
  49333. }
  49334. }
  49335. if (combineArray === null) {
  49336. parameters.push(condition);
  49337. }
  49338. else {
  49339. parameters.push(null);
  49340. }
  49341. // If interpolate value action
  49342. if (parsedAction.name === "InterpolateValueAction") {
  49343. var param = parameters[parameters.length - 2];
  49344. parameters[parameters.length - 1] = param;
  49345. parameters[parameters.length - 2] = condition;
  49346. }
  49347. // Action or condition(s) and not CombineAction
  49348. var newAction = instanciate(parsedAction.name, parameters);
  49349. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49350. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49351. if (action)
  49352. action.then(nothing);
  49353. else
  49354. actionManager.registerAction(nothing);
  49355. action = nothing;
  49356. }
  49357. if (combineArray === null) {
  49358. if (newAction instanceof BABYLON.Condition) {
  49359. condition = newAction;
  49360. newAction = action;
  49361. }
  49362. else {
  49363. condition = null;
  49364. if (action)
  49365. action.then(newAction);
  49366. else
  49367. actionManager.registerAction(newAction);
  49368. }
  49369. }
  49370. else {
  49371. combineArray.push(newAction);
  49372. }
  49373. for (var i = 0; i < parsedAction.children.length; i++)
  49374. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49375. };
  49376. // triggers
  49377. for (var i = 0; i < parsedActions.children.length; i++) {
  49378. var triggerParams;
  49379. var trigger = parsedActions.children[i];
  49380. if (trigger.properties.length > 0) {
  49381. var param = trigger.properties[0].value;
  49382. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49383. if (value._meshId) {
  49384. value.mesh = scene.getMeshByID(value._meshId);
  49385. }
  49386. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49387. }
  49388. else
  49389. triggerParams = ActionManager[trigger.name];
  49390. for (var j = 0; j < trigger.children.length; j++) {
  49391. if (!trigger.detached)
  49392. traverse(trigger.children[j], triggerParams, null, null);
  49393. }
  49394. }
  49395. };
  49396. ActionManager.GetTriggerName = function (trigger) {
  49397. switch (trigger) {
  49398. case 0: return "NothingTrigger";
  49399. case 1: return "OnPickTrigger";
  49400. case 2: return "OnLeftPickTrigger";
  49401. case 3: return "OnRightPickTrigger";
  49402. case 4: return "OnCenterPickTrigger";
  49403. case 5: return "OnPickDownTrigger";
  49404. case 6: return "OnPickUpTrigger";
  49405. case 7: return "OnLongPressTrigger";
  49406. case 8: return "OnPointerOverTrigger";
  49407. case 9: return "OnPointerOutTrigger";
  49408. case 10: return "OnEveryFrameTrigger";
  49409. case 11: return "OnIntersectionEnterTrigger";
  49410. case 12: return "OnIntersectionExitTrigger";
  49411. case 13: return "OnKeyDownTrigger";
  49412. case 14: return "OnKeyUpTrigger";
  49413. case 15: return "OnPickOutTrigger";
  49414. default: return "";
  49415. }
  49416. };
  49417. // Statics
  49418. ActionManager._NothingTrigger = 0;
  49419. ActionManager._OnPickTrigger = 1;
  49420. ActionManager._OnLeftPickTrigger = 2;
  49421. ActionManager._OnRightPickTrigger = 3;
  49422. ActionManager._OnCenterPickTrigger = 4;
  49423. ActionManager._OnPickDownTrigger = 5;
  49424. ActionManager._OnDoublePickTrigger = 6;
  49425. ActionManager._OnPickUpTrigger = 7;
  49426. ActionManager._OnLongPressTrigger = 8;
  49427. ActionManager._OnPointerOverTrigger = 9;
  49428. ActionManager._OnPointerOutTrigger = 10;
  49429. ActionManager._OnEveryFrameTrigger = 11;
  49430. ActionManager._OnIntersectionEnterTrigger = 12;
  49431. ActionManager._OnIntersectionExitTrigger = 13;
  49432. ActionManager._OnKeyDownTrigger = 14;
  49433. ActionManager._OnKeyUpTrigger = 15;
  49434. ActionManager._OnPickOutTrigger = 16;
  49435. ActionManager.Triggers = {};
  49436. return ActionManager;
  49437. }());
  49438. BABYLON.ActionManager = ActionManager;
  49439. })(BABYLON || (BABYLON = {}));
  49440. //# sourceMappingURL=babylon.actionManager.js.map
  49441. var BABYLON;
  49442. (function (BABYLON) {
  49443. var InterpolateValueAction = /** @class */ (function (_super) {
  49444. __extends(InterpolateValueAction, _super);
  49445. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49446. if (duration === void 0) { duration = 1000; }
  49447. var _this = _super.call(this, triggerOptions, condition) || this;
  49448. _this.propertyPath = propertyPath;
  49449. _this.value = value;
  49450. _this.duration = duration;
  49451. _this.stopOtherAnimations = stopOtherAnimations;
  49452. _this.onInterpolationDone = onInterpolationDone;
  49453. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49454. _this._target = _this._effectiveTarget = target;
  49455. return _this;
  49456. }
  49457. InterpolateValueAction.prototype._prepare = function () {
  49458. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49459. this._property = this._getProperty(this.propertyPath);
  49460. };
  49461. InterpolateValueAction.prototype.execute = function () {
  49462. var _this = this;
  49463. var scene = this._actionManager.getScene();
  49464. var keys = [
  49465. {
  49466. frame: 0,
  49467. value: this._effectiveTarget[this._property]
  49468. }, {
  49469. frame: 100,
  49470. value: this.value
  49471. }
  49472. ];
  49473. var dataType;
  49474. if (typeof this.value === "number") {
  49475. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49476. }
  49477. else if (this.value instanceof BABYLON.Color3) {
  49478. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49479. }
  49480. else if (this.value instanceof BABYLON.Vector3) {
  49481. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49482. }
  49483. else if (this.value instanceof BABYLON.Matrix) {
  49484. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49485. }
  49486. else if (this.value instanceof BABYLON.Quaternion) {
  49487. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49488. }
  49489. else {
  49490. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49491. return;
  49492. }
  49493. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49494. animation.setKeys(keys);
  49495. if (this.stopOtherAnimations) {
  49496. scene.stopAnimation(this._effectiveTarget);
  49497. }
  49498. var wrapper = function () {
  49499. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49500. if (_this.onInterpolationDone) {
  49501. _this.onInterpolationDone();
  49502. }
  49503. };
  49504. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49505. };
  49506. InterpolateValueAction.prototype.serialize = function (parent) {
  49507. return _super.prototype._serialize.call(this, {
  49508. name: "InterpolateValueAction",
  49509. properties: [
  49510. BABYLON.Action._GetTargetProperty(this._target),
  49511. { name: "propertyPath", value: this.propertyPath },
  49512. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49513. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49514. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49515. ]
  49516. }, parent);
  49517. };
  49518. return InterpolateValueAction;
  49519. }(BABYLON.Action));
  49520. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49521. })(BABYLON || (BABYLON = {}));
  49522. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49523. var BABYLON;
  49524. (function (BABYLON) {
  49525. var SwitchBooleanAction = /** @class */ (function (_super) {
  49526. __extends(SwitchBooleanAction, _super);
  49527. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49528. var _this = _super.call(this, triggerOptions, condition) || this;
  49529. _this.propertyPath = propertyPath;
  49530. _this._target = _this._effectiveTarget = target;
  49531. return _this;
  49532. }
  49533. SwitchBooleanAction.prototype._prepare = function () {
  49534. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49535. this._property = this._getProperty(this.propertyPath);
  49536. };
  49537. SwitchBooleanAction.prototype.execute = function () {
  49538. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49539. };
  49540. SwitchBooleanAction.prototype.serialize = function (parent) {
  49541. return _super.prototype._serialize.call(this, {
  49542. name: "SwitchBooleanAction",
  49543. properties: [
  49544. BABYLON.Action._GetTargetProperty(this._target),
  49545. { name: "propertyPath", value: this.propertyPath }
  49546. ]
  49547. }, parent);
  49548. };
  49549. return SwitchBooleanAction;
  49550. }(BABYLON.Action));
  49551. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49552. var SetStateAction = /** @class */ (function (_super) {
  49553. __extends(SetStateAction, _super);
  49554. function SetStateAction(triggerOptions, target, value, condition) {
  49555. var _this = _super.call(this, triggerOptions, condition) || this;
  49556. _this.value = value;
  49557. _this._target = target;
  49558. return _this;
  49559. }
  49560. SetStateAction.prototype.execute = function () {
  49561. this._target.state = this.value;
  49562. };
  49563. SetStateAction.prototype.serialize = function (parent) {
  49564. return _super.prototype._serialize.call(this, {
  49565. name: "SetStateAction",
  49566. properties: [
  49567. BABYLON.Action._GetTargetProperty(this._target),
  49568. { name: "value", value: this.value }
  49569. ]
  49570. }, parent);
  49571. };
  49572. return SetStateAction;
  49573. }(BABYLON.Action));
  49574. BABYLON.SetStateAction = SetStateAction;
  49575. var SetValueAction = /** @class */ (function (_super) {
  49576. __extends(SetValueAction, _super);
  49577. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49578. var _this = _super.call(this, triggerOptions, condition) || this;
  49579. _this.propertyPath = propertyPath;
  49580. _this.value = value;
  49581. _this._target = _this._effectiveTarget = target;
  49582. return _this;
  49583. }
  49584. SetValueAction.prototype._prepare = function () {
  49585. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49586. this._property = this._getProperty(this.propertyPath);
  49587. };
  49588. SetValueAction.prototype.execute = function () {
  49589. this._effectiveTarget[this._property] = this.value;
  49590. if (this._target.markAsDirty) {
  49591. this._target.markAsDirty(this._property);
  49592. }
  49593. };
  49594. SetValueAction.prototype.serialize = function (parent) {
  49595. return _super.prototype._serialize.call(this, {
  49596. name: "SetValueAction",
  49597. properties: [
  49598. BABYLON.Action._GetTargetProperty(this._target),
  49599. { name: "propertyPath", value: this.propertyPath },
  49600. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49601. ]
  49602. }, parent);
  49603. };
  49604. return SetValueAction;
  49605. }(BABYLON.Action));
  49606. BABYLON.SetValueAction = SetValueAction;
  49607. var IncrementValueAction = /** @class */ (function (_super) {
  49608. __extends(IncrementValueAction, _super);
  49609. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49610. var _this = _super.call(this, triggerOptions, condition) || this;
  49611. _this.propertyPath = propertyPath;
  49612. _this.value = value;
  49613. _this._target = _this._effectiveTarget = target;
  49614. return _this;
  49615. }
  49616. IncrementValueAction.prototype._prepare = function () {
  49617. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49618. this._property = this._getProperty(this.propertyPath);
  49619. if (typeof this._effectiveTarget[this._property] !== "number") {
  49620. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49621. }
  49622. };
  49623. IncrementValueAction.prototype.execute = function () {
  49624. this._effectiveTarget[this._property] += this.value;
  49625. if (this._target.markAsDirty) {
  49626. this._target.markAsDirty(this._property);
  49627. }
  49628. };
  49629. IncrementValueAction.prototype.serialize = function (parent) {
  49630. return _super.prototype._serialize.call(this, {
  49631. name: "IncrementValueAction",
  49632. properties: [
  49633. BABYLON.Action._GetTargetProperty(this._target),
  49634. { name: "propertyPath", value: this.propertyPath },
  49635. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49636. ]
  49637. }, parent);
  49638. };
  49639. return IncrementValueAction;
  49640. }(BABYLON.Action));
  49641. BABYLON.IncrementValueAction = IncrementValueAction;
  49642. var PlayAnimationAction = /** @class */ (function (_super) {
  49643. __extends(PlayAnimationAction, _super);
  49644. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49645. var _this = _super.call(this, triggerOptions, condition) || this;
  49646. _this.from = from;
  49647. _this.to = to;
  49648. _this.loop = loop;
  49649. _this._target = target;
  49650. return _this;
  49651. }
  49652. PlayAnimationAction.prototype._prepare = function () {
  49653. };
  49654. PlayAnimationAction.prototype.execute = function () {
  49655. var scene = this._actionManager.getScene();
  49656. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49657. };
  49658. PlayAnimationAction.prototype.serialize = function (parent) {
  49659. return _super.prototype._serialize.call(this, {
  49660. name: "PlayAnimationAction",
  49661. properties: [
  49662. BABYLON.Action._GetTargetProperty(this._target),
  49663. { name: "from", value: String(this.from) },
  49664. { name: "to", value: String(this.to) },
  49665. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49666. ]
  49667. }, parent);
  49668. };
  49669. return PlayAnimationAction;
  49670. }(BABYLON.Action));
  49671. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49672. var StopAnimationAction = /** @class */ (function (_super) {
  49673. __extends(StopAnimationAction, _super);
  49674. function StopAnimationAction(triggerOptions, target, condition) {
  49675. var _this = _super.call(this, triggerOptions, condition) || this;
  49676. _this._target = target;
  49677. return _this;
  49678. }
  49679. StopAnimationAction.prototype._prepare = function () {
  49680. };
  49681. StopAnimationAction.prototype.execute = function () {
  49682. var scene = this._actionManager.getScene();
  49683. scene.stopAnimation(this._target);
  49684. };
  49685. StopAnimationAction.prototype.serialize = function (parent) {
  49686. return _super.prototype._serialize.call(this, {
  49687. name: "StopAnimationAction",
  49688. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49689. }, parent);
  49690. };
  49691. return StopAnimationAction;
  49692. }(BABYLON.Action));
  49693. BABYLON.StopAnimationAction = StopAnimationAction;
  49694. var DoNothingAction = /** @class */ (function (_super) {
  49695. __extends(DoNothingAction, _super);
  49696. function DoNothingAction(triggerOptions, condition) {
  49697. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49698. return _super.call(this, triggerOptions, condition) || this;
  49699. }
  49700. DoNothingAction.prototype.execute = function () {
  49701. };
  49702. DoNothingAction.prototype.serialize = function (parent) {
  49703. return _super.prototype._serialize.call(this, {
  49704. name: "DoNothingAction",
  49705. properties: []
  49706. }, parent);
  49707. };
  49708. return DoNothingAction;
  49709. }(BABYLON.Action));
  49710. BABYLON.DoNothingAction = DoNothingAction;
  49711. var CombineAction = /** @class */ (function (_super) {
  49712. __extends(CombineAction, _super);
  49713. function CombineAction(triggerOptions, children, condition) {
  49714. var _this = _super.call(this, triggerOptions, condition) || this;
  49715. _this.children = children;
  49716. return _this;
  49717. }
  49718. CombineAction.prototype._prepare = function () {
  49719. for (var index = 0; index < this.children.length; index++) {
  49720. this.children[index]._actionManager = this._actionManager;
  49721. this.children[index]._prepare();
  49722. }
  49723. };
  49724. CombineAction.prototype.execute = function (evt) {
  49725. for (var index = 0; index < this.children.length; index++) {
  49726. this.children[index].execute(evt);
  49727. }
  49728. };
  49729. CombineAction.prototype.serialize = function (parent) {
  49730. var serializationObject = _super.prototype._serialize.call(this, {
  49731. name: "CombineAction",
  49732. properties: [],
  49733. combine: []
  49734. }, parent);
  49735. for (var i = 0; i < this.children.length; i++) {
  49736. serializationObject.combine.push(this.children[i].serialize(null));
  49737. }
  49738. return serializationObject;
  49739. };
  49740. return CombineAction;
  49741. }(BABYLON.Action));
  49742. BABYLON.CombineAction = CombineAction;
  49743. var ExecuteCodeAction = /** @class */ (function (_super) {
  49744. __extends(ExecuteCodeAction, _super);
  49745. function ExecuteCodeAction(triggerOptions, func, condition) {
  49746. var _this = _super.call(this, triggerOptions, condition) || this;
  49747. _this.func = func;
  49748. return _this;
  49749. }
  49750. ExecuteCodeAction.prototype.execute = function (evt) {
  49751. this.func(evt);
  49752. };
  49753. return ExecuteCodeAction;
  49754. }(BABYLON.Action));
  49755. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49756. var SetParentAction = /** @class */ (function (_super) {
  49757. __extends(SetParentAction, _super);
  49758. function SetParentAction(triggerOptions, target, parent, condition) {
  49759. var _this = _super.call(this, triggerOptions, condition) || this;
  49760. _this._target = target;
  49761. _this._parent = parent;
  49762. return _this;
  49763. }
  49764. SetParentAction.prototype._prepare = function () {
  49765. };
  49766. SetParentAction.prototype.execute = function () {
  49767. if (this._target.parent === this._parent) {
  49768. return;
  49769. }
  49770. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49771. invertParentWorldMatrix.invert();
  49772. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49773. this._target.parent = this._parent;
  49774. };
  49775. SetParentAction.prototype.serialize = function (parent) {
  49776. return _super.prototype._serialize.call(this, {
  49777. name: "SetParentAction",
  49778. properties: [
  49779. BABYLON.Action._GetTargetProperty(this._target),
  49780. BABYLON.Action._GetTargetProperty(this._parent),
  49781. ]
  49782. }, parent);
  49783. };
  49784. return SetParentAction;
  49785. }(BABYLON.Action));
  49786. BABYLON.SetParentAction = SetParentAction;
  49787. var PlaySoundAction = /** @class */ (function (_super) {
  49788. __extends(PlaySoundAction, _super);
  49789. function PlaySoundAction(triggerOptions, sound, condition) {
  49790. var _this = _super.call(this, triggerOptions, condition) || this;
  49791. _this._sound = sound;
  49792. return _this;
  49793. }
  49794. PlaySoundAction.prototype._prepare = function () {
  49795. };
  49796. PlaySoundAction.prototype.execute = function () {
  49797. if (this._sound !== undefined)
  49798. this._sound.play();
  49799. };
  49800. PlaySoundAction.prototype.serialize = function (parent) {
  49801. return _super.prototype._serialize.call(this, {
  49802. name: "PlaySoundAction",
  49803. properties: [{ name: "sound", value: this._sound.name }]
  49804. }, parent);
  49805. };
  49806. return PlaySoundAction;
  49807. }(BABYLON.Action));
  49808. BABYLON.PlaySoundAction = PlaySoundAction;
  49809. var StopSoundAction = /** @class */ (function (_super) {
  49810. __extends(StopSoundAction, _super);
  49811. function StopSoundAction(triggerOptions, sound, condition) {
  49812. var _this = _super.call(this, triggerOptions, condition) || this;
  49813. _this._sound = sound;
  49814. return _this;
  49815. }
  49816. StopSoundAction.prototype._prepare = function () {
  49817. };
  49818. StopSoundAction.prototype.execute = function () {
  49819. if (this._sound !== undefined)
  49820. this._sound.stop();
  49821. };
  49822. StopSoundAction.prototype.serialize = function (parent) {
  49823. return _super.prototype._serialize.call(this, {
  49824. name: "StopSoundAction",
  49825. properties: [{ name: "sound", value: this._sound.name }]
  49826. }, parent);
  49827. };
  49828. return StopSoundAction;
  49829. }(BABYLON.Action));
  49830. BABYLON.StopSoundAction = StopSoundAction;
  49831. })(BABYLON || (BABYLON = {}));
  49832. //# sourceMappingURL=babylon.directActions.js.map
  49833. var BABYLON;
  49834. (function (BABYLON) {
  49835. var SpriteManager = /** @class */ (function () {
  49836. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49837. if (epsilon === void 0) { epsilon = 0.01; }
  49838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49839. this.name = name;
  49840. this.sprites = new Array();
  49841. this.renderingGroupId = 0;
  49842. this.layerMask = 0x0FFFFFFF;
  49843. this.fogEnabled = true;
  49844. this.isPickable = false;
  49845. /**
  49846. * An event triggered when the manager is disposed.
  49847. * @type {BABYLON.Observable}
  49848. */
  49849. this.onDisposeObservable = new BABYLON.Observable();
  49850. this._vertexBuffers = {};
  49851. this._capacity = capacity;
  49852. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49853. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49854. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49855. if (cellSize.width && cellSize.height) {
  49856. this.cellWidth = cellSize.width;
  49857. this.cellHeight = cellSize.height;
  49858. }
  49859. else if (cellSize !== undefined) {
  49860. this.cellWidth = cellSize;
  49861. this.cellHeight = cellSize;
  49862. }
  49863. else {
  49864. return;
  49865. }
  49866. this._epsilon = epsilon;
  49867. this._scene = scene;
  49868. this._scene.spriteManagers.push(this);
  49869. var indices = [];
  49870. var index = 0;
  49871. for (var count = 0; count < capacity; count++) {
  49872. indices.push(index);
  49873. indices.push(index + 1);
  49874. indices.push(index + 2);
  49875. indices.push(index);
  49876. indices.push(index + 2);
  49877. indices.push(index + 3);
  49878. index += 4;
  49879. }
  49880. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49881. // VBO
  49882. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49883. this._vertexData = new Float32Array(capacity * 16 * 4);
  49884. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49885. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49886. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49887. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49888. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49889. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49890. this._vertexBuffers["options"] = options;
  49891. this._vertexBuffers["cellInfo"] = cellInfo;
  49892. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49893. // Effects
  49894. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49895. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49896. }
  49897. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49898. set: function (callback) {
  49899. if (this._onDisposeObserver) {
  49900. this.onDisposeObservable.remove(this._onDisposeObserver);
  49901. }
  49902. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49903. },
  49904. enumerable: true,
  49905. configurable: true
  49906. });
  49907. Object.defineProperty(SpriteManager.prototype, "texture", {
  49908. get: function () {
  49909. return this._spriteTexture;
  49910. },
  49911. set: function (value) {
  49912. this._spriteTexture = value;
  49913. },
  49914. enumerable: true,
  49915. configurable: true
  49916. });
  49917. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49918. var arrayOffset = index * 16;
  49919. if (offsetX === 0)
  49920. offsetX = this._epsilon;
  49921. else if (offsetX === 1)
  49922. offsetX = 1 - this._epsilon;
  49923. if (offsetY === 0)
  49924. offsetY = this._epsilon;
  49925. else if (offsetY === 1)
  49926. offsetY = 1 - this._epsilon;
  49927. this._vertexData[arrayOffset] = sprite.position.x;
  49928. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49929. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49930. this._vertexData[arrayOffset + 3] = sprite.angle;
  49931. this._vertexData[arrayOffset + 4] = sprite.width;
  49932. this._vertexData[arrayOffset + 5] = sprite.height;
  49933. this._vertexData[arrayOffset + 6] = offsetX;
  49934. this._vertexData[arrayOffset + 7] = offsetY;
  49935. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49936. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49937. var offset = (sprite.cellIndex / rowSize) >> 0;
  49938. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49939. this._vertexData[arrayOffset + 11] = offset;
  49940. // Color
  49941. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49942. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49943. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49944. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49945. };
  49946. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49947. var count = Math.min(this._capacity, this.sprites.length);
  49948. var min = BABYLON.Vector3.Zero();
  49949. var max = BABYLON.Vector3.Zero();
  49950. var distance = Number.MAX_VALUE;
  49951. var currentSprite = null;
  49952. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49953. var cameraView = camera.getViewMatrix();
  49954. for (var index = 0; index < count; index++) {
  49955. var sprite = this.sprites[index];
  49956. if (!sprite) {
  49957. continue;
  49958. }
  49959. if (predicate) {
  49960. if (!predicate(sprite)) {
  49961. continue;
  49962. }
  49963. }
  49964. else if (!sprite.isPickable) {
  49965. continue;
  49966. }
  49967. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49968. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49969. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49970. if (ray.intersectsBoxMinMax(min, max)) {
  49971. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49972. if (distance > currentDistance) {
  49973. distance = currentDistance;
  49974. currentSprite = sprite;
  49975. if (fastCheck) {
  49976. break;
  49977. }
  49978. }
  49979. }
  49980. }
  49981. if (currentSprite) {
  49982. var result = new BABYLON.PickingInfo();
  49983. result.hit = true;
  49984. result.pickedSprite = currentSprite;
  49985. result.distance = distance;
  49986. return result;
  49987. }
  49988. return null;
  49989. };
  49990. SpriteManager.prototype.render = function () {
  49991. // Check
  49992. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49993. return;
  49994. var engine = this._scene.getEngine();
  49995. var baseSize = this._spriteTexture.getBaseSize();
  49996. // Sprites
  49997. var deltaTime = engine.getDeltaTime();
  49998. var max = Math.min(this._capacity, this.sprites.length);
  49999. var rowSize = baseSize.width / this.cellWidth;
  50000. var offset = 0;
  50001. for (var index = 0; index < max; index++) {
  50002. var sprite = this.sprites[index];
  50003. if (!sprite) {
  50004. continue;
  50005. }
  50006. sprite._animate(deltaTime);
  50007. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50008. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50009. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50010. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50011. }
  50012. this._buffer.update(this._vertexData);
  50013. // Render
  50014. var effect = this._effectBase;
  50015. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50016. effect = this._effectFog;
  50017. }
  50018. engine.enableEffect(effect);
  50019. var viewMatrix = this._scene.getViewMatrix();
  50020. effect.setTexture("diffuseSampler", this._spriteTexture);
  50021. effect.setMatrix("view", viewMatrix);
  50022. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50023. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50024. // Fog
  50025. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50026. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50027. effect.setColor3("vFogColor", this._scene.fogColor);
  50028. }
  50029. // VBOs
  50030. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50031. // Draw order
  50032. engine.setDepthFunctionToLessOrEqual();
  50033. effect.setBool("alphaTest", true);
  50034. engine.setColorWrite(false);
  50035. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50036. engine.setColorWrite(true);
  50037. effect.setBool("alphaTest", false);
  50038. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50039. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50040. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50041. };
  50042. SpriteManager.prototype.dispose = function () {
  50043. if (this._buffer) {
  50044. this._buffer.dispose();
  50045. this._buffer = null;
  50046. }
  50047. if (this._indexBuffer) {
  50048. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50049. this._indexBuffer = null;
  50050. }
  50051. if (this._spriteTexture) {
  50052. this._spriteTexture.dispose();
  50053. this._spriteTexture = null;
  50054. }
  50055. // Remove from scene
  50056. var index = this._scene.spriteManagers.indexOf(this);
  50057. this._scene.spriteManagers.splice(index, 1);
  50058. // Callback
  50059. this.onDisposeObservable.notifyObservers(this);
  50060. this.onDisposeObservable.clear();
  50061. };
  50062. return SpriteManager;
  50063. }());
  50064. BABYLON.SpriteManager = SpriteManager;
  50065. })(BABYLON || (BABYLON = {}));
  50066. //# sourceMappingURL=babylon.spriteManager.js.map
  50067. var BABYLON;
  50068. (function (BABYLON) {
  50069. var Sprite = /** @class */ (function () {
  50070. function Sprite(name, manager) {
  50071. this.name = name;
  50072. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50073. this.width = 1.0;
  50074. this.height = 1.0;
  50075. this.angle = 0;
  50076. this.cellIndex = 0;
  50077. this.invertU = 0;
  50078. this.invertV = 0;
  50079. this.animations = new Array();
  50080. this.isPickable = false;
  50081. this._animationStarted = false;
  50082. this._loopAnimation = false;
  50083. this._fromIndex = 0;
  50084. this._toIndex = 0;
  50085. this._delay = 0;
  50086. this._direction = 1;
  50087. this._time = 0;
  50088. this._manager = manager;
  50089. this._manager.sprites.push(this);
  50090. this.position = BABYLON.Vector3.Zero();
  50091. }
  50092. Object.defineProperty(Sprite.prototype, "size", {
  50093. get: function () {
  50094. return this.width;
  50095. },
  50096. set: function (value) {
  50097. this.width = value;
  50098. this.height = value;
  50099. },
  50100. enumerable: true,
  50101. configurable: true
  50102. });
  50103. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50104. this._fromIndex = from;
  50105. this._toIndex = to;
  50106. this._loopAnimation = loop;
  50107. this._delay = delay;
  50108. this._animationStarted = true;
  50109. this._direction = from < to ? 1 : -1;
  50110. this.cellIndex = from;
  50111. this._time = 0;
  50112. this._onAnimationEnd = onAnimationEnd;
  50113. };
  50114. Sprite.prototype.stopAnimation = function () {
  50115. this._animationStarted = false;
  50116. };
  50117. Sprite.prototype._animate = function (deltaTime) {
  50118. if (!this._animationStarted)
  50119. return;
  50120. this._time += deltaTime;
  50121. if (this._time > this._delay) {
  50122. this._time = this._time % this._delay;
  50123. this.cellIndex += this._direction;
  50124. if (this.cellIndex > this._toIndex) {
  50125. if (this._loopAnimation) {
  50126. this.cellIndex = this._fromIndex;
  50127. }
  50128. else {
  50129. this.cellIndex = this._toIndex;
  50130. this._animationStarted = false;
  50131. if (this._onAnimationEnd) {
  50132. this._onAnimationEnd();
  50133. }
  50134. if (this.disposeWhenFinishedAnimating) {
  50135. this.dispose();
  50136. }
  50137. }
  50138. }
  50139. }
  50140. };
  50141. Sprite.prototype.dispose = function () {
  50142. for (var i = 0; i < this._manager.sprites.length; i++) {
  50143. if (this._manager.sprites[i] == this) {
  50144. this._manager.sprites.splice(i, 1);
  50145. }
  50146. }
  50147. };
  50148. return Sprite;
  50149. }());
  50150. BABYLON.Sprite = Sprite;
  50151. })(BABYLON || (BABYLON = {}));
  50152. //# sourceMappingURL=babylon.sprite.js.map
  50153. var BABYLON;
  50154. (function (BABYLON) {
  50155. var IntersectionInfo = /** @class */ (function () {
  50156. function IntersectionInfo(bu, bv, distance) {
  50157. this.bu = bu;
  50158. this.bv = bv;
  50159. this.distance = distance;
  50160. this.faceId = 0;
  50161. this.subMeshId = 0;
  50162. }
  50163. return IntersectionInfo;
  50164. }());
  50165. BABYLON.IntersectionInfo = IntersectionInfo;
  50166. var PickingInfo = /** @class */ (function () {
  50167. function PickingInfo() {
  50168. this.hit = false;
  50169. this.distance = 0;
  50170. this.pickedPoint = null;
  50171. this.pickedMesh = null;
  50172. this.bu = 0;
  50173. this.bv = 0;
  50174. this.faceId = -1;
  50175. this.subMeshId = 0;
  50176. this.pickedSprite = null;
  50177. }
  50178. // Methods
  50179. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50180. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50181. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50182. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50183. return null;
  50184. }
  50185. var indices = this.pickedMesh.getIndices();
  50186. if (!indices) {
  50187. return null;
  50188. }
  50189. var result;
  50190. if (useVerticesNormals) {
  50191. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50192. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50193. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50194. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50195. normal0 = normal0.scale(this.bu);
  50196. normal1 = normal1.scale(this.bv);
  50197. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50198. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50199. }
  50200. else {
  50201. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50202. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50203. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50204. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50205. var p1p2 = vertex1.subtract(vertex2);
  50206. var p3p2 = vertex3.subtract(vertex2);
  50207. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50208. }
  50209. if (useWorldCoordinates) {
  50210. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50211. }
  50212. return BABYLON.Vector3.Normalize(result);
  50213. };
  50214. PickingInfo.prototype.getTextureCoordinates = function () {
  50215. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50216. return null;
  50217. }
  50218. var indices = this.pickedMesh.getIndices();
  50219. if (!indices) {
  50220. return null;
  50221. }
  50222. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50223. if (!uvs) {
  50224. return null;
  50225. }
  50226. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50227. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50228. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50229. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50230. uv1 = uv1.scale(this.bu);
  50231. uv2 = uv2.scale(this.bv);
  50232. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50233. };
  50234. return PickingInfo;
  50235. }());
  50236. BABYLON.PickingInfo = PickingInfo;
  50237. })(BABYLON || (BABYLON = {}));
  50238. //# sourceMappingURL=babylon.pickingInfo.js.map
  50239. var BABYLON;
  50240. (function (BABYLON) {
  50241. var Ray = /** @class */ (function () {
  50242. function Ray(origin, direction, length) {
  50243. if (length === void 0) { length = Number.MAX_VALUE; }
  50244. this.origin = origin;
  50245. this.direction = direction;
  50246. this.length = length;
  50247. }
  50248. // Methods
  50249. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50250. var d = 0.0;
  50251. var maxValue = Number.MAX_VALUE;
  50252. var inv;
  50253. var min;
  50254. var max;
  50255. var temp;
  50256. if (Math.abs(this.direction.x) < 0.0000001) {
  50257. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50258. return false;
  50259. }
  50260. }
  50261. else {
  50262. inv = 1.0 / this.direction.x;
  50263. min = (minimum.x - this.origin.x) * inv;
  50264. max = (maximum.x - this.origin.x) * inv;
  50265. if (max === -Infinity) {
  50266. max = Infinity;
  50267. }
  50268. if (min > max) {
  50269. temp = min;
  50270. min = max;
  50271. max = temp;
  50272. }
  50273. d = Math.max(min, d);
  50274. maxValue = Math.min(max, maxValue);
  50275. if (d > maxValue) {
  50276. return false;
  50277. }
  50278. }
  50279. if (Math.abs(this.direction.y) < 0.0000001) {
  50280. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50281. return false;
  50282. }
  50283. }
  50284. else {
  50285. inv = 1.0 / this.direction.y;
  50286. min = (minimum.y - this.origin.y) * inv;
  50287. max = (maximum.y - this.origin.y) * inv;
  50288. if (max === -Infinity) {
  50289. max = Infinity;
  50290. }
  50291. if (min > max) {
  50292. temp = min;
  50293. min = max;
  50294. max = temp;
  50295. }
  50296. d = Math.max(min, d);
  50297. maxValue = Math.min(max, maxValue);
  50298. if (d > maxValue) {
  50299. return false;
  50300. }
  50301. }
  50302. if (Math.abs(this.direction.z) < 0.0000001) {
  50303. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50304. return false;
  50305. }
  50306. }
  50307. else {
  50308. inv = 1.0 / this.direction.z;
  50309. min = (minimum.z - this.origin.z) * inv;
  50310. max = (maximum.z - this.origin.z) * inv;
  50311. if (max === -Infinity) {
  50312. max = Infinity;
  50313. }
  50314. if (min > max) {
  50315. temp = min;
  50316. min = max;
  50317. max = temp;
  50318. }
  50319. d = Math.max(min, d);
  50320. maxValue = Math.min(max, maxValue);
  50321. if (d > maxValue) {
  50322. return false;
  50323. }
  50324. }
  50325. return true;
  50326. };
  50327. Ray.prototype.intersectsBox = function (box) {
  50328. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50329. };
  50330. Ray.prototype.intersectsSphere = function (sphere) {
  50331. var x = sphere.center.x - this.origin.x;
  50332. var y = sphere.center.y - this.origin.y;
  50333. var z = sphere.center.z - this.origin.z;
  50334. var pyth = (x * x) + (y * y) + (z * z);
  50335. var rr = sphere.radius * sphere.radius;
  50336. if (pyth <= rr) {
  50337. return true;
  50338. }
  50339. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50340. if (dot < 0.0) {
  50341. return false;
  50342. }
  50343. var temp = pyth - (dot * dot);
  50344. return temp <= rr;
  50345. };
  50346. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50347. if (!this._edge1) {
  50348. this._edge1 = BABYLON.Vector3.Zero();
  50349. this._edge2 = BABYLON.Vector3.Zero();
  50350. this._pvec = BABYLON.Vector3.Zero();
  50351. this._tvec = BABYLON.Vector3.Zero();
  50352. this._qvec = BABYLON.Vector3.Zero();
  50353. }
  50354. vertex1.subtractToRef(vertex0, this._edge1);
  50355. vertex2.subtractToRef(vertex0, this._edge2);
  50356. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50357. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50358. if (det === 0) {
  50359. return null;
  50360. }
  50361. var invdet = 1 / det;
  50362. this.origin.subtractToRef(vertex0, this._tvec);
  50363. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50364. if (bu < 0 || bu > 1.0) {
  50365. return null;
  50366. }
  50367. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50368. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50369. if (bv < 0 || bu + bv > 1.0) {
  50370. return null;
  50371. }
  50372. //check if the distance is longer than the predefined length.
  50373. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50374. if (distance > this.length) {
  50375. return null;
  50376. }
  50377. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50378. };
  50379. Ray.prototype.intersectsPlane = function (plane) {
  50380. var distance;
  50381. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50382. if (Math.abs(result1) < 9.99999997475243E-07) {
  50383. return null;
  50384. }
  50385. else {
  50386. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50387. distance = (-plane.d - result2) / result1;
  50388. if (distance < 0.0) {
  50389. if (distance < -9.99999997475243E-07) {
  50390. return null;
  50391. }
  50392. else {
  50393. return 0;
  50394. }
  50395. }
  50396. return distance;
  50397. }
  50398. };
  50399. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50400. var tm = BABYLON.Tmp.Matrix[0];
  50401. mesh.getWorldMatrix().invertToRef(tm);
  50402. if (this._tmpRay) {
  50403. Ray.TransformToRef(this, tm, this._tmpRay);
  50404. }
  50405. else {
  50406. this._tmpRay = Ray.Transform(this, tm);
  50407. }
  50408. return mesh.intersects(this._tmpRay, fastCheck);
  50409. };
  50410. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50411. if (results) {
  50412. results.length = 0;
  50413. }
  50414. else {
  50415. results = [];
  50416. }
  50417. for (var i = 0; i < meshes.length; i++) {
  50418. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50419. if (pickInfo.hit) {
  50420. results.push(pickInfo);
  50421. }
  50422. }
  50423. results.sort(this._comparePickingInfo);
  50424. return results;
  50425. };
  50426. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50427. if (pickingInfoA.distance < pickingInfoB.distance) {
  50428. return -1;
  50429. }
  50430. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50431. return 1;
  50432. }
  50433. else {
  50434. return 0;
  50435. }
  50436. };
  50437. /**
  50438. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50439. * @param sega the first point of the segment to test the intersection against
  50440. * @param segb the second point of the segment to test the intersection against
  50441. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50442. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50443. */
  50444. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50445. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50446. var u = segb.subtract(sega);
  50447. var v = rsegb.subtract(this.origin);
  50448. var w = sega.subtract(this.origin);
  50449. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50450. var b = BABYLON.Vector3.Dot(u, v);
  50451. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50452. var d = BABYLON.Vector3.Dot(u, w);
  50453. var e = BABYLON.Vector3.Dot(v, w);
  50454. var D = a * c - b * b; // always >= 0
  50455. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50456. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50457. // compute the line parameters of the two closest points
  50458. if (D < Ray.smallnum) {
  50459. sN = 0.0; // force using point P0 on segment S1
  50460. sD = 1.0; // to prevent possible division by 0.0 later
  50461. tN = e;
  50462. tD = c;
  50463. }
  50464. else {
  50465. sN = (b * e - c * d);
  50466. tN = (a * e - b * d);
  50467. if (sN < 0.0) {
  50468. sN = 0.0;
  50469. tN = e;
  50470. tD = c;
  50471. }
  50472. else if (sN > sD) {
  50473. sN = sD;
  50474. tN = e + b;
  50475. tD = c;
  50476. }
  50477. }
  50478. if (tN < 0.0) {
  50479. tN = 0.0;
  50480. // recompute sc for this edge
  50481. if (-d < 0.0) {
  50482. sN = 0.0;
  50483. }
  50484. else if (-d > a)
  50485. sN = sD;
  50486. else {
  50487. sN = -d;
  50488. sD = a;
  50489. }
  50490. }
  50491. else if (tN > tD) {
  50492. tN = tD;
  50493. // recompute sc for this edge
  50494. if ((-d + b) < 0.0) {
  50495. sN = 0;
  50496. }
  50497. else if ((-d + b) > a) {
  50498. sN = sD;
  50499. }
  50500. else {
  50501. sN = (-d + b);
  50502. sD = a;
  50503. }
  50504. }
  50505. // finally do the division to get sc and tc
  50506. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50507. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50508. // get the difference of the two closest points
  50509. var qtc = v.multiplyByFloats(tc, tc, tc);
  50510. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50511. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50512. if (isIntersected) {
  50513. return qtc.length();
  50514. }
  50515. return -1;
  50516. };
  50517. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50518. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50519. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50520. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50521. this.direction.normalize();
  50522. return this;
  50523. };
  50524. // Statics
  50525. Ray.Zero = function () {
  50526. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50527. };
  50528. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50529. var result = Ray.Zero();
  50530. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50531. };
  50532. /**
  50533. * 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
  50534. * transformed to the given world matrix.
  50535. * @param origin The origin point
  50536. * @param end The end point
  50537. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50538. */
  50539. Ray.CreateNewFromTo = function (origin, end, world) {
  50540. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50541. var direction = end.subtract(origin);
  50542. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50543. direction.normalize();
  50544. return Ray.Transform(new Ray(origin, direction, length), world);
  50545. };
  50546. Ray.Transform = function (ray, matrix) {
  50547. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50548. Ray.TransformToRef(ray, matrix, result);
  50549. return result;
  50550. };
  50551. Ray.TransformToRef = function (ray, matrix, result) {
  50552. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50553. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50554. result.length = ray.length;
  50555. var dir = result.direction;
  50556. var len = dir.length();
  50557. if (!(len === 0 || len === 1)) {
  50558. var num = 1.0 / len;
  50559. dir.x *= num;
  50560. dir.y *= num;
  50561. dir.z *= num;
  50562. result.length *= len;
  50563. }
  50564. };
  50565. Ray.smallnum = 0.00000001;
  50566. Ray.rayl = 10e8;
  50567. return Ray;
  50568. }());
  50569. BABYLON.Ray = Ray;
  50570. })(BABYLON || (BABYLON = {}));
  50571. //# sourceMappingURL=babylon.ray.js.map
  50572. var BABYLON;
  50573. (function (BABYLON) {
  50574. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50575. if (boxMin.x > sphereCenter.x + sphereRadius)
  50576. return false;
  50577. if (sphereCenter.x - sphereRadius > boxMax.x)
  50578. return false;
  50579. if (boxMin.y > sphereCenter.y + sphereRadius)
  50580. return false;
  50581. if (sphereCenter.y - sphereRadius > boxMax.y)
  50582. return false;
  50583. if (boxMin.z > sphereCenter.z + sphereRadius)
  50584. return false;
  50585. if (sphereCenter.z - sphereRadius > boxMax.z)
  50586. return false;
  50587. return true;
  50588. };
  50589. var getLowestRoot = (function () {
  50590. var result = { root: 0, found: false };
  50591. return function (a, b, c, maxR) {
  50592. result.root = 0;
  50593. result.found = false;
  50594. var determinant = b * b - 4.0 * a * c;
  50595. if (determinant < 0)
  50596. return result;
  50597. var sqrtD = Math.sqrt(determinant);
  50598. var r1 = (-b - sqrtD) / (2.0 * a);
  50599. var r2 = (-b + sqrtD) / (2.0 * a);
  50600. if (r1 > r2) {
  50601. var temp = r2;
  50602. r2 = r1;
  50603. r1 = temp;
  50604. }
  50605. if (r1 > 0 && r1 < maxR) {
  50606. result.root = r1;
  50607. result.found = true;
  50608. return result;
  50609. }
  50610. if (r2 > 0 && r2 < maxR) {
  50611. result.root = r2;
  50612. result.found = true;
  50613. return result;
  50614. }
  50615. return result;
  50616. };
  50617. })();
  50618. var Collider = /** @class */ (function () {
  50619. function Collider() {
  50620. this._collisionPoint = BABYLON.Vector3.Zero();
  50621. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50622. this._tempVector = BABYLON.Vector3.Zero();
  50623. this._tempVector2 = BABYLON.Vector3.Zero();
  50624. this._tempVector3 = BABYLON.Vector3.Zero();
  50625. this._tempVector4 = BABYLON.Vector3.Zero();
  50626. this._edge = BABYLON.Vector3.Zero();
  50627. this._baseToVertex = BABYLON.Vector3.Zero();
  50628. this._destinationPoint = BABYLON.Vector3.Zero();
  50629. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50630. this._displacementVector = BABYLON.Vector3.Zero();
  50631. this._radius = BABYLON.Vector3.One();
  50632. this._retry = 0;
  50633. this._basePointWorld = BABYLON.Vector3.Zero();
  50634. this._velocityWorld = BABYLON.Vector3.Zero();
  50635. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50636. this._collisionMask = -1;
  50637. }
  50638. Object.defineProperty(Collider.prototype, "collisionMask", {
  50639. get: function () {
  50640. return this._collisionMask;
  50641. },
  50642. set: function (mask) {
  50643. this._collisionMask = !isNaN(mask) ? mask : -1;
  50644. },
  50645. enumerable: true,
  50646. configurable: true
  50647. });
  50648. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50649. /**
  50650. * Gets the plane normal used to compute the sliding response (in local space)
  50651. */
  50652. get: function () {
  50653. return this._slidePlaneNormal;
  50654. },
  50655. enumerable: true,
  50656. configurable: true
  50657. });
  50658. // Methods
  50659. Collider.prototype._initialize = function (source, dir, e) {
  50660. this._velocity = dir;
  50661. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50662. this._basePoint = source;
  50663. source.multiplyToRef(this._radius, this._basePointWorld);
  50664. dir.multiplyToRef(this._radius, this._velocityWorld);
  50665. this._velocityWorldLength = this._velocityWorld.length();
  50666. this._epsilon = e;
  50667. this.collisionFound = false;
  50668. };
  50669. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50670. pa.subtractToRef(point, this._tempVector);
  50671. pb.subtractToRef(point, this._tempVector2);
  50672. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50673. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50674. if (d < 0)
  50675. return false;
  50676. pc.subtractToRef(point, this._tempVector3);
  50677. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50678. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50679. if (d < 0)
  50680. return false;
  50681. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50682. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50683. return d >= 0;
  50684. };
  50685. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50686. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50687. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50688. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50689. return false;
  50690. }
  50691. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50692. return false;
  50693. return true;
  50694. };
  50695. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50696. var t0;
  50697. var embeddedInPlane = false;
  50698. //defensive programming, actually not needed.
  50699. if (!trianglePlaneArray) {
  50700. trianglePlaneArray = [];
  50701. }
  50702. if (!trianglePlaneArray[faceIndex]) {
  50703. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50704. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50705. }
  50706. var trianglePlane = trianglePlaneArray[faceIndex];
  50707. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50708. return;
  50709. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50710. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50711. if (normalDotVelocity == 0) {
  50712. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50713. return;
  50714. embeddedInPlane = true;
  50715. t0 = 0;
  50716. }
  50717. else {
  50718. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50719. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50720. if (t0 > t1) {
  50721. var temp = t1;
  50722. t1 = t0;
  50723. t0 = temp;
  50724. }
  50725. if (t0 > 1.0 || t1 < 0.0)
  50726. return;
  50727. if (t0 < 0)
  50728. t0 = 0;
  50729. if (t0 > 1.0)
  50730. t0 = 1.0;
  50731. }
  50732. this._collisionPoint.copyFromFloats(0, 0, 0);
  50733. var found = false;
  50734. var t = 1.0;
  50735. if (!embeddedInPlane) {
  50736. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50737. this._velocity.scaleToRef(t0, this._tempVector);
  50738. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50739. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50740. found = true;
  50741. t = t0;
  50742. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50743. }
  50744. }
  50745. if (!found) {
  50746. var velocitySquaredLength = this._velocity.lengthSquared();
  50747. var a = velocitySquaredLength;
  50748. this._basePoint.subtractToRef(p1, this._tempVector);
  50749. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50750. var c = this._tempVector.lengthSquared() - 1.0;
  50751. var lowestRoot = getLowestRoot(a, b, c, t);
  50752. if (lowestRoot.found) {
  50753. t = lowestRoot.root;
  50754. found = true;
  50755. this._collisionPoint.copyFrom(p1);
  50756. }
  50757. this._basePoint.subtractToRef(p2, this._tempVector);
  50758. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50759. c = this._tempVector.lengthSquared() - 1.0;
  50760. lowestRoot = getLowestRoot(a, b, c, t);
  50761. if (lowestRoot.found) {
  50762. t = lowestRoot.root;
  50763. found = true;
  50764. this._collisionPoint.copyFrom(p2);
  50765. }
  50766. this._basePoint.subtractToRef(p3, this._tempVector);
  50767. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50768. c = this._tempVector.lengthSquared() - 1.0;
  50769. lowestRoot = getLowestRoot(a, b, c, t);
  50770. if (lowestRoot.found) {
  50771. t = lowestRoot.root;
  50772. found = true;
  50773. this._collisionPoint.copyFrom(p3);
  50774. }
  50775. p2.subtractToRef(p1, this._edge);
  50776. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50777. var edgeSquaredLength = this._edge.lengthSquared();
  50778. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50779. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50780. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50781. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50782. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50783. lowestRoot = getLowestRoot(a, b, c, t);
  50784. if (lowestRoot.found) {
  50785. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50786. if (f >= 0.0 && f <= 1.0) {
  50787. t = lowestRoot.root;
  50788. found = true;
  50789. this._edge.scaleInPlace(f);
  50790. p1.addToRef(this._edge, this._collisionPoint);
  50791. }
  50792. }
  50793. p3.subtractToRef(p2, this._edge);
  50794. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50795. edgeSquaredLength = this._edge.lengthSquared();
  50796. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50797. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50798. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50799. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50800. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50801. lowestRoot = getLowestRoot(a, b, c, t);
  50802. if (lowestRoot.found) {
  50803. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50804. if (f >= 0.0 && f <= 1.0) {
  50805. t = lowestRoot.root;
  50806. found = true;
  50807. this._edge.scaleInPlace(f);
  50808. p2.addToRef(this._edge, this._collisionPoint);
  50809. }
  50810. }
  50811. p1.subtractToRef(p3, this._edge);
  50812. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50813. edgeSquaredLength = this._edge.lengthSquared();
  50814. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50815. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50816. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50817. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50818. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50819. lowestRoot = getLowestRoot(a, b, c, t);
  50820. if (lowestRoot.found) {
  50821. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50822. if (f >= 0.0 && f <= 1.0) {
  50823. t = lowestRoot.root;
  50824. found = true;
  50825. this._edge.scaleInPlace(f);
  50826. p3.addToRef(this._edge, this._collisionPoint);
  50827. }
  50828. }
  50829. }
  50830. if (found) {
  50831. var distToCollision = t * this._velocity.length();
  50832. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50833. if (!this.intersectionPoint) {
  50834. this.intersectionPoint = this._collisionPoint.clone();
  50835. }
  50836. else {
  50837. this.intersectionPoint.copyFrom(this._collisionPoint);
  50838. }
  50839. this._nearestDistance = distToCollision;
  50840. this.collisionFound = true;
  50841. }
  50842. }
  50843. };
  50844. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50845. for (var i = indexStart; i < indexEnd; i += 3) {
  50846. var p1 = pts[indices[i] - decal];
  50847. var p2 = pts[indices[i + 1] - decal];
  50848. var p3 = pts[indices[i + 2] - decal];
  50849. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50850. }
  50851. };
  50852. Collider.prototype._getResponse = function (pos, vel) {
  50853. pos.addToRef(vel, this._destinationPoint);
  50854. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50855. this._basePoint.addToRef(vel, pos);
  50856. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50857. this._slidePlaneNormal.normalize();
  50858. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50859. pos.addInPlace(this._displacementVector);
  50860. this.intersectionPoint.addInPlace(this._displacementVector);
  50861. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50862. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50863. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50864. };
  50865. return Collider;
  50866. }());
  50867. BABYLON.Collider = Collider;
  50868. })(BABYLON || (BABYLON = {}));
  50869. //# sourceMappingURL=babylon.collider.js.map
  50870. var BABYLON;
  50871. (function (BABYLON) {
  50872. //WebWorker code will be inserted to this variable.
  50873. BABYLON.CollisionWorker = "";
  50874. var WorkerTaskType;
  50875. (function (WorkerTaskType) {
  50876. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50877. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50878. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50879. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50880. var WorkerReplyType;
  50881. (function (WorkerReplyType) {
  50882. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50883. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50884. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50885. var CollisionCoordinatorWorker = /** @class */ (function () {
  50886. function CollisionCoordinatorWorker() {
  50887. var _this = this;
  50888. this._scaledPosition = BABYLON.Vector3.Zero();
  50889. this._scaledVelocity = BABYLON.Vector3.Zero();
  50890. this.onMeshUpdated = function (transformNode) {
  50891. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50892. };
  50893. this.onGeometryUpdated = function (geometry) {
  50894. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50895. };
  50896. this._afterRender = function () {
  50897. if (!_this._init)
  50898. return;
  50899. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50900. return;
  50901. }
  50902. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50903. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50904. if (_this._runningUpdated > 4) {
  50905. return;
  50906. }
  50907. ++_this._runningUpdated;
  50908. var payload = {
  50909. updatedMeshes: _this._addUpdateMeshesList,
  50910. updatedGeometries: _this._addUpdateGeometriesList,
  50911. removedGeometries: _this._toRemoveGeometryArray,
  50912. removedMeshes: _this._toRemoveMeshesArray
  50913. };
  50914. var message = {
  50915. payload: payload,
  50916. taskType: WorkerTaskType.UPDATE
  50917. };
  50918. var serializable = [];
  50919. for (var id in payload.updatedGeometries) {
  50920. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50921. //prepare transferables
  50922. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50923. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50924. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50925. }
  50926. }
  50927. _this._worker.postMessage(message, serializable);
  50928. _this._addUpdateMeshesList = {};
  50929. _this._addUpdateGeometriesList = {};
  50930. _this._toRemoveGeometryArray = [];
  50931. _this._toRemoveMeshesArray = [];
  50932. };
  50933. this._onMessageFromWorker = function (e) {
  50934. var returnData = e.data;
  50935. if (returnData.error != WorkerReplyType.SUCCESS) {
  50936. //TODO what errors can be returned from the worker?
  50937. BABYLON.Tools.Warn("error returned from worker!");
  50938. return;
  50939. }
  50940. switch (returnData.taskType) {
  50941. case WorkerTaskType.INIT:
  50942. _this._init = true;
  50943. //Update the worked with ALL of the scene's current state
  50944. _this._scene.meshes.forEach(function (mesh) {
  50945. _this.onMeshAdded(mesh);
  50946. });
  50947. _this._scene.getGeometries().forEach(function (geometry) {
  50948. _this.onGeometryAdded(geometry);
  50949. });
  50950. break;
  50951. case WorkerTaskType.UPDATE:
  50952. _this._runningUpdated--;
  50953. break;
  50954. case WorkerTaskType.COLLIDE:
  50955. var returnPayload = returnData.payload;
  50956. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50957. return;
  50958. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50959. if (callback) {
  50960. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50961. if (mesh) {
  50962. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50963. }
  50964. }
  50965. //cleanup
  50966. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50967. break;
  50968. }
  50969. };
  50970. this._collisionsCallbackArray = [];
  50971. this._init = false;
  50972. this._runningUpdated = 0;
  50973. this._addUpdateMeshesList = {};
  50974. this._addUpdateGeometriesList = {};
  50975. this._toRemoveGeometryArray = [];
  50976. this._toRemoveMeshesArray = [];
  50977. }
  50978. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50979. if (!this._init)
  50980. return;
  50981. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50982. return;
  50983. position.divideToRef(collider._radius, this._scaledPosition);
  50984. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50985. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50986. var payload = {
  50987. collider: {
  50988. position: this._scaledPosition.asArray(),
  50989. velocity: this._scaledVelocity.asArray(),
  50990. radius: collider._radius.asArray()
  50991. },
  50992. collisionId: collisionIndex,
  50993. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50994. maximumRetry: maximumRetry
  50995. };
  50996. var message = {
  50997. payload: payload,
  50998. taskType: WorkerTaskType.COLLIDE
  50999. };
  51000. this._worker.postMessage(message);
  51001. };
  51002. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51003. this._scene = scene;
  51004. this._scene.registerAfterRender(this._afterRender);
  51005. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51006. this._worker = new Worker(workerUrl);
  51007. this._worker.onmessage = this._onMessageFromWorker;
  51008. var message = {
  51009. payload: {},
  51010. taskType: WorkerTaskType.INIT
  51011. };
  51012. this._worker.postMessage(message);
  51013. };
  51014. CollisionCoordinatorWorker.prototype.destroy = function () {
  51015. this._scene.unregisterAfterRender(this._afterRender);
  51016. this._worker.terminate();
  51017. };
  51018. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51019. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51020. this.onMeshUpdated(mesh);
  51021. };
  51022. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51023. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51024. };
  51025. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51026. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51027. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51028. this.onGeometryUpdated(geometry);
  51029. };
  51030. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51031. this._toRemoveGeometryArray.push(geometry.id);
  51032. };
  51033. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51034. var submeshes = [];
  51035. if (mesh.subMeshes) {
  51036. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51037. var boundingInfo = sm.getBoundingInfo();
  51038. return {
  51039. position: idx,
  51040. verticesStart: sm.verticesStart,
  51041. verticesCount: sm.verticesCount,
  51042. indexStart: sm.indexStart,
  51043. indexCount: sm.indexCount,
  51044. hasMaterial: !!sm.getMaterial(),
  51045. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51046. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51047. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51048. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51049. };
  51050. });
  51051. }
  51052. var geometryId = null;
  51053. if (mesh instanceof BABYLON.Mesh) {
  51054. var geometry = mesh.geometry;
  51055. geometryId = geometry ? geometry.id : null;
  51056. }
  51057. else if (mesh instanceof BABYLON.InstancedMesh) {
  51058. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51059. geometryId = geometry ? geometry.id : null;
  51060. }
  51061. var boundingInfo = mesh.getBoundingInfo();
  51062. return {
  51063. uniqueId: mesh.uniqueId,
  51064. id: mesh.id,
  51065. name: mesh.name,
  51066. geometryId: geometryId,
  51067. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51068. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51069. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51070. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51071. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51072. subMeshes: submeshes,
  51073. checkCollisions: mesh.checkCollisions
  51074. };
  51075. };
  51076. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51077. return {
  51078. id: geometry.id,
  51079. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51080. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51081. indices: new Uint32Array(geometry.getIndices() || []),
  51082. };
  51083. };
  51084. return CollisionCoordinatorWorker;
  51085. }());
  51086. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51087. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51088. function CollisionCoordinatorLegacy() {
  51089. this._scaledPosition = BABYLON.Vector3.Zero();
  51090. this._scaledVelocity = BABYLON.Vector3.Zero();
  51091. this._finalPosition = BABYLON.Vector3.Zero();
  51092. }
  51093. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51094. position.divideToRef(collider._radius, this._scaledPosition);
  51095. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51096. collider.collidedMesh = null;
  51097. collider._retry = 0;
  51098. collider._initialVelocity = this._scaledVelocity;
  51099. collider._initialPosition = this._scaledPosition;
  51100. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51101. this._finalPosition.multiplyInPlace(collider._radius);
  51102. //run the callback
  51103. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51104. };
  51105. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51106. this._scene = scene;
  51107. };
  51108. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51109. //Legacy need no destruction method.
  51110. };
  51111. //No update in legacy mode
  51112. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51113. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51114. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51115. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51116. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51117. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51118. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51119. if (excludedMesh === void 0) { excludedMesh = null; }
  51120. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51121. if (collider._retry >= maximumRetry) {
  51122. finalPosition.copyFrom(position);
  51123. return;
  51124. }
  51125. // Check if this is a mesh else camera or -1
  51126. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51127. collider._initialize(position, velocity, closeDistance);
  51128. // Check all meshes
  51129. for (var index = 0; index < this._scene.meshes.length; index++) {
  51130. var mesh = this._scene.meshes[index];
  51131. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51132. mesh._checkCollision(collider);
  51133. }
  51134. }
  51135. if (!collider.collisionFound) {
  51136. position.addToRef(velocity, finalPosition);
  51137. return;
  51138. }
  51139. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51140. collider._getResponse(position, velocity);
  51141. }
  51142. if (velocity.length() <= closeDistance) {
  51143. finalPosition.copyFrom(position);
  51144. return;
  51145. }
  51146. collider._retry++;
  51147. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51148. };
  51149. return CollisionCoordinatorLegacy;
  51150. }());
  51151. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51152. })(BABYLON || (BABYLON = {}));
  51153. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51154. var BABYLON;
  51155. (function (BABYLON) {
  51156. /**
  51157. * A particle represents one of the element emitted by a particle system.
  51158. * This is mainly define by its coordinates, direction, velocity and age.
  51159. */
  51160. var Particle = /** @class */ (function () {
  51161. /**
  51162. * Creates a new instance of @see Particle
  51163. * @param particleSystem the particle system the particle belongs to
  51164. */
  51165. function Particle(
  51166. /**
  51167. * particleSystem the particle system the particle belongs to.
  51168. */
  51169. particleSystem) {
  51170. this.particleSystem = particleSystem;
  51171. /**
  51172. * The world position of the particle in the scene.
  51173. */
  51174. this.position = BABYLON.Vector3.Zero();
  51175. /**
  51176. * The world direction of the particle in the scene.
  51177. */
  51178. this.direction = BABYLON.Vector3.Zero();
  51179. /**
  51180. * The color of the particle.
  51181. */
  51182. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51183. /**
  51184. * The color change of the particle per step.
  51185. */
  51186. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51187. /**
  51188. * Defines how long will the life of the particle be.
  51189. */
  51190. this.lifeTime = 1.0;
  51191. /**
  51192. * The current age of the particle.
  51193. */
  51194. this.age = 0;
  51195. /**
  51196. * The current size of the particle.
  51197. */
  51198. this.size = 0;
  51199. /**
  51200. * The current angle of the particle.
  51201. */
  51202. this.angle = 0;
  51203. /**
  51204. * Defines how fast is the angle changing.
  51205. */
  51206. this.angularSpeed = 0;
  51207. /**
  51208. * Defines the cell index used by the particle to be rendered from a sprite.
  51209. */
  51210. this.cellIndex = 0;
  51211. this._currentFrameCounter = 0;
  51212. if (!this.particleSystem.isAnimationSheetEnabled) {
  51213. return;
  51214. }
  51215. this.updateCellInfoFromSystem();
  51216. }
  51217. Particle.prototype.updateCellInfoFromSystem = function () {
  51218. this.cellIndex = this.particleSystem.startSpriteCellID;
  51219. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51220. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51221. }
  51222. else {
  51223. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51224. }
  51225. };
  51226. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51227. // (ageOffset / scaledUpdateSpeed) / available cells
  51228. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51229. this._currentFrameCounter += scaledUpdateSpeed;
  51230. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51231. this._currentFrameCounter = 0;
  51232. this.cellIndex++;
  51233. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51234. this.cellIndex = this.particleSystem.endSpriteCellID;
  51235. }
  51236. }
  51237. };
  51238. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51239. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51240. this.cellIndex++;
  51241. this._currentFrameCounter = 0;
  51242. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51243. if (this.particleSystem.spriteCellLoop) {
  51244. this.cellIndex = this.particleSystem.startSpriteCellID;
  51245. }
  51246. else {
  51247. this.cellIndex = this.particleSystem.endSpriteCellID;
  51248. }
  51249. }
  51250. }
  51251. else {
  51252. this._currentFrameCounter++;
  51253. }
  51254. };
  51255. /**
  51256. * Copy the properties of particle to another one.
  51257. * @param other the particle to copy the information to.
  51258. */
  51259. Particle.prototype.copyTo = function (other) {
  51260. other.position.copyFrom(this.position);
  51261. other.direction.copyFrom(this.direction);
  51262. other.color.copyFrom(this.color);
  51263. other.colorStep.copyFrom(this.colorStep);
  51264. other.lifeTime = this.lifeTime;
  51265. other.age = this.age;
  51266. other.size = this.size;
  51267. other.angle = this.angle;
  51268. other.angularSpeed = this.angularSpeed;
  51269. other.particleSystem = this.particleSystem;
  51270. other.cellIndex = this.cellIndex;
  51271. };
  51272. return Particle;
  51273. }());
  51274. BABYLON.Particle = Particle;
  51275. })(BABYLON || (BABYLON = {}));
  51276. //# sourceMappingURL=babylon.particle.js.map
  51277. var BABYLON;
  51278. (function (BABYLON) {
  51279. /**
  51280. * This represents a particle system in Babylon.
  51281. * 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.
  51282. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51283. * @example https://doc.babylonjs.com/babylon101/particles
  51284. */
  51285. var ParticleSystem = /** @class */ (function () {
  51286. /**
  51287. * Instantiates a particle system.
  51288. * 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.
  51289. * @param name The name of the particle system
  51290. * @param capacity The max number of particles alive at the same time
  51291. * @param scene The scene the particle system belongs to
  51292. * @param customEffect a custom effect used to change the way particles are rendered by default
  51293. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51294. * @param epsilon Offset used to render the particles
  51295. */
  51296. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51297. if (customEffect === void 0) { customEffect = null; }
  51298. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51299. if (epsilon === void 0) { epsilon = 0.01; }
  51300. var _this = this;
  51301. /**
  51302. * List of animations used by the particle system.
  51303. */
  51304. this.animations = [];
  51305. /**
  51306. * The rendering group used by the Particle system to chose when to render.
  51307. */
  51308. this.renderingGroupId = 0;
  51309. /**
  51310. * The emitter represents the Mesh or position we are attaching the particle system to.
  51311. */
  51312. this.emitter = null;
  51313. /**
  51314. * The maximum number of particles to emit per frame
  51315. */
  51316. this.emitRate = 10;
  51317. /**
  51318. * If you want to launch only a few particles at once, that can be done, as well.
  51319. */
  51320. this.manualEmitCount = -1;
  51321. /**
  51322. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51323. */
  51324. this.updateSpeed = 0.01;
  51325. /**
  51326. * The amount of time the particle system is running (depends of the overall update speed).
  51327. */
  51328. this.targetStopDuration = 0;
  51329. /**
  51330. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51331. */
  51332. this.disposeOnStop = false;
  51333. /**
  51334. * Minimum power of emitting particles.
  51335. */
  51336. this.minEmitPower = 1;
  51337. /**
  51338. * Maximum power of emitting particles.
  51339. */
  51340. this.maxEmitPower = 1;
  51341. /**
  51342. * Minimum life time of emitting particles.
  51343. */
  51344. this.minLifeTime = 1;
  51345. /**
  51346. * Maximum life time of emitting particles.
  51347. */
  51348. this.maxLifeTime = 1;
  51349. /**
  51350. * Minimum Size of emitting particles.
  51351. */
  51352. this.minSize = 1;
  51353. /**
  51354. * Maximum Size of emitting particles.
  51355. */
  51356. this.maxSize = 1;
  51357. /**
  51358. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51359. */
  51360. this.minAngularSpeed = 0;
  51361. /**
  51362. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51363. */
  51364. this.maxAngularSpeed = 0;
  51365. /**
  51366. * The layer mask we are rendering the particles through.
  51367. */
  51368. this.layerMask = 0x0FFFFFFF;
  51369. /**
  51370. * This can help using your own shader to render the particle system.
  51371. * The according effect will be created
  51372. */
  51373. this.customShader = null;
  51374. /**
  51375. * By default particle system starts as soon as they are created. This prevents the
  51376. * automatic start to happen and let you decide when to start emitting particles.
  51377. */
  51378. this.preventAutoStart = false;
  51379. /**
  51380. * Callback triggered when the particle animation is ending.
  51381. */
  51382. this.onAnimationEnd = null;
  51383. /**
  51384. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51385. */
  51386. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51387. /**
  51388. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51389. * to override the particles.
  51390. */
  51391. this.forceDepthWrite = false;
  51392. /**
  51393. * You can use gravity if you want to give an orientation to your particles.
  51394. */
  51395. this.gravity = BABYLON.Vector3.Zero();
  51396. /**
  51397. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51398. */
  51399. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51400. /**
  51401. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51402. */
  51403. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51404. /**
  51405. * Color the particle will have at the end of its lifetime.
  51406. */
  51407. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51408. /**
  51409. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51410. */
  51411. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51412. /**
  51413. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51414. */
  51415. this.spriteCellLoop = true;
  51416. /**
  51417. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51418. */
  51419. this.spriteCellChangeSpeed = 0;
  51420. /**
  51421. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51422. */
  51423. this.startSpriteCellID = 0;
  51424. /**
  51425. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51426. */
  51427. this.endSpriteCellID = 0;
  51428. /**
  51429. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51430. */
  51431. this.spriteCellWidth = 0;
  51432. /**
  51433. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51434. */
  51435. this.spriteCellHeight = 0;
  51436. /**
  51437. * An event triggered when the system is disposed.
  51438. */
  51439. this.onDisposeObservable = new BABYLON.Observable();
  51440. this._particles = new Array();
  51441. this._stockParticles = new Array();
  51442. this._newPartsExcess = 0;
  51443. this._vertexBuffers = {};
  51444. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51445. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51446. this._scaledDirection = BABYLON.Vector3.Zero();
  51447. this._scaledGravity = BABYLON.Vector3.Zero();
  51448. this._currentRenderId = -1;
  51449. this._started = false;
  51450. this._stopped = false;
  51451. this._actualFrame = 0;
  51452. this._vertexBufferSize = 11;
  51453. // start of sub system methods
  51454. /**
  51455. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51456. * Its lifetime will start back at 0.
  51457. */
  51458. this.recycleParticle = function (particle) {
  51459. var lastParticle = _this._particles.pop();
  51460. if (lastParticle !== particle) {
  51461. lastParticle.copyTo(particle);
  51462. }
  51463. _this._stockParticles.push(lastParticle);
  51464. };
  51465. this._createParticle = function () {
  51466. var particle;
  51467. if (_this._stockParticles.length !== 0) {
  51468. particle = _this._stockParticles.pop();
  51469. particle.age = 0;
  51470. particle.cellIndex = _this.startSpriteCellID;
  51471. }
  51472. else {
  51473. particle = new BABYLON.Particle(_this);
  51474. }
  51475. return particle;
  51476. };
  51477. this._emitFromParticle = function (particle) {
  51478. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51479. return;
  51480. }
  51481. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51482. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51483. subSystem._rootParticleSystem = _this;
  51484. _this.activeSubSystems.push(subSystem);
  51485. subSystem.start();
  51486. };
  51487. this._appendParticleVertexes = null;
  51488. this.id = name;
  51489. this.name = name;
  51490. this._capacity = capacity;
  51491. this._epsilon = epsilon;
  51492. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51493. if (isAnimationSheetEnabled) {
  51494. this._vertexBufferSize = 12;
  51495. }
  51496. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51497. this._customEffect = customEffect;
  51498. scene.particleSystems.push(this);
  51499. this._createIndexBuffer();
  51500. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51501. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51502. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51503. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51504. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51505. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51506. if (this._isAnimationSheetEnabled) {
  51507. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51508. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51509. }
  51510. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51511. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51512. this._vertexBuffers["options"] = options;
  51513. // Default emitter type
  51514. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51515. this.updateFunction = function (particles) {
  51516. for (var index = 0; index < particles.length; index++) {
  51517. var particle = particles[index];
  51518. particle.age += _this._scaledUpdateSpeed;
  51519. if (particle.age >= particle.lifeTime) {
  51520. _this._emitFromParticle(particle);
  51521. _this.recycleParticle(particle);
  51522. index--;
  51523. continue;
  51524. }
  51525. else {
  51526. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51527. particle.color.addInPlace(_this._scaledColorStep);
  51528. if (particle.color.a < 0)
  51529. particle.color.a = 0;
  51530. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51531. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51532. particle.position.addInPlace(_this._scaledDirection);
  51533. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51534. particle.direction.addInPlace(_this._scaledGravity);
  51535. if (_this._isAnimationSheetEnabled) {
  51536. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51537. }
  51538. }
  51539. }
  51540. };
  51541. }
  51542. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51543. /**
  51544. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51545. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51546. */
  51547. get: function () {
  51548. if (this.particleEmitterType.direction1) {
  51549. return this.particleEmitterType.direction1;
  51550. }
  51551. return BABYLON.Vector3.Zero();
  51552. },
  51553. set: function (value) {
  51554. if (this.particleEmitterType.direction1) {
  51555. this.particleEmitterType.direction1 = value;
  51556. }
  51557. },
  51558. enumerable: true,
  51559. configurable: true
  51560. });
  51561. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51562. /**
  51563. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51564. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51565. */
  51566. get: function () {
  51567. if (this.particleEmitterType.direction2) {
  51568. return this.particleEmitterType.direction2;
  51569. }
  51570. return BABYLON.Vector3.Zero();
  51571. },
  51572. set: function (value) {
  51573. if (this.particleEmitterType.direction2) {
  51574. this.particleEmitterType.direction2 = value;
  51575. }
  51576. },
  51577. enumerable: true,
  51578. configurable: true
  51579. });
  51580. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51581. /**
  51582. * 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.
  51583. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51584. */
  51585. get: function () {
  51586. if (this.particleEmitterType.minEmitBox) {
  51587. return this.particleEmitterType.minEmitBox;
  51588. }
  51589. return BABYLON.Vector3.Zero();
  51590. },
  51591. set: function (value) {
  51592. if (this.particleEmitterType.minEmitBox) {
  51593. this.particleEmitterType.minEmitBox = value;
  51594. }
  51595. },
  51596. enumerable: true,
  51597. configurable: true
  51598. });
  51599. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51600. /**
  51601. * 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.
  51602. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51603. */
  51604. get: function () {
  51605. if (this.particleEmitterType.maxEmitBox) {
  51606. return this.particleEmitterType.maxEmitBox;
  51607. }
  51608. return BABYLON.Vector3.Zero();
  51609. },
  51610. set: function (value) {
  51611. if (this.particleEmitterType.maxEmitBox) {
  51612. this.particleEmitterType.maxEmitBox = value;
  51613. }
  51614. },
  51615. enumerable: true,
  51616. configurable: true
  51617. });
  51618. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51619. /**
  51620. * Sets a callback that will be triggered when the system is disposed.
  51621. */
  51622. set: function (callback) {
  51623. if (this._onDisposeObserver) {
  51624. this.onDisposeObservable.remove(this._onDisposeObserver);
  51625. }
  51626. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51627. },
  51628. enumerable: true,
  51629. configurable: true
  51630. });
  51631. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51632. /**
  51633. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51634. */
  51635. get: function () {
  51636. return this._isAnimationSheetEnabled;
  51637. },
  51638. enumerable: true,
  51639. configurable: true
  51640. });
  51641. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51642. //end of Sub-emitter
  51643. /**
  51644. * Gets the current list of active particles
  51645. */
  51646. get: function () {
  51647. return this._particles;
  51648. },
  51649. enumerable: true,
  51650. configurable: true
  51651. });
  51652. /**
  51653. * Returns the string "ParticleSystem"
  51654. * @returns a string containing the class name
  51655. */
  51656. ParticleSystem.prototype.getClassName = function () {
  51657. return "ParticleSystem";
  51658. };
  51659. ParticleSystem.prototype._createIndexBuffer = function () {
  51660. var indices = [];
  51661. var index = 0;
  51662. for (var count = 0; count < this._capacity; count++) {
  51663. indices.push(index);
  51664. indices.push(index + 1);
  51665. indices.push(index + 2);
  51666. indices.push(index);
  51667. indices.push(index + 2);
  51668. indices.push(index + 3);
  51669. index += 4;
  51670. }
  51671. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51672. };
  51673. /**
  51674. * Gets the maximum number of particles active at the same time.
  51675. * @returns The max number of active particles.
  51676. */
  51677. ParticleSystem.prototype.getCapacity = function () {
  51678. return this._capacity;
  51679. };
  51680. /**
  51681. * Gets Wether there are still active particles in the system.
  51682. * @returns True if it is alive, otherwise false.
  51683. */
  51684. ParticleSystem.prototype.isAlive = function () {
  51685. return this._alive;
  51686. };
  51687. /**
  51688. * Gets Wether the system has been started.
  51689. * @returns True if it has been started, otherwise false.
  51690. */
  51691. ParticleSystem.prototype.isStarted = function () {
  51692. return this._started;
  51693. };
  51694. /**
  51695. * Starts the particle system and begins to emit.
  51696. */
  51697. ParticleSystem.prototype.start = function () {
  51698. this._started = true;
  51699. this._stopped = false;
  51700. this._actualFrame = 0;
  51701. if (this.subEmitters && this.subEmitters.length != 0) {
  51702. this.activeSubSystems = new Array();
  51703. }
  51704. };
  51705. /**
  51706. * Stops the particle system.
  51707. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  51708. */
  51709. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51710. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51711. this._stopped = true;
  51712. if (stopSubEmitters) {
  51713. this._stopSubEmitters();
  51714. }
  51715. };
  51716. // animation sheet
  51717. /**
  51718. * Remove all active particles
  51719. */
  51720. ParticleSystem.prototype.reset = function () {
  51721. this._stockParticles = [];
  51722. this._particles = [];
  51723. };
  51724. /**
  51725. * @ignore (for internal use only)
  51726. */
  51727. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51728. var offset = index * this._vertexBufferSize;
  51729. this._vertexData[offset] = particle.position.x;
  51730. this._vertexData[offset + 1] = particle.position.y;
  51731. this._vertexData[offset + 2] = particle.position.z;
  51732. this._vertexData[offset + 3] = particle.color.r;
  51733. this._vertexData[offset + 4] = particle.color.g;
  51734. this._vertexData[offset + 5] = particle.color.b;
  51735. this._vertexData[offset + 6] = particle.color.a;
  51736. this._vertexData[offset + 7] = particle.angle;
  51737. this._vertexData[offset + 8] = particle.size;
  51738. this._vertexData[offset + 9] = offsetX;
  51739. this._vertexData[offset + 10] = offsetY;
  51740. };
  51741. /**
  51742. * @ignore (for internal use only)
  51743. */
  51744. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51745. if (offsetX === 0)
  51746. offsetX = this._epsilon;
  51747. else if (offsetX === 1)
  51748. offsetX = 1 - this._epsilon;
  51749. if (offsetY === 0)
  51750. offsetY = this._epsilon;
  51751. else if (offsetY === 1)
  51752. offsetY = 1 - this._epsilon;
  51753. var offset = index * this._vertexBufferSize;
  51754. this._vertexData[offset] = particle.position.x;
  51755. this._vertexData[offset + 1] = particle.position.y;
  51756. this._vertexData[offset + 2] = particle.position.z;
  51757. this._vertexData[offset + 3] = particle.color.r;
  51758. this._vertexData[offset + 4] = particle.color.g;
  51759. this._vertexData[offset + 5] = particle.color.b;
  51760. this._vertexData[offset + 6] = particle.color.a;
  51761. this._vertexData[offset + 7] = particle.angle;
  51762. this._vertexData[offset + 8] = particle.size;
  51763. this._vertexData[offset + 9] = offsetX;
  51764. this._vertexData[offset + 10] = offsetY;
  51765. this._vertexData[offset + 11] = particle.cellIndex;
  51766. };
  51767. ParticleSystem.prototype._stopSubEmitters = function () {
  51768. if (!this.activeSubSystems) {
  51769. return;
  51770. }
  51771. this.activeSubSystems.forEach(function (subSystem) {
  51772. subSystem.stop(true);
  51773. });
  51774. this.activeSubSystems = new Array();
  51775. };
  51776. ParticleSystem.prototype._removeFromRoot = function () {
  51777. if (!this._rootParticleSystem) {
  51778. return;
  51779. }
  51780. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51781. if (index !== -1) {
  51782. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51783. }
  51784. };
  51785. // end of sub system methods
  51786. ParticleSystem.prototype._update = function (newParticles) {
  51787. // Update current
  51788. this._alive = this._particles.length > 0;
  51789. this.updateFunction(this._particles);
  51790. // Add new ones
  51791. var worldMatrix;
  51792. if (this.emitter.position) {
  51793. var emitterMesh = this.emitter;
  51794. worldMatrix = emitterMesh.getWorldMatrix();
  51795. }
  51796. else {
  51797. var emitterPosition = this.emitter;
  51798. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51799. }
  51800. var particle;
  51801. for (var index = 0; index < newParticles; index++) {
  51802. if (this._particles.length === this._capacity) {
  51803. break;
  51804. }
  51805. particle = this._createParticle();
  51806. this._particles.push(particle);
  51807. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51808. if (this.startPositionFunction) {
  51809. this.startPositionFunction(worldMatrix, particle.position, particle);
  51810. }
  51811. else {
  51812. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51813. }
  51814. if (this.startDirectionFunction) {
  51815. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51816. }
  51817. else {
  51818. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51819. }
  51820. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51821. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51822. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51823. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51824. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51825. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51826. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51827. }
  51828. };
  51829. ParticleSystem.prototype._getEffect = function () {
  51830. if (this._customEffect) {
  51831. return this._customEffect;
  51832. }
  51833. ;
  51834. var defines = [];
  51835. if (this._scene.clipPlane) {
  51836. defines.push("#define CLIPPLANE");
  51837. }
  51838. if (this._isAnimationSheetEnabled) {
  51839. defines.push("#define ANIMATESHEET");
  51840. }
  51841. // Effect
  51842. var join = defines.join("\n");
  51843. if (this._cachedDefines !== join) {
  51844. this._cachedDefines = join;
  51845. var attributesNamesOrOptions;
  51846. var effectCreationOption;
  51847. if (this._isAnimationSheetEnabled) {
  51848. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51849. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51850. }
  51851. else {
  51852. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51853. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51854. }
  51855. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51856. }
  51857. return this._effect;
  51858. };
  51859. /**
  51860. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51861. */
  51862. ParticleSystem.prototype.animate = function () {
  51863. if (!this._started)
  51864. return;
  51865. var effect = this._getEffect();
  51866. // Check
  51867. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51868. return;
  51869. if (this._currentRenderId === this._scene.getRenderId()) {
  51870. return;
  51871. }
  51872. this._currentRenderId = this._scene.getRenderId();
  51873. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51874. // determine the number of particles we need to create
  51875. var newParticles;
  51876. if (this.manualEmitCount > -1) {
  51877. newParticles = this.manualEmitCount;
  51878. this._newPartsExcess = 0;
  51879. this.manualEmitCount = 0;
  51880. }
  51881. else {
  51882. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51883. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51884. }
  51885. if (this._newPartsExcess > 1.0) {
  51886. newParticles += this._newPartsExcess >> 0;
  51887. this._newPartsExcess -= this._newPartsExcess >> 0;
  51888. }
  51889. this._alive = false;
  51890. if (!this._stopped) {
  51891. this._actualFrame += this._scaledUpdateSpeed;
  51892. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51893. this.stop();
  51894. }
  51895. else {
  51896. newParticles = 0;
  51897. }
  51898. this._update(newParticles);
  51899. // Stopped?
  51900. if (this._stopped) {
  51901. if (!this._alive) {
  51902. this._started = false;
  51903. if (this.onAnimationEnd) {
  51904. this.onAnimationEnd();
  51905. }
  51906. if (this.disposeOnStop) {
  51907. this._scene._toBeDisposed.push(this);
  51908. }
  51909. }
  51910. }
  51911. // Animation sheet
  51912. if (this._isAnimationSheetEnabled) {
  51913. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51914. }
  51915. else {
  51916. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51917. }
  51918. // Update VBO
  51919. var offset = 0;
  51920. for (var index = 0; index < this._particles.length; index++) {
  51921. var particle = this._particles[index];
  51922. this._appendParticleVertexes(offset, particle);
  51923. offset += 4;
  51924. }
  51925. if (this._vertexBuffer) {
  51926. this._vertexBuffer.update(this._vertexData);
  51927. }
  51928. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  51929. this.stop();
  51930. }
  51931. };
  51932. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51933. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51934. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51935. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51936. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51937. };
  51938. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51939. this._appendParticleVertex(offset++, particle, 0, 0);
  51940. this._appendParticleVertex(offset++, particle, 1, 0);
  51941. this._appendParticleVertex(offset++, particle, 1, 1);
  51942. this._appendParticleVertex(offset++, particle, 0, 1);
  51943. };
  51944. /**
  51945. * Rebuilds the particle system.
  51946. */
  51947. ParticleSystem.prototype.rebuild = function () {
  51948. this._createIndexBuffer();
  51949. if (this._vertexBuffer) {
  51950. this._vertexBuffer._rebuild();
  51951. }
  51952. };
  51953. /**
  51954. * Is this system ready to be used/rendered
  51955. * @return true if the system is ready
  51956. */
  51957. ParticleSystem.prototype.isReady = function () {
  51958. var effect = this._getEffect();
  51959. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  51960. return false;
  51961. }
  51962. return true;
  51963. };
  51964. /**
  51965. * Renders the particle system in its current state.
  51966. * @returns the current number of particles
  51967. */
  51968. ParticleSystem.prototype.render = function () {
  51969. var effect = this._getEffect();
  51970. // Check
  51971. if (!this.isReady() || !this._particles.length) {
  51972. return 0;
  51973. }
  51974. var engine = this._scene.getEngine();
  51975. // Render
  51976. engine.enableEffect(effect);
  51977. engine.setState(false);
  51978. var viewMatrix = this._scene.getViewMatrix();
  51979. effect.setTexture("diffuseSampler", this.particleTexture);
  51980. effect.setMatrix("view", viewMatrix);
  51981. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51982. if (this._isAnimationSheetEnabled && this.particleTexture) {
  51983. var baseSize = this.particleTexture.getBaseSize();
  51984. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51985. }
  51986. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51987. if (this._scene.clipPlane) {
  51988. var clipPlane = this._scene.clipPlane;
  51989. var invView = viewMatrix.clone();
  51990. invView.invert();
  51991. effect.setMatrix("invView", invView);
  51992. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51993. }
  51994. // VBOs
  51995. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51996. // Draw order
  51997. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51998. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51999. }
  52000. else {
  52001. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52002. }
  52003. if (this.forceDepthWrite) {
  52004. engine.setDepthWrite(true);
  52005. }
  52006. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52007. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52008. return this._particles.length;
  52009. };
  52010. /**
  52011. * Disposes the particle system and free the associated resources
  52012. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52013. */
  52014. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52015. if (disposeTexture === void 0) { disposeTexture = true; }
  52016. if (this._vertexBuffer) {
  52017. this._vertexBuffer.dispose();
  52018. this._vertexBuffer = null;
  52019. }
  52020. if (this._indexBuffer) {
  52021. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52022. this._indexBuffer = null;
  52023. }
  52024. if (disposeTexture && this.particleTexture) {
  52025. this.particleTexture.dispose();
  52026. this.particleTexture = null;
  52027. }
  52028. this._removeFromRoot();
  52029. // Remove from scene
  52030. var index = this._scene.particleSystems.indexOf(this);
  52031. if (index > -1) {
  52032. this._scene.particleSystems.splice(index, 1);
  52033. }
  52034. // Callback
  52035. this.onDisposeObservable.notifyObservers(this);
  52036. this.onDisposeObservable.clear();
  52037. };
  52038. /**
  52039. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52040. * @param radius The radius of the sphere to emit from
  52041. * @returns the emitter
  52042. */
  52043. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52044. if (radius === void 0) { radius = 1; }
  52045. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52046. this.particleEmitterType = particleEmitter;
  52047. return particleEmitter;
  52048. };
  52049. /**
  52050. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52051. * @param radius The radius of the sphere to emit from
  52052. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52053. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52054. * @returns the emitter
  52055. */
  52056. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52057. if (radius === void 0) { radius = 1; }
  52058. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52059. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52060. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52061. this.particleEmitterType = particleEmitter;
  52062. return particleEmitter;
  52063. };
  52064. /**
  52065. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52066. * @param radius The radius of the cone to emit from
  52067. * @param angle The base angle of the cone
  52068. * @returns the emitter
  52069. */
  52070. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52071. if (radius === void 0) { radius = 1; }
  52072. if (angle === void 0) { angle = Math.PI / 4; }
  52073. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52074. this.particleEmitterType = particleEmitter;
  52075. return particleEmitter;
  52076. };
  52077. // 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.
  52078. /**
  52079. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52080. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52081. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52082. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52083. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52084. * @returns the emitter
  52085. */
  52086. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52087. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52088. this.direction1 = direction1;
  52089. this.direction2 = direction2;
  52090. this.minEmitBox = minEmitBox;
  52091. this.maxEmitBox = maxEmitBox;
  52092. this.particleEmitterType = particleEmitter;
  52093. return particleEmitter;
  52094. };
  52095. // Clone
  52096. /**
  52097. * Clones the particle system.
  52098. * @param name The name of the cloned object
  52099. * @param newEmitter The new emitter to use
  52100. * @returns the cloned particle system
  52101. */
  52102. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52103. var custom = null;
  52104. var program = null;
  52105. if (this.customShader != null) {
  52106. program = this.customShader;
  52107. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52108. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52109. }
  52110. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52111. result.customShader = program;
  52112. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52113. if (newEmitter === undefined) {
  52114. newEmitter = this.emitter;
  52115. }
  52116. result.emitter = newEmitter;
  52117. if (this.particleTexture) {
  52118. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52119. }
  52120. if (!this.preventAutoStart) {
  52121. result.start();
  52122. }
  52123. return result;
  52124. };
  52125. /**
  52126. * Serializes the particle system to a JSON object.
  52127. * @returns the JSON object
  52128. */
  52129. ParticleSystem.prototype.serialize = function () {
  52130. var serializationObject = {};
  52131. serializationObject.name = this.name;
  52132. serializationObject.id = this.id;
  52133. // Emitter
  52134. if (this.emitter.position) {
  52135. var emitterMesh = this.emitter;
  52136. serializationObject.emitterId = emitterMesh.id;
  52137. }
  52138. else {
  52139. var emitterPosition = this.emitter;
  52140. serializationObject.emitter = emitterPosition.asArray();
  52141. }
  52142. serializationObject.capacity = this.getCapacity();
  52143. if (this.particleTexture) {
  52144. serializationObject.textureName = this.particleTexture.name;
  52145. }
  52146. // Animations
  52147. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52148. // Particle system
  52149. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52150. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52151. serializationObject.minSize = this.minSize;
  52152. serializationObject.maxSize = this.maxSize;
  52153. serializationObject.minEmitPower = this.minEmitPower;
  52154. serializationObject.maxEmitPower = this.maxEmitPower;
  52155. serializationObject.minLifeTime = this.minLifeTime;
  52156. serializationObject.maxLifeTime = this.maxLifeTime;
  52157. serializationObject.emitRate = this.emitRate;
  52158. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52159. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52160. serializationObject.gravity = this.gravity.asArray();
  52161. serializationObject.direction1 = this.direction1.asArray();
  52162. serializationObject.direction2 = this.direction2.asArray();
  52163. serializationObject.color1 = this.color1.asArray();
  52164. serializationObject.color2 = this.color2.asArray();
  52165. serializationObject.colorDead = this.colorDead.asArray();
  52166. serializationObject.updateSpeed = this.updateSpeed;
  52167. serializationObject.targetStopDuration = this.targetStopDuration;
  52168. serializationObject.textureMask = this.textureMask.asArray();
  52169. serializationObject.blendMode = this.blendMode;
  52170. serializationObject.customShader = this.customShader;
  52171. serializationObject.preventAutoStart = this.preventAutoStart;
  52172. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52173. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52174. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52175. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52176. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52177. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52178. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52179. // Emitter
  52180. if (this.particleEmitterType) {
  52181. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52182. }
  52183. return serializationObject;
  52184. };
  52185. /**
  52186. * Parses a JSON object to create a particle system.
  52187. * @param parsedParticleSystem The JSON object to parse
  52188. * @param scene The scene to create the particle system in
  52189. * @param rootUrl The root url to use to load external dependencies like texture
  52190. * @returns the Parsed particle system
  52191. */
  52192. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52193. var name = parsedParticleSystem.name;
  52194. var custom = null;
  52195. var program = null;
  52196. if (parsedParticleSystem.customShader) {
  52197. program = parsedParticleSystem.customShader;
  52198. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52199. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52200. }
  52201. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52202. particleSystem.customShader = program;
  52203. if (parsedParticleSystem.id) {
  52204. particleSystem.id = parsedParticleSystem.id;
  52205. }
  52206. // Auto start
  52207. if (parsedParticleSystem.preventAutoStart) {
  52208. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52209. }
  52210. // Texture
  52211. if (parsedParticleSystem.textureName) {
  52212. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52213. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52214. }
  52215. // Emitter
  52216. if (parsedParticleSystem.emitterId) {
  52217. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52218. }
  52219. else {
  52220. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52221. }
  52222. // Animations
  52223. if (parsedParticleSystem.animations) {
  52224. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52225. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52226. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52227. }
  52228. }
  52229. if (parsedParticleSystem.autoAnimate) {
  52230. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52231. }
  52232. // Particle system
  52233. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52234. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52235. particleSystem.minSize = parsedParticleSystem.minSize;
  52236. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52237. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52238. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52239. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52240. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52241. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52242. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52243. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52244. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52245. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52246. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52247. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52248. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52249. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52250. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52251. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52252. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52253. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52254. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52255. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52256. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52257. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52258. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52259. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52260. if (!particleSystem.preventAutoStart) {
  52261. particleSystem.start();
  52262. }
  52263. return particleSystem;
  52264. };
  52265. /**
  52266. * Source color is added to the destination color without alpha affecting the result.
  52267. */
  52268. ParticleSystem.BLENDMODE_ONEONE = 0;
  52269. /**
  52270. * Blend current color and particle color using particle’s alpha.
  52271. */
  52272. ParticleSystem.BLENDMODE_STANDARD = 1;
  52273. return ParticleSystem;
  52274. }());
  52275. BABYLON.ParticleSystem = ParticleSystem;
  52276. })(BABYLON || (BABYLON = {}));
  52277. //# sourceMappingURL=babylon.particleSystem.js.map
  52278. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52279. var BABYLON;
  52280. (function (BABYLON) {
  52281. /**
  52282. * Particle emitter emitting particles from the inside of a box.
  52283. * It emits the particles randomly between 2 given directions.
  52284. */
  52285. var BoxParticleEmitter = /** @class */ (function () {
  52286. /**
  52287. * Creates a new instance of @see BoxParticleEmitter
  52288. */
  52289. function BoxParticleEmitter() {
  52290. /**
  52291. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52292. */
  52293. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52294. /**
  52295. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52296. */
  52297. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52298. /**
  52299. * 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.
  52300. */
  52301. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52302. /**
  52303. * 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.
  52304. */
  52305. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52306. }
  52307. /**
  52308. * Called by the particle System when the direction is computed for the created particle.
  52309. * @param emitPower is the power of the particle (speed)
  52310. * @param worldMatrix is the world matrix of the particle system
  52311. * @param directionToUpdate is the direction vector to update with the result
  52312. * @param particle is the particle we are computed the direction for
  52313. */
  52314. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52315. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52316. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52317. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52318. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52319. };
  52320. /**
  52321. * Called by the particle System when the position is computed for the created particle.
  52322. * @param worldMatrix is the world matrix of the particle system
  52323. * @param positionToUpdate is the position vector to update with the result
  52324. * @param particle is the particle we are computed the position for
  52325. */
  52326. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52327. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52328. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52329. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52330. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52331. };
  52332. /**
  52333. * Clones the current emitter and returns a copy of it
  52334. * @returns the new emitter
  52335. */
  52336. BoxParticleEmitter.prototype.clone = function () {
  52337. var newOne = new BoxParticleEmitter();
  52338. BABYLON.Tools.DeepCopy(this, newOne);
  52339. return newOne;
  52340. };
  52341. /**
  52342. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52343. * @param effect defines the update shader
  52344. */
  52345. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52346. effect.setVector3("direction1", this.direction1);
  52347. effect.setVector3("direction2", this.direction2);
  52348. effect.setVector3("minEmitBox", this.minEmitBox);
  52349. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52350. };
  52351. /**
  52352. * Returns a string to use to update the GPU particles update shader
  52353. * @returns a string containng the defines string
  52354. */
  52355. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52356. return "#define BOXEMITTER";
  52357. };
  52358. /**
  52359. * Returns the string "BoxEmitter"
  52360. * @returns a string containing the class name
  52361. */
  52362. BoxParticleEmitter.prototype.getClassName = function () {
  52363. return "BoxEmitter";
  52364. };
  52365. /**
  52366. * Serializes the particle system to a JSON object.
  52367. * @returns the JSON object
  52368. */
  52369. BoxParticleEmitter.prototype.serialize = function () {
  52370. var serializationObject = {};
  52371. serializationObject.type = this.getClassName();
  52372. serializationObject.direction1 = this.direction1.asArray();
  52373. ;
  52374. serializationObject.direction2 = this.direction2.asArray();
  52375. ;
  52376. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52377. ;
  52378. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52379. ;
  52380. return serializationObject;
  52381. };
  52382. /**
  52383. * Parse properties from a JSON object
  52384. * @param serializationObject defines the JSON object
  52385. */
  52386. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52387. this.direction1.copyFrom(serializationObject.direction1);
  52388. this.direction2.copyFrom(serializationObject.direction2);
  52389. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52390. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52391. };
  52392. return BoxParticleEmitter;
  52393. }());
  52394. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52395. })(BABYLON || (BABYLON = {}));
  52396. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52397. var BABYLON;
  52398. (function (BABYLON) {
  52399. /**
  52400. * Particle emitter emitting particles from the inside of a cone.
  52401. * It emits the particles alongside the cone volume from the base to the particle.
  52402. * The emission direction might be randomized.
  52403. */
  52404. var ConeParticleEmitter = /** @class */ (function () {
  52405. /**
  52406. * Creates a new instance of @see ConeParticleEmitter
  52407. * @param radius the radius of the emission cone (1 by default)
  52408. * @param angles the cone base angle (PI by default)
  52409. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52410. */
  52411. function ConeParticleEmitter(radius,
  52412. /**
  52413. * The radius of the emission cone.
  52414. */
  52415. angle,
  52416. /**
  52417. * The cone base angle.
  52418. */
  52419. directionRandomizer) {
  52420. if (radius === void 0) { radius = 1; }
  52421. if (angle === void 0) { angle = Math.PI; }
  52422. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52423. this.angle = angle;
  52424. this.directionRandomizer = directionRandomizer;
  52425. this.radius = radius;
  52426. }
  52427. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52428. /**
  52429. * Gets the radius of the emission cone.
  52430. */
  52431. get: function () {
  52432. return this._radius;
  52433. },
  52434. /**
  52435. * Sets the radius of the emission cone.
  52436. */
  52437. set: function (value) {
  52438. this._radius = value;
  52439. if (this.angle !== 0) {
  52440. this._height = value / Math.tan(this.angle / 2);
  52441. }
  52442. else {
  52443. this._height = 1;
  52444. }
  52445. },
  52446. enumerable: true,
  52447. configurable: true
  52448. });
  52449. /**
  52450. * Called by the particle System when the direction is computed for the created particle.
  52451. * @param emitPower is the power of the particle (speed)
  52452. * @param worldMatrix is the world matrix of the particle system
  52453. * @param directionToUpdate is the direction vector to update with the result
  52454. * @param particle is the particle we are computed the direction for
  52455. */
  52456. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52457. if (this.angle === 0) {
  52458. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52459. }
  52460. else {
  52461. // measure the direction Vector from the emitter to the particle.
  52462. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52463. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52464. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52465. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52466. direction.x += randX;
  52467. direction.y += randY;
  52468. direction.z += randZ;
  52469. direction.normalize();
  52470. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52471. }
  52472. };
  52473. /**
  52474. * Called by the particle System when the position is computed for the created particle.
  52475. * @param worldMatrix is the world matrix of the particle system
  52476. * @param positionToUpdate is the position vector to update with the result
  52477. * @param particle is the particle we are computed the position for
  52478. */
  52479. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52480. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52481. var h = BABYLON.Scalar.RandomRange(0, 1);
  52482. // Better distribution in a cone at normal angles.
  52483. h = 1 - h * h;
  52484. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52485. radius = radius * h / this._height;
  52486. var randX = radius * Math.sin(s);
  52487. var randZ = radius * Math.cos(s);
  52488. var randY = h * this._height;
  52489. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52490. };
  52491. /**
  52492. * Clones the current emitter and returns a copy of it
  52493. * @returns the new emitter
  52494. */
  52495. ConeParticleEmitter.prototype.clone = function () {
  52496. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52497. BABYLON.Tools.DeepCopy(this, newOne);
  52498. return newOne;
  52499. };
  52500. /**
  52501. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52502. * @param effect defines the update shader
  52503. */
  52504. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52505. effect.setFloat("radius", this.radius);
  52506. effect.setFloat("angle", this.angle);
  52507. effect.setFloat("height", this._height);
  52508. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52509. };
  52510. /**
  52511. * Returns a string to use to update the GPU particles update shader
  52512. * @returns a string containng the defines string
  52513. */
  52514. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52515. return "#define CONEEMITTER";
  52516. };
  52517. /**
  52518. * Returns the string "BoxEmitter"
  52519. * @returns a string containing the class name
  52520. */
  52521. ConeParticleEmitter.prototype.getClassName = function () {
  52522. return "ConeEmitter";
  52523. };
  52524. /**
  52525. * Serializes the particle system to a JSON object.
  52526. * @returns the JSON object
  52527. */
  52528. ConeParticleEmitter.prototype.serialize = function () {
  52529. var serializationObject = {};
  52530. serializationObject.type = this.getClassName();
  52531. serializationObject.radius = this.radius;
  52532. serializationObject.angle = this.angle;
  52533. serializationObject.directionRandomizer = this.directionRandomizer;
  52534. return serializationObject;
  52535. };
  52536. /**
  52537. * Parse properties from a JSON object
  52538. * @param serializationObject defines the JSON object
  52539. */
  52540. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52541. this.radius = serializationObject.radius;
  52542. this.angle = serializationObject.angle;
  52543. this.directionRandomizer = serializationObject.directionRandomizer;
  52544. };
  52545. return ConeParticleEmitter;
  52546. }());
  52547. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52548. })(BABYLON || (BABYLON = {}));
  52549. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52550. var BABYLON;
  52551. (function (BABYLON) {
  52552. /**
  52553. * Particle emitter emitting particles from the inside of a sphere.
  52554. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52555. */
  52556. var SphereParticleEmitter = /** @class */ (function () {
  52557. /**
  52558. * Creates a new instance of @see SphereParticleEmitter
  52559. * @param radius the radius of the emission sphere (1 by default)
  52560. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52561. */
  52562. function SphereParticleEmitter(
  52563. /**
  52564. * The radius of the emission sphere.
  52565. */
  52566. radius,
  52567. /**
  52568. * How much to randomize the particle direction [0-1].
  52569. */
  52570. directionRandomizer) {
  52571. if (radius === void 0) { radius = 1; }
  52572. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52573. this.radius = radius;
  52574. this.directionRandomizer = directionRandomizer;
  52575. }
  52576. /**
  52577. * Called by the particle System when the direction is computed for the created particle.
  52578. * @param emitPower is the power of the particle (speed)
  52579. * @param worldMatrix is the world matrix of the particle system
  52580. * @param directionToUpdate is the direction vector to update with the result
  52581. * @param particle is the particle we are computed the direction for
  52582. */
  52583. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52584. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52585. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52586. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52587. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52588. direction.x += randX;
  52589. direction.y += randY;
  52590. direction.z += randZ;
  52591. direction.normalize();
  52592. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52593. };
  52594. /**
  52595. * Called by the particle System when the position is computed for the created particle.
  52596. * @param worldMatrix is the world matrix of the particle system
  52597. * @param positionToUpdate is the position vector to update with the result
  52598. * @param particle is the particle we are computed the position for
  52599. */
  52600. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52601. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52602. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52603. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52604. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52605. var randY = randRadius * Math.cos(theta);
  52606. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52607. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52608. };
  52609. /**
  52610. * Clones the current emitter and returns a copy of it
  52611. * @returns the new emitter
  52612. */
  52613. SphereParticleEmitter.prototype.clone = function () {
  52614. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52615. BABYLON.Tools.DeepCopy(this, newOne);
  52616. return newOne;
  52617. };
  52618. /**
  52619. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52620. * @param effect defines the update shader
  52621. */
  52622. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52623. effect.setFloat("radius", this.radius);
  52624. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52625. };
  52626. /**
  52627. * Returns a string to use to update the GPU particles update shader
  52628. * @returns a string containng the defines string
  52629. */
  52630. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52631. return "#define SPHEREEMITTER";
  52632. };
  52633. /**
  52634. * Returns the string "SphereParticleEmitter"
  52635. * @returns a string containing the class name
  52636. */
  52637. SphereParticleEmitter.prototype.getClassName = function () {
  52638. return "SphereParticleEmitter";
  52639. };
  52640. /**
  52641. * Serializes the particle system to a JSON object.
  52642. * @returns the JSON object
  52643. */
  52644. SphereParticleEmitter.prototype.serialize = function () {
  52645. var serializationObject = {};
  52646. serializationObject.type = this.getClassName();
  52647. serializationObject.radius = this.radius;
  52648. serializationObject.directionRandomizer = this.directionRandomizer;
  52649. return serializationObject;
  52650. };
  52651. /**
  52652. * Parse properties from a JSON object
  52653. * @param serializationObject defines the JSON object
  52654. */
  52655. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52656. this.radius = serializationObject.radius;
  52657. this.directionRandomizer = serializationObject.directionRandomizer;
  52658. };
  52659. return SphereParticleEmitter;
  52660. }());
  52661. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52662. /**
  52663. * Particle emitter emitting particles from the inside of a sphere.
  52664. * It emits the particles randomly between two vectors.
  52665. */
  52666. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52667. __extends(SphereDirectedParticleEmitter, _super);
  52668. /**
  52669. * Creates a new instance of @see SphereDirectedParticleEmitter
  52670. * @param radius the radius of the emission sphere (1 by default)
  52671. * @param direction1 the min limit of the emission direction (up vector by default)
  52672. * @param direction2 the max limit of the emission direction (up vector by default)
  52673. */
  52674. function SphereDirectedParticleEmitter(radius,
  52675. /**
  52676. * The min limit of the emission direction.
  52677. */
  52678. direction1,
  52679. /**
  52680. * The max limit of the emission direction.
  52681. */
  52682. direction2) {
  52683. if (radius === void 0) { radius = 1; }
  52684. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52685. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52686. var _this = _super.call(this, radius) || this;
  52687. _this.direction1 = direction1;
  52688. _this.direction2 = direction2;
  52689. return _this;
  52690. }
  52691. /**
  52692. * Called by the particle System when the direction is computed for the created particle.
  52693. * @param emitPower is the power of the particle (speed)
  52694. * @param worldMatrix is the world matrix of the particle system
  52695. * @param directionToUpdate is the direction vector to update with the result
  52696. * @param particle is the particle we are computed the direction for
  52697. */
  52698. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52699. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52700. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52701. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52702. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52703. };
  52704. /**
  52705. * Clones the current emitter and returns a copy of it
  52706. * @returns the new emitter
  52707. */
  52708. SphereDirectedParticleEmitter.prototype.clone = function () {
  52709. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52710. BABYLON.Tools.DeepCopy(this, newOne);
  52711. return newOne;
  52712. };
  52713. /**
  52714. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52715. * @param effect defines the update shader
  52716. */
  52717. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52718. effect.setFloat("radius", this.radius);
  52719. effect.setVector3("direction1", this.direction1);
  52720. effect.setVector3("direction2", this.direction2);
  52721. };
  52722. /**
  52723. * Returns a string to use to update the GPU particles update shader
  52724. * @returns a string containng the defines string
  52725. */
  52726. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52727. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52728. };
  52729. /**
  52730. * Returns the string "SphereDirectedParticleEmitter"
  52731. * @returns a string containing the class name
  52732. */
  52733. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52734. return "SphereDirectedParticleEmitter";
  52735. };
  52736. /**
  52737. * Serializes the particle system to a JSON object.
  52738. * @returns the JSON object
  52739. */
  52740. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52741. var serializationObject = _super.prototype.serialize.call(this);
  52742. ;
  52743. serializationObject.direction1 = this.direction1.asArray();
  52744. ;
  52745. serializationObject.direction2 = this.direction2.asArray();
  52746. ;
  52747. return serializationObject;
  52748. };
  52749. /**
  52750. * Parse properties from a JSON object
  52751. * @param serializationObject defines the JSON object
  52752. */
  52753. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52754. _super.prototype.parse.call(this, serializationObject);
  52755. this.direction1.copyFrom(serializationObject.direction1);
  52756. this.direction2.copyFrom(serializationObject.direction2);
  52757. };
  52758. return SphereDirectedParticleEmitter;
  52759. }(SphereParticleEmitter));
  52760. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52761. })(BABYLON || (BABYLON = {}));
  52762. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52763. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52764. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52765. s = arguments[i];
  52766. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52767. t[p] = s[p];
  52768. }
  52769. return t;
  52770. };
  52771. var BABYLON;
  52772. (function (BABYLON) {
  52773. /**
  52774. * This represents a GPU particle system in Babylon
  52775. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52776. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52777. */
  52778. var GPUParticleSystem = /** @class */ (function () {
  52779. /**
  52780. * Instantiates a GPU particle system.
  52781. * 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.
  52782. * @param name The name of the particle system
  52783. * @param capacity The max number of particles alive at the same time
  52784. * @param scene The scene the particle system belongs to
  52785. */
  52786. function GPUParticleSystem(name, options, scene) {
  52787. /**
  52788. * The emitter represents the Mesh or position we are attaching the particle system to.
  52789. */
  52790. this.emitter = null;
  52791. /**
  52792. * The rendering group used by the Particle system to chose when to render.
  52793. */
  52794. this.renderingGroupId = 0;
  52795. /**
  52796. * The layer mask we are rendering the particles through.
  52797. */
  52798. this.layerMask = 0x0FFFFFFF;
  52799. this._targetIndex = 0;
  52800. this._currentRenderId = -1;
  52801. this._started = false;
  52802. this._stopped = false;
  52803. this._timeDelta = 0;
  52804. this._attributesStrideSize = 14;
  52805. this._actualFrame = 0;
  52806. /**
  52807. * List of animations used by the particle system.
  52808. */
  52809. this.animations = [];
  52810. /**
  52811. * An event triggered when the system is disposed.
  52812. */
  52813. this.onDisposeObservable = new BABYLON.Observable();
  52814. /**
  52815. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52816. */
  52817. this.updateSpeed = 0.01;
  52818. /**
  52819. * The amount of time the particle system is running (depends of the overall update speed).
  52820. */
  52821. this.targetStopDuration = 0;
  52822. /**
  52823. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52824. */
  52825. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52826. /**
  52827. * Minimum life time of emitting particles.
  52828. */
  52829. this.minLifeTime = 1;
  52830. /**
  52831. * Maximum life time of emitting particles.
  52832. */
  52833. this.maxLifeTime = 1;
  52834. /**
  52835. * Minimum Size of emitting particles.
  52836. */
  52837. this.minSize = 1;
  52838. /**
  52839. * Maximum Size of emitting particles.
  52840. */
  52841. this.maxSize = 1;
  52842. /**
  52843. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52844. */
  52845. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52846. /**
  52847. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52848. */
  52849. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52850. /**
  52851. * Color the particle will have at the end of its lifetime.
  52852. */
  52853. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52854. /**
  52855. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52856. */
  52857. this.emitRate = 100;
  52858. /**
  52859. * You can use gravity if you want to give an orientation to your particles.
  52860. */
  52861. this.gravity = BABYLON.Vector3.Zero();
  52862. /**
  52863. * Minimum power of emitting particles.
  52864. */
  52865. this.minEmitPower = 1;
  52866. /**
  52867. * Maximum power of emitting particles.
  52868. */
  52869. this.maxEmitPower = 1;
  52870. /**
  52871. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52872. * to override the particles.
  52873. */
  52874. this.forceDepthWrite = false;
  52875. this.id = name;
  52876. this.name = name;
  52877. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52878. this._engine = this._scene.getEngine();
  52879. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52880. this._capacity = fullOptions.capacity;
  52881. this._activeCount = fullOptions.capacity;
  52882. this._currentActiveCount = 0;
  52883. this._scene.particleSystems.push(this);
  52884. this._updateEffectOptions = {
  52885. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52886. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52887. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  52888. uniformBuffersNames: [],
  52889. samplers: ["randomSampler"],
  52890. defines: "",
  52891. fallbacks: null,
  52892. onCompiled: null,
  52893. onError: null,
  52894. indexParameters: null,
  52895. maxSimultaneousLights: 0,
  52896. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52897. };
  52898. // Random data
  52899. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52900. var d = [];
  52901. for (var i = 0; i < maxTextureSize; ++i) {
  52902. d.push(Math.random());
  52903. d.push(Math.random());
  52904. d.push(Math.random());
  52905. d.push(Math.random());
  52906. }
  52907. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  52908. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52909. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52910. this._randomTextureSize = maxTextureSize;
  52911. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52912. }
  52913. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52914. /**
  52915. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52916. */
  52917. get: function () {
  52918. if (!BABYLON.Engine.LastCreatedEngine) {
  52919. return false;
  52920. }
  52921. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52922. },
  52923. enumerable: true,
  52924. configurable: true
  52925. });
  52926. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52927. /**
  52928. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52929. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52930. */
  52931. get: function () {
  52932. if (this.particleEmitterType.direction1) {
  52933. return this.particleEmitterType.direction1;
  52934. }
  52935. return BABYLON.Vector3.Zero();
  52936. },
  52937. set: function (value) {
  52938. if (this.particleEmitterType.direction1) {
  52939. this.particleEmitterType.direction1 = value;
  52940. }
  52941. },
  52942. enumerable: true,
  52943. configurable: true
  52944. });
  52945. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52946. /**
  52947. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52948. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52949. */
  52950. get: function () {
  52951. if (this.particleEmitterType.direction2) {
  52952. return this.particleEmitterType.direction2;
  52953. }
  52954. return BABYLON.Vector3.Zero();
  52955. },
  52956. set: function (value) {
  52957. if (this.particleEmitterType.direction2) {
  52958. this.particleEmitterType.direction2 = value;
  52959. }
  52960. },
  52961. enumerable: true,
  52962. configurable: true
  52963. });
  52964. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52965. /**
  52966. * 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.
  52967. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52968. */
  52969. get: function () {
  52970. if (this.particleEmitterType.minEmitBox) {
  52971. return this.particleEmitterType.minEmitBox;
  52972. }
  52973. return BABYLON.Vector3.Zero();
  52974. },
  52975. set: function (value) {
  52976. if (this.particleEmitterType.minEmitBox) {
  52977. this.particleEmitterType.minEmitBox = value;
  52978. }
  52979. },
  52980. enumerable: true,
  52981. configurable: true
  52982. });
  52983. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52984. /**
  52985. * 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.
  52986. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52987. */
  52988. get: function () {
  52989. if (this.particleEmitterType.maxEmitBox) {
  52990. return this.particleEmitterType.maxEmitBox;
  52991. }
  52992. return BABYLON.Vector3.Zero();
  52993. },
  52994. set: function (value) {
  52995. if (this.particleEmitterType.maxEmitBox) {
  52996. this.particleEmitterType.maxEmitBox = value;
  52997. }
  52998. },
  52999. enumerable: true,
  53000. configurable: true
  53001. });
  53002. /**
  53003. * Gets the maximum number of particles active at the same time.
  53004. * @returns The max number of active particles.
  53005. */
  53006. GPUParticleSystem.prototype.getCapacity = function () {
  53007. return this._capacity;
  53008. };
  53009. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53010. /**
  53011. * Gets or set the number of active particles
  53012. */
  53013. get: function () {
  53014. return this._activeCount;
  53015. },
  53016. set: function (value) {
  53017. this._activeCount = Math.min(value, this._capacity);
  53018. },
  53019. enumerable: true,
  53020. configurable: true
  53021. });
  53022. /**
  53023. * Is this system ready to be used/rendered
  53024. * @return true if the system is ready
  53025. */
  53026. GPUParticleSystem.prototype.isReady = function () {
  53027. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53028. return false;
  53029. }
  53030. return true;
  53031. };
  53032. /**
  53033. * Gets Wether the system has been started.
  53034. * @returns True if it has been started, otherwise false.
  53035. */
  53036. GPUParticleSystem.prototype.isStarted = function () {
  53037. return this._started;
  53038. };
  53039. /**
  53040. * Starts the particle system and begins to emit.
  53041. */
  53042. GPUParticleSystem.prototype.start = function () {
  53043. this._started = true;
  53044. this._stopped = false;
  53045. };
  53046. /**
  53047. * Stops the particle system.
  53048. */
  53049. GPUParticleSystem.prototype.stop = function () {
  53050. this._stopped = true;
  53051. };
  53052. /**
  53053. * Remove all active particles
  53054. */
  53055. GPUParticleSystem.prototype.reset = function () {
  53056. this._releaseBuffers();
  53057. this._releaseVAOs();
  53058. this._currentActiveCount = 0;
  53059. this._targetIndex = 0;
  53060. };
  53061. /**
  53062. * Returns the string "GPUParticleSystem"
  53063. * @returns a string containing the class name
  53064. */
  53065. GPUParticleSystem.prototype.getClassName = function () {
  53066. return "GPUParticleSystem";
  53067. };
  53068. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53069. var updateVertexBuffers = {};
  53070. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53071. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53072. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53073. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53074. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53075. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53076. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53077. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53078. this._engine.bindArrayBuffer(null);
  53079. return vao;
  53080. };
  53081. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53082. var renderVertexBuffers = {};
  53083. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53084. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53085. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53086. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53087. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53088. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53089. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53090. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53091. this._engine.bindArrayBuffer(null);
  53092. return vao;
  53093. };
  53094. GPUParticleSystem.prototype._initialize = function (force) {
  53095. if (force === void 0) { force = false; }
  53096. if (this._buffer0 && !force) {
  53097. return;
  53098. }
  53099. var engine = this._scene.getEngine();
  53100. var data = new Array();
  53101. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53102. // position
  53103. data.push(0.0);
  53104. data.push(0.0);
  53105. data.push(0.0);
  53106. // Age and life
  53107. data.push(0.0); // create the particle as a dead one to create a new one at start
  53108. data.push(0.0);
  53109. // Seed
  53110. data.push(Math.random());
  53111. // Size
  53112. data.push(0.0);
  53113. // color
  53114. data.push(0.0);
  53115. data.push(0.0);
  53116. data.push(0.0);
  53117. data.push(0.0);
  53118. // direction
  53119. data.push(0.0);
  53120. data.push(0.0);
  53121. data.push(0.0);
  53122. }
  53123. // Sprite data
  53124. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53125. -0.5, 0.5, 0, 1,
  53126. -0.5, -0.5, 0, 0,
  53127. 0.5, -0.5, 1, 0]);
  53128. // Buffers
  53129. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53130. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53131. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53132. // Update VAO
  53133. this._updateVAO = [];
  53134. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53135. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53136. // Render VAO
  53137. this._renderVAO = [];
  53138. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53139. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53140. // Links
  53141. this._sourceBuffer = this._buffer0;
  53142. this._targetBuffer = this._buffer1;
  53143. };
  53144. /** @ignore */
  53145. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53146. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53147. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53148. return;
  53149. }
  53150. this._updateEffectOptions.defines = defines;
  53151. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53152. };
  53153. /** @ignore */
  53154. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53155. var defines = "";
  53156. if (this._scene.clipPlane) {
  53157. defines = "\n#define CLIPPLANE";
  53158. }
  53159. if (this._renderEffect && this._renderEffect.defines === defines) {
  53160. return;
  53161. }
  53162. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53163. };
  53164. /**
  53165. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53166. */
  53167. GPUParticleSystem.prototype.animate = function () {
  53168. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53169. this._actualFrame += this._timeDelta;
  53170. if (!this._stopped) {
  53171. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53172. this.stop();
  53173. }
  53174. }
  53175. };
  53176. /**
  53177. * Renders the particle system in its current state.
  53178. * @returns the current number of particles
  53179. */
  53180. GPUParticleSystem.prototype.render = function () {
  53181. if (!this._started) {
  53182. return 0;
  53183. }
  53184. this._recreateUpdateEffect();
  53185. this._recreateRenderEffect();
  53186. if (!this.isReady()) {
  53187. return 0;
  53188. }
  53189. if (this._currentRenderId === this._scene.getRenderId()) {
  53190. return 0;
  53191. }
  53192. this._currentRenderId = this._scene.getRenderId();
  53193. // Get everything ready to render
  53194. this._initialize();
  53195. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53196. // Enable update effect
  53197. this._engine.enableEffect(this._updateEffect);
  53198. this._engine.setState(false);
  53199. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53200. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53201. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53202. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53203. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53204. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53205. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53206. this._updateEffect.setDirectColor4("color1", this.color1);
  53207. this._updateEffect.setDirectColor4("color2", this.color2);
  53208. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53209. this._updateEffect.setVector3("gravity", this.gravity);
  53210. if (this.particleEmitterType) {
  53211. this.particleEmitterType.applyToShader(this._updateEffect);
  53212. }
  53213. var emitterWM;
  53214. if (this.emitter.position) {
  53215. var emitterMesh = this.emitter;
  53216. emitterWM = emitterMesh.getWorldMatrix();
  53217. }
  53218. else {
  53219. var emitterPosition = this.emitter;
  53220. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53221. }
  53222. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53223. // Bind source VAO
  53224. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53225. // Update
  53226. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53227. this._engine.setRasterizerState(false);
  53228. this._engine.beginTransformFeedback();
  53229. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53230. this._engine.endTransformFeedback();
  53231. this._engine.setRasterizerState(true);
  53232. this._engine.bindTransformFeedbackBuffer(null);
  53233. // Enable render effect
  53234. this._engine.enableEffect(this._renderEffect);
  53235. var viewMatrix = this._scene.getViewMatrix();
  53236. this._renderEffect.setMatrix("view", viewMatrix);
  53237. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53238. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53239. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53240. if (this._scene.clipPlane) {
  53241. var clipPlane = this._scene.clipPlane;
  53242. var invView = viewMatrix.clone();
  53243. invView.invert();
  53244. this._renderEffect.setMatrix("invView", invView);
  53245. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53246. }
  53247. // Draw order
  53248. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53249. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53250. }
  53251. else {
  53252. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53253. }
  53254. if (this.forceDepthWrite) {
  53255. this._engine.setDepthWrite(true);
  53256. }
  53257. // Bind source VAO
  53258. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53259. // Render
  53260. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53261. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53262. // Switch VAOs
  53263. this._targetIndex++;
  53264. if (this._targetIndex === 2) {
  53265. this._targetIndex = 0;
  53266. }
  53267. // Switch buffers
  53268. var tmpBuffer = this._sourceBuffer;
  53269. this._sourceBuffer = this._targetBuffer;
  53270. this._targetBuffer = tmpBuffer;
  53271. return this._currentActiveCount;
  53272. };
  53273. /**
  53274. * Rebuilds the particle system
  53275. */
  53276. GPUParticleSystem.prototype.rebuild = function () {
  53277. this._initialize(true);
  53278. };
  53279. GPUParticleSystem.prototype._releaseBuffers = function () {
  53280. if (this._buffer0) {
  53281. this._buffer0.dispose();
  53282. this._buffer0 = null;
  53283. }
  53284. if (this._buffer1) {
  53285. this._buffer1.dispose();
  53286. this._buffer1 = null;
  53287. }
  53288. if (this._spriteBuffer) {
  53289. this._spriteBuffer.dispose();
  53290. this._spriteBuffer = null;
  53291. }
  53292. };
  53293. GPUParticleSystem.prototype._releaseVAOs = function () {
  53294. if (!this._updateVAO) {
  53295. return;
  53296. }
  53297. for (var index = 0; index < this._updateVAO.length; index++) {
  53298. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53299. }
  53300. this._updateVAO = [];
  53301. for (var index = 0; index < this._renderVAO.length; index++) {
  53302. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53303. }
  53304. this._renderVAO = [];
  53305. };
  53306. /**
  53307. * Disposes the particle system and free the associated resources
  53308. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53309. */
  53310. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53311. if (disposeTexture === void 0) { disposeTexture = true; }
  53312. var index = this._scene.particleSystems.indexOf(this);
  53313. if (index > -1) {
  53314. this._scene.particleSystems.splice(index, 1);
  53315. }
  53316. this._releaseBuffers();
  53317. this._releaseVAOs();
  53318. if (this._randomTexture) {
  53319. this._randomTexture.dispose();
  53320. this._randomTexture = null;
  53321. }
  53322. if (disposeTexture && this.particleTexture) {
  53323. this.particleTexture.dispose();
  53324. this.particleTexture = null;
  53325. }
  53326. // Callback
  53327. this.onDisposeObservable.notifyObservers(this);
  53328. this.onDisposeObservable.clear();
  53329. };
  53330. /**
  53331. * Clones the particle system.
  53332. * @param name The name of the cloned object
  53333. * @param newEmitter The new emitter to use
  53334. * @returns the cloned particle system
  53335. */
  53336. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53337. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53338. BABYLON.Tools.DeepCopy(this, result);
  53339. if (newEmitter === undefined) {
  53340. newEmitter = this.emitter;
  53341. }
  53342. result.emitter = newEmitter;
  53343. if (this.particleTexture) {
  53344. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53345. }
  53346. return result;
  53347. };
  53348. /**
  53349. * Serializes the particle system to a JSON object.
  53350. * @returns the JSON object
  53351. */
  53352. GPUParticleSystem.prototype.serialize = function () {
  53353. var serializationObject = {};
  53354. serializationObject.name = this.name;
  53355. serializationObject.id = this.id;
  53356. // Emitter
  53357. if (this.emitter.position) {
  53358. var emitterMesh = this.emitter;
  53359. serializationObject.emitterId = emitterMesh.id;
  53360. }
  53361. else {
  53362. var emitterPosition = this.emitter;
  53363. serializationObject.emitter = emitterPosition.asArray();
  53364. }
  53365. serializationObject.capacity = this.getCapacity();
  53366. if (this.particleTexture) {
  53367. serializationObject.textureName = this.particleTexture.name;
  53368. }
  53369. // Animations
  53370. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53371. // Particle system
  53372. serializationObject.activeParticleCount = this.activeParticleCount;
  53373. serializationObject.randomTextureSize = this._randomTextureSize;
  53374. serializationObject.minSize = this.minSize;
  53375. serializationObject.maxSize = this.maxSize;
  53376. serializationObject.minEmitPower = this.minEmitPower;
  53377. serializationObject.maxEmitPower = this.maxEmitPower;
  53378. serializationObject.minLifeTime = this.minLifeTime;
  53379. serializationObject.maxLifeTime = this.maxLifeTime;
  53380. serializationObject.emitRate = this.emitRate;
  53381. serializationObject.gravity = this.gravity.asArray();
  53382. serializationObject.color1 = this.color1.asArray();
  53383. serializationObject.color2 = this.color2.asArray();
  53384. serializationObject.colorDead = this.colorDead.asArray();
  53385. serializationObject.updateSpeed = this.updateSpeed;
  53386. serializationObject.targetStopDuration = this.targetStopDuration;
  53387. serializationObject.blendMode = this.blendMode;
  53388. // Emitter
  53389. if (this.particleEmitterType) {
  53390. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53391. }
  53392. return serializationObject;
  53393. };
  53394. /**
  53395. * Parses a JSON object to create a GPU particle system.
  53396. * @param parsedParticleSystem The JSON object to parse
  53397. * @param scene The scene to create the particle system in
  53398. * @param rootUrl The root url to use to load external dependencies like texture
  53399. * @returns the parsed GPU particle system
  53400. */
  53401. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53402. var name = parsedParticleSystem.name;
  53403. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53404. if (parsedParticleSystem.id) {
  53405. particleSystem.id = parsedParticleSystem.id;
  53406. }
  53407. // Texture
  53408. if (parsedParticleSystem.textureName) {
  53409. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53410. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53411. }
  53412. // Emitter
  53413. if (parsedParticleSystem.emitterId) {
  53414. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53415. }
  53416. else {
  53417. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53418. }
  53419. // Animations
  53420. if (parsedParticleSystem.animations) {
  53421. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53422. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53423. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53424. }
  53425. }
  53426. // Particle system
  53427. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53428. particleSystem.minSize = parsedParticleSystem.minSize;
  53429. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53430. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53431. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53432. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53433. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53434. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53435. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53436. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53437. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53438. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53439. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53440. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53441. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53442. // Emitter
  53443. if (parsedParticleSystem.particleEmitterType) {
  53444. var emitterType = void 0;
  53445. switch (parsedParticleSystem.particleEmitterType.type) {
  53446. case "SphereEmitter":
  53447. emitterType = new BABYLON.SphereParticleEmitter();
  53448. break;
  53449. case "SphereDirectedParticleEmitter":
  53450. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53451. break;
  53452. case "ConeEmitter":
  53453. emitterType = new BABYLON.ConeParticleEmitter();
  53454. break;
  53455. case "BoxEmitter":
  53456. default:
  53457. emitterType = new BABYLON.BoxParticleEmitter();
  53458. break;
  53459. }
  53460. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53461. particleSystem.particleEmitterType = emitterType;
  53462. }
  53463. return particleSystem;
  53464. };
  53465. return GPUParticleSystem;
  53466. }());
  53467. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53468. })(BABYLON || (BABYLON = {}));
  53469. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53470. var BABYLON;
  53471. (function (BABYLON) {
  53472. /**
  53473. * Represents one particle of a solid particle system.
  53474. * @see SolidParticleSystem
  53475. */
  53476. var SolidParticle = /** @class */ (function () {
  53477. /**
  53478. * Creates a Solid Particle object.
  53479. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53480. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53481. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53482. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53483. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53484. * @param shapeId (integer) is the model shape identifier in the SPS.
  53485. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53486. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53487. */
  53488. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53489. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53490. /**
  53491. * particle global index
  53492. */
  53493. this.idx = 0;
  53494. /**
  53495. * The color of the particle
  53496. */
  53497. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53498. /**
  53499. * The world space position of the particle.
  53500. */
  53501. this.position = BABYLON.Vector3.Zero();
  53502. /**
  53503. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53504. */
  53505. this.rotation = BABYLON.Vector3.Zero();
  53506. /**
  53507. * The scaling of the particle.
  53508. */
  53509. this.scaling = BABYLON.Vector3.One();
  53510. /**
  53511. * The uvs of the particle.
  53512. */
  53513. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53514. /**
  53515. * The current speed of the particle.
  53516. */
  53517. this.velocity = BABYLON.Vector3.Zero();
  53518. /**
  53519. * The pivot point in the particle local space.
  53520. */
  53521. this.pivot = BABYLON.Vector3.Zero();
  53522. /**
  53523. * Must the particle be translated from its pivot point in its local space ?
  53524. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53525. * Default : false
  53526. */
  53527. this.translateFromPivot = false;
  53528. /**
  53529. * Is the particle active or not ?
  53530. */
  53531. this.alive = true;
  53532. /**
  53533. * Is the particle visible or not ?
  53534. */
  53535. this.isVisible = true;
  53536. /**
  53537. * Index of this particle in the global "positions" array (Internal use)
  53538. */
  53539. this._pos = 0;
  53540. /**
  53541. * Index of this particle in the global "indices" array (Internal use)
  53542. */
  53543. this._ind = 0;
  53544. /**
  53545. * ModelShape id of this particle
  53546. */
  53547. this.shapeId = 0;
  53548. /**
  53549. * Index of the particle in its shape id (Internal use)
  53550. */
  53551. this.idxInShape = 0;
  53552. /**
  53553. * Still set as invisible in order to skip useless computations (Internal use)
  53554. */
  53555. this._stillInvisible = false;
  53556. /**
  53557. * Last computed particle rotation matrix
  53558. */
  53559. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53560. /**
  53561. * Parent particle Id, if any.
  53562. * Default null.
  53563. */
  53564. this.parentId = null;
  53565. /**
  53566. * Internal global position in the SPS.
  53567. */
  53568. this._globalPosition = BABYLON.Vector3.Zero();
  53569. this.idx = particleIndex;
  53570. this._pos = positionIndex;
  53571. this._ind = indiceIndex;
  53572. this._model = model;
  53573. this.shapeId = shapeId;
  53574. this.idxInShape = idxInShape;
  53575. this._sps = sps;
  53576. if (modelBoundingInfo) {
  53577. this._modelBoundingInfo = modelBoundingInfo;
  53578. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53579. }
  53580. }
  53581. Object.defineProperty(SolidParticle.prototype, "scale", {
  53582. /**
  53583. * Legacy support, changed scale to scaling
  53584. */
  53585. get: function () {
  53586. return this.scaling;
  53587. },
  53588. /**
  53589. * Legacy support, changed scale to scaling
  53590. */
  53591. set: function (scale) {
  53592. this.scaling = scale;
  53593. },
  53594. enumerable: true,
  53595. configurable: true
  53596. });
  53597. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53598. /**
  53599. * Legacy support, changed quaternion to rotationQuaternion
  53600. */
  53601. get: function () {
  53602. return this.rotationQuaternion;
  53603. },
  53604. /**
  53605. * Legacy support, changed quaternion to rotationQuaternion
  53606. */
  53607. set: function (q) {
  53608. this.rotationQuaternion = q;
  53609. },
  53610. enumerable: true,
  53611. configurable: true
  53612. });
  53613. /**
  53614. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53615. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53616. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53617. * @returns true if it intersects
  53618. */
  53619. SolidParticle.prototype.intersectsMesh = function (target) {
  53620. if (!this._boundingInfo || !target._boundingInfo) {
  53621. return false;
  53622. }
  53623. if (this._sps._bSphereOnly) {
  53624. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53625. }
  53626. return this._boundingInfo.intersects(target._boundingInfo, false);
  53627. };
  53628. return SolidParticle;
  53629. }());
  53630. BABYLON.SolidParticle = SolidParticle;
  53631. /**
  53632. * Represents the shape of the model used by one particle of a solid particle system.
  53633. * SPS internal tool, don't use it manually.
  53634. * @see SolidParticleSystem
  53635. */
  53636. var ModelShape = /** @class */ (function () {
  53637. /**
  53638. * 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.
  53639. * SPS internal tool, don't use it manually.
  53640. * @ignore
  53641. */
  53642. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53643. /**
  53644. * length of the shape in the model indices array (internal use)
  53645. */
  53646. this._indicesLength = 0;
  53647. this.shapeID = id;
  53648. this._shape = shape;
  53649. this._indicesLength = indicesLength;
  53650. this._shapeUV = shapeUV;
  53651. this._positionFunction = posFunction;
  53652. this._vertexFunction = vtxFunction;
  53653. }
  53654. return ModelShape;
  53655. }());
  53656. BABYLON.ModelShape = ModelShape;
  53657. /**
  53658. * Represents a Depth Sorted Particle in the solid particle system.
  53659. * @see SolidParticleSystem
  53660. */
  53661. var DepthSortedParticle = /** @class */ (function () {
  53662. function DepthSortedParticle() {
  53663. /**
  53664. * Index of the particle in the "indices" array
  53665. */
  53666. this.ind = 0;
  53667. /**
  53668. * Length of the particle shape in the "indices" array
  53669. */
  53670. this.indicesLength = 0;
  53671. /**
  53672. * Squared distance from the particle to the camera
  53673. */
  53674. this.sqDistance = 0.0;
  53675. }
  53676. return DepthSortedParticle;
  53677. }());
  53678. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53679. })(BABYLON || (BABYLON = {}));
  53680. //# sourceMappingURL=babylon.solidParticle.js.map
  53681. var BABYLON;
  53682. (function (BABYLON) {
  53683. /**
  53684. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53685. *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.
  53686. * The SPS is also a particle system. It provides some methods to manage the particles.
  53687. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53688. *
  53689. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53690. */
  53691. var SolidParticleSystem = /** @class */ (function () {
  53692. /**
  53693. * Creates a SPS (Solid Particle System) object.
  53694. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53695. * @param scene (Scene) is the scene in which the SPS is added.
  53696. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53697. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53698. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53699. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53700. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53701. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53702. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53703. */
  53704. function SolidParticleSystem(name, scene, options) {
  53705. /**
  53706. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53707. * Example : var p = SPS.particles[i];
  53708. */
  53709. this.particles = new Array();
  53710. /**
  53711. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53712. */
  53713. this.nbParticles = 0;
  53714. /**
  53715. * If the particles must ever face the camera (default false). Useful for planar particles.
  53716. */
  53717. this.billboard = false;
  53718. /**
  53719. * Recompute normals when adding a shape
  53720. */
  53721. this.recomputeNormals = true;
  53722. /**
  53723. * This a counter ofr your own usage. It's not set by any SPS functions.
  53724. */
  53725. this.counter = 0;
  53726. /**
  53727. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53728. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53729. */
  53730. this.vars = {};
  53731. /**
  53732. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53733. */
  53734. this._bSphereOnly = false;
  53735. /**
  53736. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53737. */
  53738. this._bSphereRadiusFactor = 1.0;
  53739. this._positions = new Array();
  53740. this._indices = new Array();
  53741. this._normals = new Array();
  53742. this._colors = new Array();
  53743. this._uvs = new Array();
  53744. this._index = 0; // indices index
  53745. this._updatable = true;
  53746. this._pickable = false;
  53747. this._isVisibilityBoxLocked = false;
  53748. this._alwaysVisible = false;
  53749. this._depthSort = false;
  53750. this._shapeCounter = 0;
  53751. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53752. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53753. this._computeParticleColor = true;
  53754. this._computeParticleTexture = true;
  53755. this._computeParticleRotation = true;
  53756. this._computeParticleVertex = false;
  53757. this._computeBoundingBox = false;
  53758. this._depthSortParticles = true;
  53759. this._cam_axisZ = BABYLON.Vector3.Zero();
  53760. this._cam_axisY = BABYLON.Vector3.Zero();
  53761. this._cam_axisX = BABYLON.Vector3.Zero();
  53762. this._axisZ = BABYLON.Axis.Z;
  53763. this._camDir = BABYLON.Vector3.Zero();
  53764. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53765. this._rotMatrix = new BABYLON.Matrix();
  53766. this._invertMatrix = new BABYLON.Matrix();
  53767. this._rotated = BABYLON.Vector3.Zero();
  53768. this._quaternion = new BABYLON.Quaternion();
  53769. this._vertex = BABYLON.Vector3.Zero();
  53770. this._normal = BABYLON.Vector3.Zero();
  53771. this._yaw = 0.0;
  53772. this._pitch = 0.0;
  53773. this._roll = 0.0;
  53774. this._halfroll = 0.0;
  53775. this._halfpitch = 0.0;
  53776. this._halfyaw = 0.0;
  53777. this._sinRoll = 0.0;
  53778. this._cosRoll = 0.0;
  53779. this._sinPitch = 0.0;
  53780. this._cosPitch = 0.0;
  53781. this._sinYaw = 0.0;
  53782. this._cosYaw = 0.0;
  53783. this._mustUnrotateFixedNormals = false;
  53784. this._minimum = BABYLON.Vector3.Zero();
  53785. this._maximum = BABYLON.Vector3.Zero();
  53786. this._minBbox = BABYLON.Vector3.Zero();
  53787. this._maxBbox = BABYLON.Vector3.Zero();
  53788. this._particlesIntersect = false;
  53789. this._depthSortFunction = function (p1, p2) {
  53790. return (p2.sqDistance - p1.sqDistance);
  53791. };
  53792. this._needs32Bits = false;
  53793. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53794. this._scaledPivot = BABYLON.Vector3.Zero();
  53795. this._particleHasParent = false;
  53796. this.name = name;
  53797. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53798. this._camera = scene.activeCamera;
  53799. this._pickable = options ? options.isPickable : false;
  53800. this._depthSort = options ? options.enableDepthSort : false;
  53801. this._particlesIntersect = options ? options.particleIntersection : false;
  53802. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53803. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53804. if (options && options.updatable) {
  53805. this._updatable = options.updatable;
  53806. }
  53807. else {
  53808. this._updatable = true;
  53809. }
  53810. if (this._pickable) {
  53811. this.pickedParticles = [];
  53812. }
  53813. if (this._depthSort) {
  53814. this.depthSortedParticles = [];
  53815. }
  53816. }
  53817. /**
  53818. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53819. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53820. * @returns the created mesh
  53821. */
  53822. SolidParticleSystem.prototype.buildMesh = function () {
  53823. if (this.nbParticles === 0) {
  53824. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53825. this.addShape(triangle, 1);
  53826. triangle.dispose();
  53827. }
  53828. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53829. this._positions32 = new Float32Array(this._positions);
  53830. this._uvs32 = new Float32Array(this._uvs);
  53831. this._colors32 = new Float32Array(this._colors);
  53832. if (this.recomputeNormals) {
  53833. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53834. }
  53835. this._normals32 = new Float32Array(this._normals);
  53836. this._fixedNormal32 = new Float32Array(this._normals);
  53837. if (this._mustUnrotateFixedNormals) {
  53838. this._unrotateFixedNormals();
  53839. }
  53840. var vertexData = new BABYLON.VertexData();
  53841. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53842. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53843. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53844. if (this._uvs32) {
  53845. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53846. ;
  53847. }
  53848. if (this._colors32) {
  53849. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53850. }
  53851. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53852. vertexData.applyToMesh(mesh, this._updatable);
  53853. this.mesh = mesh;
  53854. this.mesh.isPickable = this._pickable;
  53855. // free memory
  53856. if (!this._depthSort) {
  53857. this._indices = null;
  53858. }
  53859. this._positions = null;
  53860. this._normals = null;
  53861. this._uvs = null;
  53862. this._colors = null;
  53863. if (!this._updatable) {
  53864. this.particles.length = 0;
  53865. }
  53866. return mesh;
  53867. };
  53868. /**
  53869. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53870. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53871. * Thus the particles generated from `digest()` have their property `position` set yet.
  53872. * @param mesh ( Mesh ) is the mesh to be digested
  53873. * @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
  53874. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53875. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53876. * @returns the current SPS
  53877. */
  53878. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53879. var size = (options && options.facetNb) || 1;
  53880. var number = (options && options.number) || 0;
  53881. var delta = (options && options.delta) || 0;
  53882. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53883. var meshInd = mesh.getIndices();
  53884. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53885. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53886. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53887. var f = 0; // facet counter
  53888. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53889. // compute size from number
  53890. if (number) {
  53891. number = (number > totalFacets) ? totalFacets : number;
  53892. size = Math.round(totalFacets / number);
  53893. delta = 0;
  53894. }
  53895. else {
  53896. size = (size > totalFacets) ? totalFacets : size;
  53897. }
  53898. var facetPos = []; // submesh positions
  53899. var facetInd = []; // submesh indices
  53900. var facetUV = []; // submesh UV
  53901. var facetCol = []; // submesh colors
  53902. var barycenter = BABYLON.Vector3.Zero();
  53903. var sizeO = size;
  53904. while (f < totalFacets) {
  53905. size = sizeO + Math.floor((1 + delta) * Math.random());
  53906. if (f > totalFacets - size) {
  53907. size = totalFacets - f;
  53908. }
  53909. // reset temp arrays
  53910. facetPos.length = 0;
  53911. facetInd.length = 0;
  53912. facetUV.length = 0;
  53913. facetCol.length = 0;
  53914. // iterate over "size" facets
  53915. var fi = 0;
  53916. for (var j = f * 3; j < (f + size) * 3; j++) {
  53917. facetInd.push(fi);
  53918. var i = meshInd[j];
  53919. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53920. if (meshUV) {
  53921. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53922. }
  53923. if (meshCol) {
  53924. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53925. }
  53926. fi++;
  53927. }
  53928. // create a model shape for each single particle
  53929. var idx = this.nbParticles;
  53930. var shape = this._posToShape(facetPos);
  53931. var shapeUV = this._uvsToShapeUV(facetUV);
  53932. // compute the barycenter of the shape
  53933. var v;
  53934. for (v = 0; v < shape.length; v++) {
  53935. barycenter.addInPlace(shape[v]);
  53936. }
  53937. barycenter.scaleInPlace(1 / shape.length);
  53938. // shift the shape from its barycenter to the origin
  53939. for (v = 0; v < shape.length; v++) {
  53940. shape[v].subtractInPlace(barycenter);
  53941. }
  53942. var bInfo;
  53943. if (this._particlesIntersect) {
  53944. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53945. }
  53946. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53947. // add the particle in the SPS
  53948. var currentPos = this._positions.length;
  53949. var currentInd = this._indices.length;
  53950. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53951. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53952. // initialize the particle position
  53953. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53954. this._index += shape.length;
  53955. idx++;
  53956. this.nbParticles++;
  53957. this._shapeCounter++;
  53958. f += size;
  53959. }
  53960. return this;
  53961. };
  53962. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53963. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53964. var index = 0;
  53965. var idx = 0;
  53966. for (var p = 0; p < this.particles.length; p++) {
  53967. this._particle = this.particles[p];
  53968. this._shape = this._particle._model._shape;
  53969. if (this._particle.rotationQuaternion) {
  53970. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53971. }
  53972. else {
  53973. this._yaw = this._particle.rotation.y;
  53974. this._pitch = this._particle.rotation.x;
  53975. this._roll = this._particle.rotation.z;
  53976. this._quaternionRotationYPR();
  53977. }
  53978. this._quaternionToRotationMatrix();
  53979. this._rotMatrix.invertToRef(this._invertMatrix);
  53980. for (var pt = 0; pt < this._shape.length; pt++) {
  53981. idx = index + pt * 3;
  53982. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53983. this._fixedNormal32[idx] = this._normal.x;
  53984. this._fixedNormal32[idx + 1] = this._normal.y;
  53985. this._fixedNormal32[idx + 2] = this._normal.z;
  53986. }
  53987. index = idx + 3;
  53988. }
  53989. };
  53990. //reset copy
  53991. SolidParticleSystem.prototype._resetCopy = function () {
  53992. this._copy.position.x = 0;
  53993. this._copy.position.y = 0;
  53994. this._copy.position.z = 0;
  53995. this._copy.rotation.x = 0;
  53996. this._copy.rotation.y = 0;
  53997. this._copy.rotation.z = 0;
  53998. this._copy.rotationQuaternion = null;
  53999. this._copy.scaling.x = 1.0;
  54000. this._copy.scaling.y = 1.0;
  54001. this._copy.scaling.z = 1.0;
  54002. this._copy.uvs.x = 0;
  54003. this._copy.uvs.y = 0;
  54004. this._copy.uvs.z = 1.0;
  54005. this._copy.uvs.w = 1.0;
  54006. this._copy.color = null;
  54007. this._copy.translateFromPivot = false;
  54008. };
  54009. // _meshBuilder : inserts the shape model in the global SPS mesh
  54010. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54011. var i;
  54012. var u = 0;
  54013. var c = 0;
  54014. var n = 0;
  54015. this._resetCopy();
  54016. if (options && options.positionFunction) {
  54017. options.positionFunction(this._copy, idx, idxInShape);
  54018. this._mustUnrotateFixedNormals = true;
  54019. }
  54020. if (this._copy.rotationQuaternion) {
  54021. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54022. }
  54023. else {
  54024. this._yaw = this._copy.rotation.y;
  54025. this._pitch = this._copy.rotation.x;
  54026. this._roll = this._copy.rotation.z;
  54027. this._quaternionRotationYPR();
  54028. }
  54029. this._quaternionToRotationMatrix();
  54030. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54031. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54032. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54033. if (this._copy.translateFromPivot) {
  54034. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54035. }
  54036. else {
  54037. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54038. }
  54039. for (i = 0; i < shape.length; i++) {
  54040. this._vertex.x = shape[i].x;
  54041. this._vertex.y = shape[i].y;
  54042. this._vertex.z = shape[i].z;
  54043. if (options && options.vertexFunction) {
  54044. options.vertexFunction(this._copy, this._vertex, i);
  54045. }
  54046. this._vertex.x *= this._copy.scaling.x;
  54047. this._vertex.y *= this._copy.scaling.y;
  54048. this._vertex.z *= this._copy.scaling.z;
  54049. this._vertex.x -= this._scaledPivot.x;
  54050. this._vertex.y -= this._scaledPivot.y;
  54051. this._vertex.z -= this._scaledPivot.z;
  54052. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54053. this._rotated.addInPlace(this._pivotBackTranslation);
  54054. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54055. if (meshUV) {
  54056. 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);
  54057. u += 2;
  54058. }
  54059. if (this._copy.color) {
  54060. this._color = this._copy.color;
  54061. }
  54062. else if (meshCol && meshCol[c] !== undefined) {
  54063. this._color.r = meshCol[c];
  54064. this._color.g = meshCol[c + 1];
  54065. this._color.b = meshCol[c + 2];
  54066. this._color.a = meshCol[c + 3];
  54067. }
  54068. else {
  54069. this._color.r = 1.0;
  54070. this._color.g = 1.0;
  54071. this._color.b = 1.0;
  54072. this._color.a = 1.0;
  54073. }
  54074. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54075. c += 4;
  54076. if (!this.recomputeNormals && meshNor) {
  54077. this._normal.x = meshNor[n];
  54078. this._normal.y = meshNor[n + 1];
  54079. this._normal.z = meshNor[n + 2];
  54080. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54081. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54082. n += 3;
  54083. }
  54084. }
  54085. for (i = 0; i < meshInd.length; i++) {
  54086. var current_ind = p + meshInd[i];
  54087. indices.push(current_ind);
  54088. if (current_ind > 65535) {
  54089. this._needs32Bits = true;
  54090. }
  54091. }
  54092. if (this._pickable) {
  54093. var nbfaces = meshInd.length / 3;
  54094. for (i = 0; i < nbfaces; i++) {
  54095. this.pickedParticles.push({ idx: idx, faceId: i });
  54096. }
  54097. }
  54098. if (this._depthSort) {
  54099. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54100. }
  54101. return this._copy;
  54102. };
  54103. // returns a shape array from positions array
  54104. SolidParticleSystem.prototype._posToShape = function (positions) {
  54105. var shape = [];
  54106. for (var i = 0; i < positions.length; i += 3) {
  54107. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54108. }
  54109. return shape;
  54110. };
  54111. // returns a shapeUV array from a Vector4 uvs
  54112. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54113. var shapeUV = [];
  54114. if (uvs) {
  54115. for (var i = 0; i < uvs.length; i++)
  54116. shapeUV.push(uvs[i]);
  54117. }
  54118. return shapeUV;
  54119. };
  54120. // adds a new particle object in the particles array
  54121. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54122. if (bInfo === void 0) { bInfo = null; }
  54123. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54124. this.particles.push(sp);
  54125. return sp;
  54126. };
  54127. /**
  54128. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54129. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54130. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54131. * @param nb (positive integer) the number of particles to be created from this model
  54132. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54133. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54134. * @returns the number of shapes in the system
  54135. */
  54136. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54137. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54138. var meshInd = mesh.getIndices();
  54139. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54140. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54141. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54142. var bbInfo;
  54143. if (this._particlesIntersect) {
  54144. bbInfo = mesh.getBoundingInfo();
  54145. }
  54146. var shape = this._posToShape(meshPos);
  54147. var shapeUV = this._uvsToShapeUV(meshUV);
  54148. var posfunc = options ? options.positionFunction : null;
  54149. var vtxfunc = options ? options.vertexFunction : null;
  54150. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54151. // particles
  54152. var sp;
  54153. var currentCopy;
  54154. var idx = this.nbParticles;
  54155. for (var i = 0; i < nb; i++) {
  54156. var currentPos = this._positions.length;
  54157. var currentInd = this._indices.length;
  54158. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54159. if (this._updatable) {
  54160. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54161. sp.position.copyFrom(currentCopy.position);
  54162. sp.rotation.copyFrom(currentCopy.rotation);
  54163. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54164. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54165. }
  54166. if (currentCopy.color && sp.color) {
  54167. sp.color.copyFrom(currentCopy.color);
  54168. }
  54169. sp.scaling.copyFrom(currentCopy.scaling);
  54170. sp.uvs.copyFrom(currentCopy.uvs);
  54171. }
  54172. this._index += shape.length;
  54173. idx++;
  54174. }
  54175. this.nbParticles += nb;
  54176. this._shapeCounter++;
  54177. return this._shapeCounter - 1;
  54178. };
  54179. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54180. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54181. this._resetCopy();
  54182. if (particle._model._positionFunction) {
  54183. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54184. }
  54185. if (this._copy.rotationQuaternion) {
  54186. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54187. }
  54188. else {
  54189. this._yaw = this._copy.rotation.y;
  54190. this._pitch = this._copy.rotation.x;
  54191. this._roll = this._copy.rotation.z;
  54192. this._quaternionRotationYPR();
  54193. }
  54194. this._quaternionToRotationMatrix();
  54195. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54196. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54197. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54198. if (this._copy.translateFromPivot) {
  54199. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54200. }
  54201. else {
  54202. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54203. }
  54204. this._shape = particle._model._shape;
  54205. for (var pt = 0; pt < this._shape.length; pt++) {
  54206. this._vertex.x = this._shape[pt].x;
  54207. this._vertex.y = this._shape[pt].y;
  54208. this._vertex.z = this._shape[pt].z;
  54209. if (particle._model._vertexFunction) {
  54210. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54211. }
  54212. this._vertex.x *= this._copy.scaling.x;
  54213. this._vertex.y *= this._copy.scaling.y;
  54214. this._vertex.z *= this._copy.scaling.z;
  54215. this._vertex.x -= this._scaledPivot.x;
  54216. this._vertex.y -= this._scaledPivot.y;
  54217. this._vertex.z -= this._scaledPivot.z;
  54218. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54219. this._rotated.addInPlace(this._pivotBackTranslation);
  54220. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54221. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54222. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54223. }
  54224. particle.position.x = 0.0;
  54225. particle.position.y = 0.0;
  54226. particle.position.z = 0.0;
  54227. particle.rotation.x = 0.0;
  54228. particle.rotation.y = 0.0;
  54229. particle.rotation.z = 0.0;
  54230. particle.rotationQuaternion = null;
  54231. particle.scaling.x = 1.0;
  54232. particle.scaling.y = 1.0;
  54233. particle.scaling.z = 1.0;
  54234. particle.uvs.x = 0.0;
  54235. particle.uvs.y = 0.0;
  54236. particle.uvs.z = 1.0;
  54237. particle.uvs.w = 1.0;
  54238. particle.pivot.x = 0.0;
  54239. particle.pivot.y = 0.0;
  54240. particle.pivot.z = 0.0;
  54241. particle.translateFromPivot = false;
  54242. particle.parentId = null;
  54243. };
  54244. /**
  54245. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54246. * @returns the SPS.
  54247. */
  54248. SolidParticleSystem.prototype.rebuildMesh = function () {
  54249. for (var p = 0; p < this.particles.length; p++) {
  54250. this._rebuildParticle(this.particles[p]);
  54251. }
  54252. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54253. return this;
  54254. };
  54255. /**
  54256. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54257. * This method calls `updateParticle()` for each particle of the SPS.
  54258. * For an animated SPS, it is usually called within the render loop.
  54259. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54260. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54261. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54262. * @returns the SPS.
  54263. */
  54264. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54265. if (start === void 0) { start = 0; }
  54266. if (end === void 0) { end = this.nbParticles - 1; }
  54267. if (update === void 0) { update = true; }
  54268. if (!this._updatable) {
  54269. return this;
  54270. }
  54271. // custom beforeUpdate
  54272. this.beforeUpdateParticles(start, end, update);
  54273. this._cam_axisX.x = 1.0;
  54274. this._cam_axisX.y = 0.0;
  54275. this._cam_axisX.z = 0.0;
  54276. this._cam_axisY.x = 0.0;
  54277. this._cam_axisY.y = 1.0;
  54278. this._cam_axisY.z = 0.0;
  54279. this._cam_axisZ.x = 0.0;
  54280. this._cam_axisZ.y = 0.0;
  54281. this._cam_axisZ.z = 1.0;
  54282. // cases when the World Matrix is to be computed first
  54283. if (this.billboard || this._depthSort) {
  54284. this.mesh.computeWorldMatrix(true);
  54285. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54286. }
  54287. // if the particles will always face the camera
  54288. if (this.billboard) {
  54289. // compute the camera position and un-rotate it by the current mesh rotation
  54290. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54291. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54292. this._cam_axisZ.normalize();
  54293. // same for camera up vector extracted from the cam view matrix
  54294. var view = this._camera.getViewMatrix(true);
  54295. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54296. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54297. this._cam_axisY.normalize();
  54298. this._cam_axisX.normalize();
  54299. }
  54300. // if depthSort, compute the camera global position in the mesh local system
  54301. if (this._depthSort) {
  54302. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54303. }
  54304. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54305. var idx = 0; // current position index in the global array positions32
  54306. var index = 0; // position start index in the global array positions32 of the current particle
  54307. var colidx = 0; // current color index in the global array colors32
  54308. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54309. var uvidx = 0; // current uv index in the global array uvs32
  54310. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54311. var pt = 0; // current index in the particle model shape
  54312. if (this.mesh.isFacetDataEnabled) {
  54313. this._computeBoundingBox = true;
  54314. }
  54315. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54316. if (this._computeBoundingBox) {
  54317. if (start == 0 && end == this.nbParticles - 1) {
  54318. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54319. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54320. }
  54321. else {
  54322. if (this.mesh._boundingInfo) {
  54323. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54324. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54325. }
  54326. }
  54327. }
  54328. // particle loop
  54329. index = this.particles[start]._pos;
  54330. var vpos = (index / 3) | 0;
  54331. colorIndex = vpos * 4;
  54332. uvIndex = vpos * 2;
  54333. for (var p = start; p <= end; p++) {
  54334. this._particle = this.particles[p];
  54335. this._shape = this._particle._model._shape;
  54336. this._shapeUV = this._particle._model._shapeUV;
  54337. // call to custom user function to update the particle properties
  54338. this.updateParticle(this._particle);
  54339. // camera-particle distance for depth sorting
  54340. if (this._depthSort && this._depthSortParticles) {
  54341. var dsp = this.depthSortedParticles[p];
  54342. dsp.ind = this._particle._ind;
  54343. dsp.indicesLength = this._particle._model._indicesLength;
  54344. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54345. }
  54346. // skip the computations for inactive or already invisible particles
  54347. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54348. // increment indexes for the next particle
  54349. pt = this._shape.length;
  54350. index += pt * 3;
  54351. colorIndex += pt * 4;
  54352. uvIndex += pt * 2;
  54353. continue;
  54354. }
  54355. if (this._particle.isVisible) {
  54356. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54357. this._particleHasParent = (this._particle.parentId !== null);
  54358. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54359. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54360. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54361. // particle rotation matrix
  54362. if (this.billboard) {
  54363. this._particle.rotation.x = 0.0;
  54364. this._particle.rotation.y = 0.0;
  54365. }
  54366. if (this._computeParticleRotation || this.billboard) {
  54367. if (this._particle.rotationQuaternion) {
  54368. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54369. }
  54370. else {
  54371. this._yaw = this._particle.rotation.y;
  54372. this._pitch = this._particle.rotation.x;
  54373. this._roll = this._particle.rotation.z;
  54374. this._quaternionRotationYPR();
  54375. }
  54376. this._quaternionToRotationMatrix();
  54377. }
  54378. if (this._particleHasParent) {
  54379. this._parent = this.particles[this._particle.parentId];
  54380. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  54381. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  54382. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  54383. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54384. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54385. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54386. if (this._computeParticleRotation || this.billboard) {
  54387. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  54388. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  54389. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  54390. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  54391. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  54392. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  54393. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  54394. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  54395. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  54396. }
  54397. }
  54398. else {
  54399. this._particle._globalPosition.x = this._particle.position.x;
  54400. this._particle._globalPosition.y = this._particle.position.y;
  54401. this._particle._globalPosition.z = this._particle.position.z;
  54402. if (this._computeParticleRotation || this.billboard) {
  54403. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54404. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54405. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54406. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54407. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54408. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54409. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54410. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54411. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54412. }
  54413. }
  54414. if (this._particle.translateFromPivot) {
  54415. this._pivotBackTranslation.x = 0.0;
  54416. this._pivotBackTranslation.y = 0.0;
  54417. this._pivotBackTranslation.z = 0.0;
  54418. }
  54419. else {
  54420. this._pivotBackTranslation.x = this._scaledPivot.x;
  54421. this._pivotBackTranslation.y = this._scaledPivot.y;
  54422. this._pivotBackTranslation.z = this._scaledPivot.z;
  54423. }
  54424. // particle vertex loop
  54425. for (pt = 0; pt < this._shape.length; pt++) {
  54426. idx = index + pt * 3;
  54427. colidx = colorIndex + pt * 4;
  54428. uvidx = uvIndex + pt * 2;
  54429. this._vertex.x = this._shape[pt].x;
  54430. this._vertex.y = this._shape[pt].y;
  54431. this._vertex.z = this._shape[pt].z;
  54432. if (this._computeParticleVertex) {
  54433. this.updateParticleVertex(this._particle, this._vertex, pt);
  54434. }
  54435. // positions
  54436. this._vertex.x *= this._particle.scaling.x;
  54437. this._vertex.y *= this._particle.scaling.y;
  54438. this._vertex.z *= this._particle.scaling.z;
  54439. this._vertex.x -= this._scaledPivot.x;
  54440. this._vertex.y -= this._scaledPivot.y;
  54441. this._vertex.z -= this._scaledPivot.z;
  54442. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54443. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54444. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54445. this._rotated.x += this._pivotBackTranslation.x;
  54446. this._rotated.y += this._pivotBackTranslation.y;
  54447. this._rotated.z += this._pivotBackTranslation.z;
  54448. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54449. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  54450. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  54451. if (this._computeBoundingBox) {
  54452. if (this._positions32[idx] < this._minimum.x) {
  54453. this._minimum.x = this._positions32[idx];
  54454. }
  54455. if (this._positions32[idx] > this._maximum.x) {
  54456. this._maximum.x = this._positions32[idx];
  54457. }
  54458. if (this._positions32[idx + 1] < this._minimum.y) {
  54459. this._minimum.y = this._positions32[idx + 1];
  54460. }
  54461. if (this._positions32[idx + 1] > this._maximum.y) {
  54462. this._maximum.y = this._positions32[idx + 1];
  54463. }
  54464. if (this._positions32[idx + 2] < this._minimum.z) {
  54465. this._minimum.z = this._positions32[idx + 2];
  54466. }
  54467. if (this._positions32[idx + 2] > this._maximum.z) {
  54468. this._maximum.z = this._positions32[idx + 2];
  54469. }
  54470. }
  54471. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54472. if (!this._computeParticleVertex) {
  54473. this._normal.x = this._fixedNormal32[idx];
  54474. this._normal.y = this._fixedNormal32[idx + 1];
  54475. this._normal.z = this._fixedNormal32[idx + 2];
  54476. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54477. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54478. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54479. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54480. 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;
  54481. 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;
  54482. }
  54483. if (this._computeParticleColor && this._particle.color) {
  54484. this._colors32[colidx] = this._particle.color.r;
  54485. this._colors32[colidx + 1] = this._particle.color.g;
  54486. this._colors32[colidx + 2] = this._particle.color.b;
  54487. this._colors32[colidx + 3] = this._particle.color.a;
  54488. }
  54489. if (this._computeParticleTexture) {
  54490. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54491. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54492. }
  54493. }
  54494. }
  54495. else {
  54496. this._particle._stillInvisible = true; // mark the particle as invisible
  54497. for (pt = 0; pt < this._shape.length; pt++) {
  54498. idx = index + pt * 3;
  54499. colidx = colorIndex + pt * 4;
  54500. uvidx = uvIndex + pt * 2;
  54501. this._positions32[idx] = 0.0;
  54502. this._positions32[idx + 1] = 0.0;
  54503. this._positions32[idx + 2] = 0.0;
  54504. this._normals32[idx] = 0.0;
  54505. this._normals32[idx + 1] = 0.0;
  54506. this._normals32[idx + 2] = 0.0;
  54507. if (this._computeParticleColor && this._particle.color) {
  54508. this._colors32[colidx] = this._particle.color.r;
  54509. this._colors32[colidx + 1] = this._particle.color.g;
  54510. this._colors32[colidx + 2] = this._particle.color.b;
  54511. this._colors32[colidx + 3] = this._particle.color.a;
  54512. }
  54513. if (this._computeParticleTexture) {
  54514. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54515. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54516. }
  54517. }
  54518. }
  54519. // if the particle intersections must be computed : update the bbInfo
  54520. if (this._particlesIntersect) {
  54521. var bInfo = this._particle._boundingInfo;
  54522. var bBox = bInfo.boundingBox;
  54523. var bSphere = bInfo.boundingSphere;
  54524. if (!this._bSphereOnly) {
  54525. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54526. for (var b = 0; b < bBox.vectors.length; b++) {
  54527. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54528. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54529. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54530. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54531. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54532. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54533. 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;
  54534. 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;
  54535. 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;
  54536. }
  54537. bBox._update(this.mesh._worldMatrix);
  54538. }
  54539. // place and scale the particle bouding sphere in the SPS local system, then update it
  54540. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54541. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54542. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54543. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54544. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54545. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54546. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54547. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54548. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54549. 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));
  54550. bSphere._update(this.mesh._worldMatrix);
  54551. }
  54552. // increment indexes for the next particle
  54553. index = idx + 3;
  54554. colorIndex = colidx + 4;
  54555. uvIndex = uvidx + 2;
  54556. }
  54557. // if the VBO must be updated
  54558. if (update) {
  54559. if (this._computeParticleColor) {
  54560. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54561. }
  54562. if (this._computeParticleTexture) {
  54563. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54564. }
  54565. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54566. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54567. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54568. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54569. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54570. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54571. for (var i = 0; i < this._normals32.length; i++) {
  54572. this._fixedNormal32[i] = this._normals32[i];
  54573. }
  54574. }
  54575. if (!this.mesh.areNormalsFrozen) {
  54576. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54577. }
  54578. }
  54579. if (this._depthSort && this._depthSortParticles) {
  54580. this.depthSortedParticles.sort(this._depthSortFunction);
  54581. var dspl = this.depthSortedParticles.length;
  54582. var sorted = 0;
  54583. var lind = 0;
  54584. var sind = 0;
  54585. var sid = 0;
  54586. for (sorted = 0; sorted < dspl; sorted++) {
  54587. lind = this.depthSortedParticles[sorted].indicesLength;
  54588. sind = this.depthSortedParticles[sorted].ind;
  54589. for (var i = 0; i < lind; i++) {
  54590. this._indices32[sid] = this._indices[sind + i];
  54591. sid++;
  54592. }
  54593. }
  54594. this.mesh.updateIndices(this._indices32);
  54595. }
  54596. }
  54597. if (this._computeBoundingBox) {
  54598. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54599. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54600. }
  54601. this.afterUpdateParticles(start, end, update);
  54602. return this;
  54603. };
  54604. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54605. this._halfroll = this._roll * 0.5;
  54606. this._halfpitch = this._pitch * 0.5;
  54607. this._halfyaw = this._yaw * 0.5;
  54608. this._sinRoll = Math.sin(this._halfroll);
  54609. this._cosRoll = Math.cos(this._halfroll);
  54610. this._sinPitch = Math.sin(this._halfpitch);
  54611. this._cosPitch = Math.cos(this._halfpitch);
  54612. this._sinYaw = Math.sin(this._halfyaw);
  54613. this._cosYaw = Math.cos(this._halfyaw);
  54614. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54615. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54616. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54617. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54618. };
  54619. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54620. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54621. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54622. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54623. this._rotMatrix.m[3] = 0;
  54624. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54625. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54626. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54627. this._rotMatrix.m[7] = 0;
  54628. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54629. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54630. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54631. this._rotMatrix.m[11] = 0;
  54632. this._rotMatrix.m[12] = 0;
  54633. this._rotMatrix.m[13] = 0;
  54634. this._rotMatrix.m[14] = 0;
  54635. this._rotMatrix.m[15] = 1.0;
  54636. };
  54637. /**
  54638. * Disposes the SPS.
  54639. */
  54640. SolidParticleSystem.prototype.dispose = function () {
  54641. this.mesh.dispose();
  54642. this.vars = null;
  54643. // drop references to internal big arrays for the GC
  54644. this._positions = null;
  54645. this._indices = null;
  54646. this._normals = null;
  54647. this._uvs = null;
  54648. this._colors = null;
  54649. this._indices32 = null;
  54650. this._positions32 = null;
  54651. this._normals32 = null;
  54652. this._fixedNormal32 = null;
  54653. this._uvs32 = null;
  54654. this._colors32 = null;
  54655. this.pickedParticles = null;
  54656. };
  54657. /**
  54658. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54659. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54660. * @returns the SPS.
  54661. */
  54662. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54663. if (!this._isVisibilityBoxLocked) {
  54664. this.mesh.refreshBoundingInfo();
  54665. }
  54666. return this;
  54667. };
  54668. /**
  54669. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54670. * @param size the size (float) of the visibility box
  54671. * note : this doesn't lock the SPS mesh bounding box.
  54672. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54673. */
  54674. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54675. var vis = size / 2;
  54676. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54677. };
  54678. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54679. /**
  54680. * Gets whether the SPS as always visible or not
  54681. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54682. */
  54683. get: function () {
  54684. return this._alwaysVisible;
  54685. },
  54686. /**
  54687. * Sets the SPS as always visible or not
  54688. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54689. */
  54690. set: function (val) {
  54691. this._alwaysVisible = val;
  54692. this.mesh.alwaysSelectAsActiveMesh = val;
  54693. },
  54694. enumerable: true,
  54695. configurable: true
  54696. });
  54697. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54698. /**
  54699. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54700. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54701. */
  54702. get: function () {
  54703. return this._isVisibilityBoxLocked;
  54704. },
  54705. /**
  54706. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54707. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54708. */
  54709. set: function (val) {
  54710. this._isVisibilityBoxLocked = val;
  54711. var boundingInfo = this.mesh.getBoundingInfo();
  54712. boundingInfo.isLocked = val;
  54713. },
  54714. enumerable: true,
  54715. configurable: true
  54716. });
  54717. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54718. /**
  54719. * Gets if `setParticles()` computes the particle rotations or not.
  54720. * Default value : true. The SPS is faster when it's set to false.
  54721. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54722. */
  54723. get: function () {
  54724. return this._computeParticleRotation;
  54725. },
  54726. /**
  54727. * Tells to `setParticles()` to compute the particle rotations or not.
  54728. * Default value : true. The SPS is faster when it's set to false.
  54729. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54730. */
  54731. set: function (val) {
  54732. this._computeParticleRotation = val;
  54733. },
  54734. enumerable: true,
  54735. configurable: true
  54736. });
  54737. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54738. /**
  54739. * Gets if `setParticles()` computes the particle colors or not.
  54740. * Default value : true. The SPS is faster when it's set to false.
  54741. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54742. */
  54743. get: function () {
  54744. return this._computeParticleColor;
  54745. },
  54746. /**
  54747. * Tells to `setParticles()` to compute the particle colors or not.
  54748. * Default value : true. The SPS is faster when it's set to false.
  54749. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54750. */
  54751. set: function (val) {
  54752. this._computeParticleColor = val;
  54753. },
  54754. enumerable: true,
  54755. configurable: true
  54756. });
  54757. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54758. /**
  54759. * Gets if `setParticles()` computes the particle textures or not.
  54760. * Default value : true. The SPS is faster when it's set to false.
  54761. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54762. */
  54763. get: function () {
  54764. return this._computeParticleTexture;
  54765. },
  54766. set: function (val) {
  54767. this._computeParticleTexture = val;
  54768. },
  54769. enumerable: true,
  54770. configurable: true
  54771. });
  54772. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54773. /**
  54774. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54775. * Default value : false. The SPS is faster when it's set to false.
  54776. * Note : the particle custom vertex positions aren't stored values.
  54777. */
  54778. get: function () {
  54779. return this._computeParticleVertex;
  54780. },
  54781. /**
  54782. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54783. * Default value : false. The SPS is faster when it's set to false.
  54784. * Note : the particle custom vertex positions aren't stored values.
  54785. */
  54786. set: function (val) {
  54787. this._computeParticleVertex = val;
  54788. },
  54789. enumerable: true,
  54790. configurable: true
  54791. });
  54792. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54793. /**
  54794. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54795. */
  54796. get: function () {
  54797. return this._computeBoundingBox;
  54798. },
  54799. /**
  54800. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54801. */
  54802. set: function (val) {
  54803. this._computeBoundingBox = val;
  54804. },
  54805. enumerable: true,
  54806. configurable: true
  54807. });
  54808. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54809. /**
  54810. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54811. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54812. * Default : `true`
  54813. */
  54814. get: function () {
  54815. return this._depthSortParticles;
  54816. },
  54817. /**
  54818. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54819. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54820. * Default : `true`
  54821. */
  54822. set: function (val) {
  54823. this._depthSortParticles = val;
  54824. },
  54825. enumerable: true,
  54826. configurable: true
  54827. });
  54828. // =======================================================================
  54829. // Particle behavior logic
  54830. // these following methods may be overwritten by the user to fit his needs
  54831. /**
  54832. * This function does nothing. It may be overwritten to set all the particle first values.
  54833. * The SPS doesn't call this function, you may have to call it by your own.
  54834. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54835. */
  54836. SolidParticleSystem.prototype.initParticles = function () {
  54837. };
  54838. /**
  54839. * This function does nothing. It may be overwritten to recycle a particle.
  54840. * The SPS doesn't call this function, you may have to call it by your own.
  54841. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54842. * @param particle The particle to recycle
  54843. * @returns the recycled particle
  54844. */
  54845. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54846. return particle;
  54847. };
  54848. /**
  54849. * Updates a particle : this function should be overwritten by the user.
  54850. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54851. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54852. * @example : just set a particle position or velocity and recycle conditions
  54853. * @param particle The particle to update
  54854. * @returns the updated particle
  54855. */
  54856. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54857. return particle;
  54858. };
  54859. /**
  54860. * Updates a vertex of a particle : it can be overwritten by the user.
  54861. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54862. * @param particle the current particle
  54863. * @param vertex the current index of the current particle
  54864. * @param pt the index of the current vertex in the particle shape
  54865. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54866. * @example : just set a vertex particle position
  54867. * @returns the updated vertex
  54868. */
  54869. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54870. return vertex;
  54871. };
  54872. /**
  54873. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54874. * This does nothing and may be overwritten by the user.
  54875. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54876. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54877. * @param update the boolean update value actually passed to setParticles()
  54878. */
  54879. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54880. };
  54881. /**
  54882. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54883. * This will be passed three parameters.
  54884. * This does nothing and may be overwritten by the user.
  54885. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54886. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54887. * @param update the boolean update value actually passed to setParticles()
  54888. */
  54889. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54890. };
  54891. return SolidParticleSystem;
  54892. }());
  54893. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54894. })(BABYLON || (BABYLON = {}));
  54895. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54896. var BABYLON;
  54897. (function (BABYLON) {
  54898. var ShaderMaterial = /** @class */ (function (_super) {
  54899. __extends(ShaderMaterial, _super);
  54900. function ShaderMaterial(name, scene, shaderPath, options) {
  54901. var _this = _super.call(this, name, scene) || this;
  54902. _this._textures = {};
  54903. _this._textureArrays = {};
  54904. _this._floats = {};
  54905. _this._ints = {};
  54906. _this._floatsArrays = {};
  54907. _this._colors3 = {};
  54908. _this._colors3Arrays = {};
  54909. _this._colors4 = {};
  54910. _this._vectors2 = {};
  54911. _this._vectors3 = {};
  54912. _this._vectors4 = {};
  54913. _this._matrices = {};
  54914. _this._matrices3x3 = {};
  54915. _this._matrices2x2 = {};
  54916. _this._vectors2Arrays = {};
  54917. _this._vectors3Arrays = {};
  54918. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54919. _this._shaderPath = shaderPath;
  54920. options.needAlphaBlending = options.needAlphaBlending || false;
  54921. options.needAlphaTesting = options.needAlphaTesting || false;
  54922. options.attributes = options.attributes || ["position", "normal", "uv"];
  54923. options.uniforms = options.uniforms || ["worldViewProjection"];
  54924. options.uniformBuffers = options.uniformBuffers || [];
  54925. options.samplers = options.samplers || [];
  54926. options.defines = options.defines || [];
  54927. _this._options = options;
  54928. return _this;
  54929. }
  54930. ShaderMaterial.prototype.getClassName = function () {
  54931. return "ShaderMaterial";
  54932. };
  54933. ShaderMaterial.prototype.needAlphaBlending = function () {
  54934. return this._options.needAlphaBlending;
  54935. };
  54936. ShaderMaterial.prototype.needAlphaTesting = function () {
  54937. return this._options.needAlphaTesting;
  54938. };
  54939. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54940. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54941. this._options.uniforms.push(uniformName);
  54942. }
  54943. };
  54944. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54945. if (this._options.samplers.indexOf(name) === -1) {
  54946. this._options.samplers.push(name);
  54947. }
  54948. this._textures[name] = texture;
  54949. return this;
  54950. };
  54951. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54952. if (this._options.samplers.indexOf(name) === -1) {
  54953. this._options.samplers.push(name);
  54954. }
  54955. this._checkUniform(name);
  54956. this._textureArrays[name] = textures;
  54957. return this;
  54958. };
  54959. ShaderMaterial.prototype.setFloat = function (name, value) {
  54960. this._checkUniform(name);
  54961. this._floats[name] = value;
  54962. return this;
  54963. };
  54964. ShaderMaterial.prototype.setInt = function (name, value) {
  54965. this._checkUniform(name);
  54966. this._ints[name] = value;
  54967. return this;
  54968. };
  54969. ShaderMaterial.prototype.setFloats = function (name, value) {
  54970. this._checkUniform(name);
  54971. this._floatsArrays[name] = value;
  54972. return this;
  54973. };
  54974. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54975. this._checkUniform(name);
  54976. this._colors3[name] = value;
  54977. return this;
  54978. };
  54979. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54980. this._checkUniform(name);
  54981. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54982. color.toArray(arr, arr.length);
  54983. return arr;
  54984. }, []);
  54985. return this;
  54986. };
  54987. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54988. this._checkUniform(name);
  54989. this._colors4[name] = value;
  54990. return this;
  54991. };
  54992. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54993. this._checkUniform(name);
  54994. this._vectors2[name] = value;
  54995. return this;
  54996. };
  54997. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54998. this._checkUniform(name);
  54999. this._vectors3[name] = value;
  55000. return this;
  55001. };
  55002. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55003. this._checkUniform(name);
  55004. this._vectors4[name] = value;
  55005. return this;
  55006. };
  55007. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55008. this._checkUniform(name);
  55009. this._matrices[name] = value;
  55010. return this;
  55011. };
  55012. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55013. this._checkUniform(name);
  55014. this._matrices3x3[name] = value;
  55015. return this;
  55016. };
  55017. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55018. this._checkUniform(name);
  55019. this._matrices2x2[name] = value;
  55020. return this;
  55021. };
  55022. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55023. this._checkUniform(name);
  55024. this._vectors2Arrays[name] = value;
  55025. return this;
  55026. };
  55027. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55028. this._checkUniform(name);
  55029. this._vectors3Arrays[name] = value;
  55030. return this;
  55031. };
  55032. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55033. if (!mesh) {
  55034. return true;
  55035. }
  55036. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55037. return false;
  55038. }
  55039. return false;
  55040. };
  55041. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55042. var scene = this.getScene();
  55043. var engine = scene.getEngine();
  55044. if (!this.checkReadyOnEveryCall) {
  55045. if (this._renderId === scene.getRenderId()) {
  55046. if (this._checkCache(scene, mesh, useInstances)) {
  55047. return true;
  55048. }
  55049. }
  55050. }
  55051. // Instances
  55052. var defines = [];
  55053. var attribs = [];
  55054. var fallbacks = new BABYLON.EffectFallbacks();
  55055. if (useInstances) {
  55056. defines.push("#define INSTANCES");
  55057. }
  55058. for (var index = 0; index < this._options.defines.length; index++) {
  55059. defines.push(this._options.defines[index]);
  55060. }
  55061. for (var index = 0; index < this._options.attributes.length; index++) {
  55062. attribs.push(this._options.attributes[index]);
  55063. }
  55064. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55065. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55066. defines.push("#define VERTEXCOLOR");
  55067. }
  55068. // Bones
  55069. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55070. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55071. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55072. if (mesh.numBoneInfluencers > 4) {
  55073. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55074. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55075. }
  55076. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55077. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55078. fallbacks.addCPUSkinningFallback(0, mesh);
  55079. if (this._options.uniforms.indexOf("mBones") === -1) {
  55080. this._options.uniforms.push("mBones");
  55081. }
  55082. }
  55083. else {
  55084. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55085. }
  55086. // Textures
  55087. for (var name in this._textures) {
  55088. if (!this._textures[name].isReady()) {
  55089. return false;
  55090. }
  55091. }
  55092. // Alpha test
  55093. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55094. defines.push("#define ALPHATEST");
  55095. }
  55096. var previousEffect = this._effect;
  55097. var join = defines.join("\n");
  55098. this._effect = engine.createEffect(this._shaderPath, {
  55099. attributes: attribs,
  55100. uniformsNames: this._options.uniforms,
  55101. uniformBuffersNames: this._options.uniformBuffers,
  55102. samplers: this._options.samplers,
  55103. defines: join,
  55104. fallbacks: fallbacks,
  55105. onCompiled: this.onCompiled,
  55106. onError: this.onError
  55107. }, engine);
  55108. if (!this._effect.isReady()) {
  55109. return false;
  55110. }
  55111. if (previousEffect !== this._effect) {
  55112. scene.resetCachedMaterial();
  55113. }
  55114. this._renderId = scene.getRenderId();
  55115. return true;
  55116. };
  55117. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55118. var scene = this.getScene();
  55119. if (!this._effect) {
  55120. return;
  55121. }
  55122. if (this._options.uniforms.indexOf("world") !== -1) {
  55123. this._effect.setMatrix("world", world);
  55124. }
  55125. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55126. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55127. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55128. }
  55129. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55130. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55131. }
  55132. };
  55133. ShaderMaterial.prototype.bind = function (world, mesh) {
  55134. // Std values
  55135. this.bindOnlyWorldMatrix(world);
  55136. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55137. if (this._options.uniforms.indexOf("view") !== -1) {
  55138. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55139. }
  55140. if (this._options.uniforms.indexOf("projection") !== -1) {
  55141. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55142. }
  55143. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55144. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55145. }
  55146. // Bones
  55147. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55148. var name;
  55149. // Texture
  55150. for (name in this._textures) {
  55151. this._effect.setTexture(name, this._textures[name]);
  55152. }
  55153. // Texture arrays
  55154. for (name in this._textureArrays) {
  55155. this._effect.setTextureArray(name, this._textureArrays[name]);
  55156. }
  55157. // Int
  55158. for (name in this._ints) {
  55159. this._effect.setInt(name, this._ints[name]);
  55160. }
  55161. // Float
  55162. for (name in this._floats) {
  55163. this._effect.setFloat(name, this._floats[name]);
  55164. }
  55165. // Floats
  55166. for (name in this._floatsArrays) {
  55167. this._effect.setArray(name, this._floatsArrays[name]);
  55168. }
  55169. // Color3
  55170. for (name in this._colors3) {
  55171. this._effect.setColor3(name, this._colors3[name]);
  55172. }
  55173. for (name in this._colors3Arrays) {
  55174. this._effect.setArray3(name, this._colors3Arrays[name]);
  55175. }
  55176. // Color4
  55177. for (name in this._colors4) {
  55178. var color = this._colors4[name];
  55179. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55180. }
  55181. // Vector2
  55182. for (name in this._vectors2) {
  55183. this._effect.setVector2(name, this._vectors2[name]);
  55184. }
  55185. // Vector3
  55186. for (name in this._vectors3) {
  55187. this._effect.setVector3(name, this._vectors3[name]);
  55188. }
  55189. // Vector4
  55190. for (name in this._vectors4) {
  55191. this._effect.setVector4(name, this._vectors4[name]);
  55192. }
  55193. // Matrix
  55194. for (name in this._matrices) {
  55195. this._effect.setMatrix(name, this._matrices[name]);
  55196. }
  55197. // Matrix 3x3
  55198. for (name in this._matrices3x3) {
  55199. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55200. }
  55201. // Matrix 2x2
  55202. for (name in this._matrices2x2) {
  55203. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55204. }
  55205. // Vector2Array
  55206. for (name in this._vectors2Arrays) {
  55207. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55208. }
  55209. // Vector3Array
  55210. for (name in this._vectors3Arrays) {
  55211. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55212. }
  55213. }
  55214. this._afterBind(mesh);
  55215. };
  55216. ShaderMaterial.prototype.getActiveTextures = function () {
  55217. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55218. for (var name in this._textures) {
  55219. activeTextures.push(this._textures[name]);
  55220. }
  55221. for (var name in this._textureArrays) {
  55222. var array = this._textureArrays[name];
  55223. for (var index = 0; index < array.length; index++) {
  55224. activeTextures.push(array[index]);
  55225. }
  55226. }
  55227. return activeTextures;
  55228. };
  55229. ShaderMaterial.prototype.hasTexture = function (texture) {
  55230. if (_super.prototype.hasTexture.call(this, texture)) {
  55231. return true;
  55232. }
  55233. for (var name in this._textures) {
  55234. if (this._textures[name] === texture) {
  55235. return true;
  55236. }
  55237. }
  55238. for (var name in this._textureArrays) {
  55239. var array = this._textureArrays[name];
  55240. for (var index = 0; index < array.length; index++) {
  55241. if (array[index] === texture) {
  55242. return true;
  55243. }
  55244. }
  55245. }
  55246. return false;
  55247. };
  55248. ShaderMaterial.prototype.clone = function (name) {
  55249. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55250. return newShaderMaterial;
  55251. };
  55252. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55253. if (forceDisposeTextures) {
  55254. var name;
  55255. for (name in this._textures) {
  55256. this._textures[name].dispose();
  55257. }
  55258. for (name in this._textureArrays) {
  55259. var array = this._textureArrays[name];
  55260. for (var index = 0; index < array.length; index++) {
  55261. array[index].dispose();
  55262. }
  55263. }
  55264. }
  55265. this._textures = {};
  55266. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55267. };
  55268. ShaderMaterial.prototype.serialize = function () {
  55269. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55270. serializationObject.customType = "BABYLON.ShaderMaterial";
  55271. serializationObject.options = this._options;
  55272. serializationObject.shaderPath = this._shaderPath;
  55273. var name;
  55274. // Texture
  55275. serializationObject.textures = {};
  55276. for (name in this._textures) {
  55277. serializationObject.textures[name] = this._textures[name].serialize();
  55278. }
  55279. // Texture arrays
  55280. serializationObject.textureArrays = {};
  55281. for (name in this._textureArrays) {
  55282. serializationObject.textureArrays[name] = [];
  55283. var array = this._textureArrays[name];
  55284. for (var index = 0; index < array.length; index++) {
  55285. serializationObject.textureArrays[name].push(array[index].serialize());
  55286. }
  55287. }
  55288. // Float
  55289. serializationObject.floats = {};
  55290. for (name in this._floats) {
  55291. serializationObject.floats[name] = this._floats[name];
  55292. }
  55293. // Float s
  55294. serializationObject.FloatArrays = {};
  55295. for (name in this._floatsArrays) {
  55296. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55297. }
  55298. // Color3
  55299. serializationObject.colors3 = {};
  55300. for (name in this._colors3) {
  55301. serializationObject.colors3[name] = this._colors3[name].asArray();
  55302. }
  55303. // Color3 array
  55304. serializationObject.colors3Arrays = {};
  55305. for (name in this._colors3Arrays) {
  55306. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55307. }
  55308. // Color4
  55309. serializationObject.colors4 = {};
  55310. for (name in this._colors4) {
  55311. serializationObject.colors4[name] = this._colors4[name].asArray();
  55312. }
  55313. // Vector2
  55314. serializationObject.vectors2 = {};
  55315. for (name in this._vectors2) {
  55316. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55317. }
  55318. // Vector3
  55319. serializationObject.vectors3 = {};
  55320. for (name in this._vectors3) {
  55321. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55322. }
  55323. // Vector4
  55324. serializationObject.vectors4 = {};
  55325. for (name in this._vectors4) {
  55326. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55327. }
  55328. // Matrix
  55329. serializationObject.matrices = {};
  55330. for (name in this._matrices) {
  55331. serializationObject.matrices[name] = this._matrices[name].asArray();
  55332. }
  55333. // Matrix 3x3
  55334. serializationObject.matrices3x3 = {};
  55335. for (name in this._matrices3x3) {
  55336. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55337. }
  55338. // Matrix 2x2
  55339. serializationObject.matrices2x2 = {};
  55340. for (name in this._matrices2x2) {
  55341. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55342. }
  55343. // Vector2Array
  55344. serializationObject.vectors2Arrays = {};
  55345. for (name in this._vectors2Arrays) {
  55346. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55347. }
  55348. // Vector3Array
  55349. serializationObject.vectors3Arrays = {};
  55350. for (name in this._vectors3Arrays) {
  55351. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55352. }
  55353. return serializationObject;
  55354. };
  55355. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55356. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55357. var name;
  55358. // Texture
  55359. for (name in source.textures) {
  55360. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55361. }
  55362. // Texture arrays
  55363. for (name in source.textureArrays) {
  55364. var array = source.textureArrays[name];
  55365. var textureArray = new Array();
  55366. for (var index = 0; index < array.length; index++) {
  55367. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55368. }
  55369. material.setTextureArray(name, textureArray);
  55370. }
  55371. // Float
  55372. for (name in source.floats) {
  55373. material.setFloat(name, source.floats[name]);
  55374. }
  55375. // Float s
  55376. for (name in source.floatsArrays) {
  55377. material.setFloats(name, source.floatsArrays[name]);
  55378. }
  55379. // Color3
  55380. for (name in source.colors3) {
  55381. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55382. }
  55383. // Color3 arrays
  55384. for (name in source.colors3Arrays) {
  55385. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55386. if (i % 3 === 0) {
  55387. arr.push([num]);
  55388. }
  55389. else {
  55390. arr[arr.length - 1].push(num);
  55391. }
  55392. return arr;
  55393. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55394. material.setColor3Array(name, colors);
  55395. }
  55396. // Color4
  55397. for (name in source.colors4) {
  55398. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55399. }
  55400. // Vector2
  55401. for (name in source.vectors2) {
  55402. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55403. }
  55404. // Vector3
  55405. for (name in source.vectors3) {
  55406. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55407. }
  55408. // Vector4
  55409. for (name in source.vectors4) {
  55410. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55411. }
  55412. // Matrix
  55413. for (name in source.matrices) {
  55414. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55415. }
  55416. // Matrix 3x3
  55417. for (name in source.matrices3x3) {
  55418. material.setMatrix3x3(name, source.matrices3x3[name]);
  55419. }
  55420. // Matrix 2x2
  55421. for (name in source.matrices2x2) {
  55422. material.setMatrix2x2(name, source.matrices2x2[name]);
  55423. }
  55424. // Vector2Array
  55425. for (name in source.vectors2Arrays) {
  55426. material.setArray2(name, source.vectors2Arrays[name]);
  55427. }
  55428. // Vector3Array
  55429. for (name in source.vectors3Arrays) {
  55430. material.setArray3(name, source.vectors3Arrays[name]);
  55431. }
  55432. return material;
  55433. };
  55434. return ShaderMaterial;
  55435. }(BABYLON.Material));
  55436. BABYLON.ShaderMaterial = ShaderMaterial;
  55437. })(BABYLON || (BABYLON = {}));
  55438. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55439. var BABYLON;
  55440. (function (BABYLON) {
  55441. var GroundMesh = /** @class */ (function (_super) {
  55442. __extends(GroundMesh, _super);
  55443. function GroundMesh(name, scene) {
  55444. var _this = _super.call(this, name, scene) || this;
  55445. _this.generateOctree = false;
  55446. return _this;
  55447. }
  55448. GroundMesh.prototype.getClassName = function () {
  55449. return "GroundMesh";
  55450. };
  55451. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55452. get: function () {
  55453. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55454. },
  55455. enumerable: true,
  55456. configurable: true
  55457. });
  55458. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55459. get: function () {
  55460. return this._subdivisionsX;
  55461. },
  55462. enumerable: true,
  55463. configurable: true
  55464. });
  55465. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55466. get: function () {
  55467. return this._subdivisionsY;
  55468. },
  55469. enumerable: true,
  55470. configurable: true
  55471. });
  55472. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55473. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55474. this._subdivisionsX = chunksCount;
  55475. this._subdivisionsY = chunksCount;
  55476. this.subdivide(chunksCount);
  55477. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55478. };
  55479. /**
  55480. * Returns a height (y) value in the Worl system :
  55481. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55482. * Returns the ground y position if (x, z) are outside the ground surface.
  55483. */
  55484. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55485. var world = this.getWorldMatrix();
  55486. var invMat = BABYLON.Tmp.Matrix[5];
  55487. world.invertToRef(invMat);
  55488. var tmpVect = BABYLON.Tmp.Vector3[8];
  55489. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55490. x = tmpVect.x;
  55491. z = tmpVect.z;
  55492. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55493. return this.position.y;
  55494. }
  55495. if (!this._heightQuads || this._heightQuads.length == 0) {
  55496. this._initHeightQuads();
  55497. this._computeHeightQuads();
  55498. }
  55499. var facet = this._getFacetAt(x, z);
  55500. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55501. // return y in the World system
  55502. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55503. return tmpVect.y;
  55504. };
  55505. /**
  55506. * Returns a normalized vector (Vector3) orthogonal to the ground
  55507. * at the ground coordinates (x, z) expressed in the World system.
  55508. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55509. */
  55510. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55511. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55512. this.getNormalAtCoordinatesToRef(x, z, normal);
  55513. return normal;
  55514. };
  55515. /**
  55516. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55517. * at the ground coordinates (x, z) expressed in the World system.
  55518. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55519. * Returns the GroundMesh.
  55520. */
  55521. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55522. var world = this.getWorldMatrix();
  55523. var tmpMat = BABYLON.Tmp.Matrix[5];
  55524. world.invertToRef(tmpMat);
  55525. var tmpVect = BABYLON.Tmp.Vector3[8];
  55526. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55527. x = tmpVect.x;
  55528. z = tmpVect.z;
  55529. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55530. return this;
  55531. }
  55532. if (!this._heightQuads || this._heightQuads.length == 0) {
  55533. this._initHeightQuads();
  55534. this._computeHeightQuads();
  55535. }
  55536. var facet = this._getFacetAt(x, z);
  55537. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55538. return this;
  55539. };
  55540. /**
  55541. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55542. * if the ground has been updated.
  55543. * This can be used in the render loop.
  55544. * Returns the GroundMesh.
  55545. */
  55546. GroundMesh.prototype.updateCoordinateHeights = function () {
  55547. if (!this._heightQuads || this._heightQuads.length == 0) {
  55548. this._initHeightQuads();
  55549. }
  55550. this._computeHeightQuads();
  55551. return this;
  55552. };
  55553. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55554. GroundMesh.prototype._getFacetAt = function (x, z) {
  55555. // retrieve col and row from x, z coordinates in the ground local system
  55556. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55557. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55558. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55559. var facet;
  55560. if (z < quad.slope.x * x + quad.slope.y) {
  55561. facet = quad.facet1;
  55562. }
  55563. else {
  55564. facet = quad.facet2;
  55565. }
  55566. return facet;
  55567. };
  55568. // Creates and populates the heightMap array with "facet" elements :
  55569. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55570. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55571. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55572. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55573. // Returns the GroundMesh.
  55574. GroundMesh.prototype._initHeightQuads = function () {
  55575. var subdivisionsX = this._subdivisionsX;
  55576. var subdivisionsY = this._subdivisionsY;
  55577. this._heightQuads = new Array();
  55578. for (var row = 0; row < subdivisionsY; row++) {
  55579. for (var col = 0; col < subdivisionsX; col++) {
  55580. 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) };
  55581. this._heightQuads[row * subdivisionsX + col] = quad;
  55582. }
  55583. }
  55584. return this;
  55585. };
  55586. // Compute each quad element values and update the the heightMap array :
  55587. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55588. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55589. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55590. // Returns the GroundMesh.
  55591. GroundMesh.prototype._computeHeightQuads = function () {
  55592. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55593. if (!positions) {
  55594. return this;
  55595. }
  55596. var v1 = BABYLON.Tmp.Vector3[3];
  55597. var v2 = BABYLON.Tmp.Vector3[2];
  55598. var v3 = BABYLON.Tmp.Vector3[1];
  55599. var v4 = BABYLON.Tmp.Vector3[0];
  55600. var v1v2 = BABYLON.Tmp.Vector3[4];
  55601. var v1v3 = BABYLON.Tmp.Vector3[5];
  55602. var v1v4 = BABYLON.Tmp.Vector3[6];
  55603. var norm1 = BABYLON.Tmp.Vector3[7];
  55604. var norm2 = BABYLON.Tmp.Vector3[8];
  55605. var i = 0;
  55606. var j = 0;
  55607. var k = 0;
  55608. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55609. var h = 0;
  55610. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55611. var d2 = 0;
  55612. var subdivisionsX = this._subdivisionsX;
  55613. var subdivisionsY = this._subdivisionsY;
  55614. for (var row = 0; row < subdivisionsY; row++) {
  55615. for (var col = 0; col < subdivisionsX; col++) {
  55616. i = col * 3;
  55617. j = row * (subdivisionsX + 1) * 3;
  55618. k = (row + 1) * (subdivisionsX + 1) * 3;
  55619. v1.x = positions[j + i];
  55620. v1.y = positions[j + i + 1];
  55621. v1.z = positions[j + i + 2];
  55622. v2.x = positions[j + i + 3];
  55623. v2.y = positions[j + i + 4];
  55624. v2.z = positions[j + i + 5];
  55625. v3.x = positions[k + i];
  55626. v3.y = positions[k + i + 1];
  55627. v3.z = positions[k + i + 2];
  55628. v4.x = positions[k + i + 3];
  55629. v4.y = positions[k + i + 4];
  55630. v4.z = positions[k + i + 5];
  55631. // 2D slope V1V4
  55632. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55633. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55634. // facet equations :
  55635. // we compute each facet normal vector
  55636. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55637. // we compute the value d by applying the equation to v1 which belongs to the plane
  55638. // then we store the facet equation in a Vector4
  55639. v2.subtractToRef(v1, v1v2);
  55640. v3.subtractToRef(v1, v1v3);
  55641. v4.subtractToRef(v1, v1v4);
  55642. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55643. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55644. norm1.normalize();
  55645. norm2.normalize();
  55646. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55647. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55648. var quad = this._heightQuads[row * subdivisionsX + col];
  55649. quad.slope.copyFromFloats(cd, h);
  55650. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55651. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55652. }
  55653. }
  55654. return this;
  55655. };
  55656. GroundMesh.prototype.serialize = function (serializationObject) {
  55657. _super.prototype.serialize.call(this, serializationObject);
  55658. serializationObject.subdivisionsX = this._subdivisionsX;
  55659. serializationObject.subdivisionsY = this._subdivisionsY;
  55660. serializationObject.minX = this._minX;
  55661. serializationObject.maxX = this._maxX;
  55662. serializationObject.minZ = this._minZ;
  55663. serializationObject.maxZ = this._maxZ;
  55664. serializationObject.width = this._width;
  55665. serializationObject.height = this._height;
  55666. };
  55667. GroundMesh.Parse = function (parsedMesh, scene) {
  55668. var result = new GroundMesh(parsedMesh.name, scene);
  55669. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55670. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55671. result._minX = parsedMesh.minX;
  55672. result._maxX = parsedMesh.maxX;
  55673. result._minZ = parsedMesh.minZ;
  55674. result._maxZ = parsedMesh.maxZ;
  55675. result._width = parsedMesh.width;
  55676. result._height = parsedMesh.height;
  55677. return result;
  55678. };
  55679. return GroundMesh;
  55680. }(BABYLON.Mesh));
  55681. BABYLON.GroundMesh = GroundMesh;
  55682. })(BABYLON || (BABYLON = {}));
  55683. //# sourceMappingURL=babylon.groundMesh.js.map
  55684. var BABYLON;
  55685. (function (BABYLON) {
  55686. /**
  55687. * Creates an instance based on a source mesh.
  55688. */
  55689. var InstancedMesh = /** @class */ (function (_super) {
  55690. __extends(InstancedMesh, _super);
  55691. function InstancedMesh(name, source) {
  55692. var _this = _super.call(this, name, source.getScene()) || this;
  55693. source.instances.push(_this);
  55694. _this._sourceMesh = source;
  55695. _this.position.copyFrom(source.position);
  55696. _this.rotation.copyFrom(source.rotation);
  55697. _this.scaling.copyFrom(source.scaling);
  55698. if (source.rotationQuaternion) {
  55699. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55700. }
  55701. _this.infiniteDistance = source.infiniteDistance;
  55702. _this.setPivotMatrix(source.getPivotMatrix());
  55703. _this.refreshBoundingInfo();
  55704. _this._syncSubMeshes();
  55705. return _this;
  55706. }
  55707. /**
  55708. * Returns the string "InstancedMesh".
  55709. */
  55710. InstancedMesh.prototype.getClassName = function () {
  55711. return "InstancedMesh";
  55712. };
  55713. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55714. // Methods
  55715. get: function () {
  55716. return this._sourceMesh.receiveShadows;
  55717. },
  55718. enumerable: true,
  55719. configurable: true
  55720. });
  55721. Object.defineProperty(InstancedMesh.prototype, "material", {
  55722. get: function () {
  55723. return this._sourceMesh.material;
  55724. },
  55725. enumerable: true,
  55726. configurable: true
  55727. });
  55728. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55729. get: function () {
  55730. return this._sourceMesh.visibility;
  55731. },
  55732. enumerable: true,
  55733. configurable: true
  55734. });
  55735. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55736. get: function () {
  55737. return this._sourceMesh.skeleton;
  55738. },
  55739. enumerable: true,
  55740. configurable: true
  55741. });
  55742. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55743. get: function () {
  55744. return this._sourceMesh.renderingGroupId;
  55745. },
  55746. set: function (value) {
  55747. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55748. return;
  55749. }
  55750. //no-op with warning
  55751. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55752. },
  55753. enumerable: true,
  55754. configurable: true
  55755. });
  55756. /**
  55757. * Returns the total number of vertices (integer).
  55758. */
  55759. InstancedMesh.prototype.getTotalVertices = function () {
  55760. return this._sourceMesh.getTotalVertices();
  55761. };
  55762. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55763. get: function () {
  55764. return this._sourceMesh;
  55765. },
  55766. enumerable: true,
  55767. configurable: true
  55768. });
  55769. /**
  55770. * Is this node ready to be used/rendered
  55771. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55772. * @return {boolean} is it ready
  55773. */
  55774. InstancedMesh.prototype.isReady = function (completeCheck) {
  55775. if (completeCheck === void 0) { completeCheck = false; }
  55776. return this._sourceMesh.isReady(completeCheck, true);
  55777. };
  55778. /**
  55779. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55780. */
  55781. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55782. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55783. };
  55784. /**
  55785. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55786. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55787. * The `data` are either a numeric array either a Float32Array.
  55788. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55789. * 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).
  55790. * Note that a new underlying VertexBuffer object is created each call.
  55791. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55792. *
  55793. * Possible `kind` values :
  55794. * - BABYLON.VertexBuffer.PositionKind
  55795. * - BABYLON.VertexBuffer.UVKind
  55796. * - BABYLON.VertexBuffer.UV2Kind
  55797. * - BABYLON.VertexBuffer.UV3Kind
  55798. * - BABYLON.VertexBuffer.UV4Kind
  55799. * - BABYLON.VertexBuffer.UV5Kind
  55800. * - BABYLON.VertexBuffer.UV6Kind
  55801. * - BABYLON.VertexBuffer.ColorKind
  55802. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55803. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55804. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55805. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55806. *
  55807. * Returns the Mesh.
  55808. */
  55809. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55810. if (this.sourceMesh) {
  55811. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55812. }
  55813. return this.sourceMesh;
  55814. };
  55815. /**
  55816. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55817. * If the mesh has no geometry, it is simply returned as it is.
  55818. * The `data` are either a numeric array either a Float32Array.
  55819. * No new underlying VertexBuffer object is created.
  55820. * 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.
  55821. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55822. *
  55823. * Possible `kind` values :
  55824. * - BABYLON.VertexBuffer.PositionKind
  55825. * - BABYLON.VertexBuffer.UVKind
  55826. * - BABYLON.VertexBuffer.UV2Kind
  55827. * - BABYLON.VertexBuffer.UV3Kind
  55828. * - BABYLON.VertexBuffer.UV4Kind
  55829. * - BABYLON.VertexBuffer.UV5Kind
  55830. * - BABYLON.VertexBuffer.UV6Kind
  55831. * - BABYLON.VertexBuffer.ColorKind
  55832. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55833. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55834. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55835. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55836. *
  55837. * Returns the Mesh.
  55838. */
  55839. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55840. if (this.sourceMesh) {
  55841. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55842. }
  55843. return this.sourceMesh;
  55844. };
  55845. /**
  55846. * Sets the mesh indices.
  55847. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55848. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55849. * This method creates a new index buffer each call.
  55850. * Returns the Mesh.
  55851. */
  55852. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55853. if (totalVertices === void 0) { totalVertices = null; }
  55854. if (this.sourceMesh) {
  55855. this.sourceMesh.setIndices(indices, totalVertices);
  55856. }
  55857. return this.sourceMesh;
  55858. };
  55859. /**
  55860. * Boolean : True if the mesh owns the requested kind of data.
  55861. */
  55862. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55863. return this._sourceMesh.isVerticesDataPresent(kind);
  55864. };
  55865. /**
  55866. * Returns an array of indices (IndicesArray).
  55867. */
  55868. InstancedMesh.prototype.getIndices = function () {
  55869. return this._sourceMesh.getIndices();
  55870. };
  55871. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55872. get: function () {
  55873. return this._sourceMesh._positions;
  55874. },
  55875. enumerable: true,
  55876. configurable: true
  55877. });
  55878. /**
  55879. * Sets a new updated BoundingInfo to the mesh.
  55880. * Returns the mesh.
  55881. */
  55882. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55883. var meshBB = this._sourceMesh.getBoundingInfo();
  55884. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55885. this._updateBoundingInfo();
  55886. return this;
  55887. };
  55888. InstancedMesh.prototype._preActivate = function () {
  55889. if (this._currentLOD) {
  55890. this._currentLOD._preActivate();
  55891. }
  55892. return this;
  55893. };
  55894. InstancedMesh.prototype._activate = function (renderId) {
  55895. if (this._currentLOD) {
  55896. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55897. }
  55898. return this;
  55899. };
  55900. /**
  55901. * Returns the current associated LOD AbstractMesh.
  55902. */
  55903. InstancedMesh.prototype.getLOD = function (camera) {
  55904. if (!camera) {
  55905. return this;
  55906. }
  55907. var boundingInfo = this.getBoundingInfo();
  55908. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55909. if (this._currentLOD === this.sourceMesh) {
  55910. return this;
  55911. }
  55912. return this._currentLOD;
  55913. };
  55914. InstancedMesh.prototype._syncSubMeshes = function () {
  55915. this.releaseSubMeshes();
  55916. if (this._sourceMesh.subMeshes) {
  55917. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55918. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55919. }
  55920. }
  55921. return this;
  55922. };
  55923. InstancedMesh.prototype._generatePointsArray = function () {
  55924. return this._sourceMesh._generatePointsArray();
  55925. };
  55926. /**
  55927. * Creates a new InstancedMesh from the current mesh.
  55928. * - name (string) : the cloned mesh name
  55929. * - newParent (optional Node) : the optional Node to parent the clone to.
  55930. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55931. *
  55932. * Returns the clone.
  55933. */
  55934. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55935. var result = this._sourceMesh.createInstance(name);
  55936. // Deep copy
  55937. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55938. // Bounding info
  55939. this.refreshBoundingInfo();
  55940. // Parent
  55941. if (newParent) {
  55942. result.parent = newParent;
  55943. }
  55944. if (!doNotCloneChildren) {
  55945. // Children
  55946. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55947. var mesh = this.getScene().meshes[index];
  55948. if (mesh.parent === this) {
  55949. mesh.clone(mesh.name, result);
  55950. }
  55951. }
  55952. }
  55953. result.computeWorldMatrix(true);
  55954. return result;
  55955. };
  55956. /**
  55957. * Disposes the InstancedMesh.
  55958. * Returns nothing.
  55959. */
  55960. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55961. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55962. // Remove from mesh
  55963. var index = this._sourceMesh.instances.indexOf(this);
  55964. this._sourceMesh.instances.splice(index, 1);
  55965. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55966. };
  55967. return InstancedMesh;
  55968. }(BABYLON.AbstractMesh));
  55969. BABYLON.InstancedMesh = InstancedMesh;
  55970. })(BABYLON || (BABYLON = {}));
  55971. //# sourceMappingURL=babylon.instancedMesh.js.map
  55972. var BABYLON;
  55973. (function (BABYLON) {
  55974. var LinesMesh = /** @class */ (function (_super) {
  55975. __extends(LinesMesh, _super);
  55976. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55977. if (scene === void 0) { scene = null; }
  55978. if (parent === void 0) { parent = null; }
  55979. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55980. _this.useVertexColor = useVertexColor;
  55981. _this.useVertexAlpha = useVertexAlpha;
  55982. _this.color = new BABYLON.Color3(1, 1, 1);
  55983. _this.alpha = 1;
  55984. if (source) {
  55985. _this.color = source.color.clone();
  55986. _this.alpha = source.alpha;
  55987. _this.useVertexColor = source.useVertexColor;
  55988. _this.useVertexAlpha = source.useVertexAlpha;
  55989. }
  55990. _this._intersectionThreshold = 0.1;
  55991. var defines = [];
  55992. var options = {
  55993. attributes: [BABYLON.VertexBuffer.PositionKind],
  55994. uniforms: ["world", "viewProjection"],
  55995. needAlphaBlending: true,
  55996. defines: defines
  55997. };
  55998. if (useVertexAlpha === false) {
  55999. options.needAlphaBlending = false;
  56000. }
  56001. if (!useVertexColor) {
  56002. options.uniforms.push("color");
  56003. }
  56004. else {
  56005. options.defines.push("#define VERTEXCOLOR");
  56006. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56007. }
  56008. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56009. return _this;
  56010. }
  56011. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56012. /**
  56013. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56014. * This margin is expressed in world space coordinates, so its value may vary.
  56015. * Default value is 0.1
  56016. * @returns the intersection Threshold value.
  56017. */
  56018. get: function () {
  56019. return this._intersectionThreshold;
  56020. },
  56021. /**
  56022. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56023. * This margin is expressed in world space coordinates, so its value may vary.
  56024. * @param value the new threshold to apply
  56025. */
  56026. set: function (value) {
  56027. if (this._intersectionThreshold === value) {
  56028. return;
  56029. }
  56030. this._intersectionThreshold = value;
  56031. if (this.geometry) {
  56032. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56033. }
  56034. },
  56035. enumerable: true,
  56036. configurable: true
  56037. });
  56038. /**
  56039. * Returns the string "LineMesh"
  56040. */
  56041. LinesMesh.prototype.getClassName = function () {
  56042. return "LinesMesh";
  56043. };
  56044. Object.defineProperty(LinesMesh.prototype, "material", {
  56045. get: function () {
  56046. return this._colorShader;
  56047. },
  56048. set: function (value) {
  56049. // Do nothing
  56050. },
  56051. enumerable: true,
  56052. configurable: true
  56053. });
  56054. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56055. get: function () {
  56056. return false;
  56057. },
  56058. enumerable: true,
  56059. configurable: true
  56060. });
  56061. LinesMesh.prototype.createInstance = function (name) {
  56062. throw new Error("LinesMeshes do not support createInstance.");
  56063. };
  56064. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56065. if (!this._geometry) {
  56066. return this;
  56067. }
  56068. // VBOs
  56069. this._geometry._bind(this._colorShader.getEffect());
  56070. // Color
  56071. if (!this.useVertexColor) {
  56072. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56073. }
  56074. return this;
  56075. };
  56076. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56077. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56078. return this;
  56079. }
  56080. var engine = this.getScene().getEngine();
  56081. // Draw order
  56082. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56083. return this;
  56084. };
  56085. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56086. this._colorShader.dispose();
  56087. _super.prototype.dispose.call(this, doNotRecurse);
  56088. };
  56089. /**
  56090. * Returns a new LineMesh object cloned from the current one.
  56091. */
  56092. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56093. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56094. };
  56095. return LinesMesh;
  56096. }(BABYLON.Mesh));
  56097. BABYLON.LinesMesh = LinesMesh;
  56098. })(BABYLON || (BABYLON = {}));
  56099. //# sourceMappingURL=babylon.linesMesh.js.map
  56100. var BABYLON;
  56101. (function (BABYLON) {
  56102. var MeshBuilder = /** @class */ (function () {
  56103. function MeshBuilder() {
  56104. }
  56105. MeshBuilder.updateSideOrientation = function (orientation) {
  56106. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56107. return BABYLON.Mesh.DOUBLESIDE;
  56108. }
  56109. if (orientation === undefined || orientation === null) {
  56110. return BABYLON.Mesh.FRONTSIDE;
  56111. }
  56112. return orientation;
  56113. };
  56114. /**
  56115. * Creates a box mesh.
  56116. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56117. * The parameter `size` sets the size (float) of each box side (default 1).
  56118. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56119. * 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).
  56120. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56121. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56122. * 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).
  56123. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56125. */
  56126. MeshBuilder.CreateBox = function (name, options, scene) {
  56127. if (scene === void 0) { scene = null; }
  56128. var box = new BABYLON.Mesh(name, scene);
  56129. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56130. box._originalBuilderSideOrientation = options.sideOrientation;
  56131. var vertexData = BABYLON.VertexData.CreateBox(options);
  56132. vertexData.applyToMesh(box, options.updatable);
  56133. return box;
  56134. };
  56135. /**
  56136. * Creates a sphere mesh.
  56137. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56138. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56139. * 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`).
  56140. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56141. * 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
  56142. * 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).
  56143. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56144. * 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).
  56145. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56146. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56147. */
  56148. MeshBuilder.CreateSphere = function (name, options, scene) {
  56149. var sphere = new BABYLON.Mesh(name, scene);
  56150. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56151. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56152. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56153. vertexData.applyToMesh(sphere, options.updatable);
  56154. return sphere;
  56155. };
  56156. /**
  56157. * Creates a plane polygonal mesh. By default, this is a disc.
  56158. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56159. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56160. * 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.
  56161. * 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
  56162. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56163. * 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).
  56164. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56166. */
  56167. MeshBuilder.CreateDisc = function (name, options, scene) {
  56168. if (scene === void 0) { scene = null; }
  56169. var disc = new BABYLON.Mesh(name, scene);
  56170. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56171. disc._originalBuilderSideOrientation = options.sideOrientation;
  56172. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56173. vertexData.applyToMesh(disc, options.updatable);
  56174. return disc;
  56175. };
  56176. /**
  56177. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56178. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56179. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56180. * 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`).
  56181. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56182. * 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.
  56183. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56184. * 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).
  56185. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56186. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56187. */
  56188. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56189. var sphere = new BABYLON.Mesh(name, scene);
  56190. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56191. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56192. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56193. vertexData.applyToMesh(sphere, options.updatable);
  56194. return sphere;
  56195. };
  56196. ;
  56197. /**
  56198. * Creates a ribbon mesh.
  56199. * 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.
  56200. *
  56201. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56202. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56203. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56204. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56205. * 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.
  56206. * 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.
  56207. * 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
  56208. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56209. * 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).
  56210. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56211. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56212. * 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.
  56213. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56214. * 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
  56215. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56216. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56218. */
  56219. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56220. if (scene === void 0) { scene = null; }
  56221. var pathArray = options.pathArray;
  56222. var closeArray = options.closeArray;
  56223. var closePath = options.closePath;
  56224. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56225. var instance = options.instance;
  56226. var updatable = options.updatable;
  56227. if (instance) {
  56228. // positionFunction : ribbon case
  56229. // only pathArray and sideOrientation parameters are taken into account for positions update
  56230. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56231. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56232. var positionFunction = function (positions) {
  56233. var minlg = pathArray[0].length;
  56234. var i = 0;
  56235. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56236. for (var si = 1; si <= ns; si++) {
  56237. for (var p = 0; p < pathArray.length; p++) {
  56238. var path = pathArray[p];
  56239. var l = path.length;
  56240. minlg = (minlg < l) ? minlg : l;
  56241. var j = 0;
  56242. while (j < minlg) {
  56243. positions[i] = path[j].x;
  56244. positions[i + 1] = path[j].y;
  56245. positions[i + 2] = path[j].z;
  56246. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56247. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56248. }
  56249. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56250. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56251. }
  56252. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56253. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56254. }
  56255. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56256. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56257. }
  56258. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56259. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56260. }
  56261. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56262. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56263. }
  56264. j++;
  56265. i += 3;
  56266. }
  56267. if (instance._closePath) {
  56268. positions[i] = path[0].x;
  56269. positions[i + 1] = path[0].y;
  56270. positions[i + 2] = path[0].z;
  56271. i += 3;
  56272. }
  56273. }
  56274. }
  56275. };
  56276. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56277. positionFunction(positions);
  56278. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56279. instance._boundingInfo.update(instance._worldMatrix);
  56280. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56281. if (options.colors) {
  56282. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56283. for (var c = 0; c < options.colors.length; c++) {
  56284. colors[c * 4] = options.colors[c].r;
  56285. colors[c * 4 + 1] = options.colors[c].g;
  56286. colors[c * 4 + 2] = options.colors[c].b;
  56287. colors[c * 4 + 3] = options.colors[c].a;
  56288. }
  56289. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56290. }
  56291. if (options.uvs) {
  56292. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56293. for (var i = 0; i < options.uvs.length; i++) {
  56294. uvs[i * 2] = options.uvs[i].x;
  56295. uvs[i * 2 + 1] = options.uvs[i].y;
  56296. }
  56297. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56298. }
  56299. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56300. var indices = instance.getIndices();
  56301. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56302. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56303. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56304. if (instance._closePath) {
  56305. var indexFirst = 0;
  56306. var indexLast = 0;
  56307. for (var p = 0; p < pathArray.length; p++) {
  56308. indexFirst = instance._idx[p] * 3;
  56309. if (p + 1 < pathArray.length) {
  56310. indexLast = (instance._idx[p + 1] - 1) * 3;
  56311. }
  56312. else {
  56313. indexLast = normals.length - 3;
  56314. }
  56315. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56316. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56317. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56318. normals[indexLast] = normals[indexFirst];
  56319. normals[indexLast + 1] = normals[indexFirst + 1];
  56320. normals[indexLast + 2] = normals[indexFirst + 2];
  56321. }
  56322. }
  56323. if (!(instance.areNormalsFrozen)) {
  56324. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56325. }
  56326. }
  56327. return instance;
  56328. }
  56329. else {
  56330. var ribbon = new BABYLON.Mesh(name, scene);
  56331. ribbon._originalBuilderSideOrientation = sideOrientation;
  56332. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56333. if (closePath) {
  56334. ribbon._idx = vertexData._idx;
  56335. }
  56336. ribbon._closePath = closePath;
  56337. ribbon._closeArray = closeArray;
  56338. vertexData.applyToMesh(ribbon, updatable);
  56339. return ribbon;
  56340. }
  56341. };
  56342. /**
  56343. * Creates a cylinder or a cone mesh.
  56344. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56345. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56346. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56347. * 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.
  56348. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56349. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56350. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56351. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56352. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56353. * 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).
  56354. * 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
  56355. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56356. * 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
  56357. * 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.
  56358. * If `enclose` is false, a ring surface is one element.
  56359. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56360. * 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
  56361. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56362. * 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).
  56363. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56365. */
  56366. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56367. var cylinder = new BABYLON.Mesh(name, scene);
  56368. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56369. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56370. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56371. vertexData.applyToMesh(cylinder, options.updatable);
  56372. return cylinder;
  56373. };
  56374. /**
  56375. * Creates a torus mesh.
  56376. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56377. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56378. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56379. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56380. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56381. * 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).
  56382. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56384. */
  56385. MeshBuilder.CreateTorus = function (name, options, scene) {
  56386. var torus = new BABYLON.Mesh(name, scene);
  56387. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56388. torus._originalBuilderSideOrientation = options.sideOrientation;
  56389. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56390. vertexData.applyToMesh(torus, options.updatable);
  56391. return torus;
  56392. };
  56393. /**
  56394. * Creates a torus knot mesh.
  56395. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56396. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56397. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56398. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56399. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56400. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56401. * 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).
  56402. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56404. */
  56405. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56406. var torusKnot = new BABYLON.Mesh(name, scene);
  56407. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56408. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56409. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56410. vertexData.applyToMesh(torusKnot, options.updatable);
  56411. return torusKnot;
  56412. };
  56413. /**
  56414. * Creates a line system mesh.
  56415. * A line system is a pool of many lines gathered in a single mesh.
  56416. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56417. * 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.
  56418. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56419. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56420. * 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
  56421. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56422. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56423. * 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
  56424. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56426. */
  56427. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56428. var instance = options.instance;
  56429. var lines = options.lines;
  56430. var colors = options.colors;
  56431. if (instance) {
  56432. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56433. var vertexColor;
  56434. var lineColors;
  56435. if (colors) {
  56436. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56437. }
  56438. var i = 0;
  56439. var c = 0;
  56440. for (var l = 0; l < lines.length; l++) {
  56441. var points = lines[l];
  56442. for (var p = 0; p < points.length; p++) {
  56443. positions[i] = points[p].x;
  56444. positions[i + 1] = points[p].y;
  56445. positions[i + 2] = points[p].z;
  56446. if (colors && vertexColor) {
  56447. lineColors = colors[l];
  56448. vertexColor[c] = lineColors[p].r;
  56449. vertexColor[c + 1] = lineColors[p].g;
  56450. vertexColor[c + 2] = lineColors[p].b;
  56451. vertexColor[c + 3] = lineColors[p].a;
  56452. c += 4;
  56453. }
  56454. i += 3;
  56455. }
  56456. }
  56457. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56458. if (colors && vertexColor) {
  56459. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56460. }
  56461. return instance;
  56462. }
  56463. // line system creation
  56464. var useVertexColor = (colors) ? true : false;
  56465. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56466. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56467. vertexData.applyToMesh(lineSystem, options.updatable);
  56468. return lineSystem;
  56469. };
  56470. /**
  56471. * Creates a line mesh.
  56472. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56473. * 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.
  56474. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56475. * The parameter `points` is an array successive Vector3.
  56476. * 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
  56477. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56478. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56479. * When updating an instance, remember that only point positions can change, not the number of points.
  56480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56481. */
  56482. MeshBuilder.CreateLines = function (name, options, scene) {
  56483. if (scene === void 0) { scene = null; }
  56484. var colors = (options.colors) ? [options.colors] : null;
  56485. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56486. return lines;
  56487. };
  56488. /**
  56489. * Creates a dashed line mesh.
  56490. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56491. * 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.
  56492. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56493. * The parameter `points` is an array successive Vector3.
  56494. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56495. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56496. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56497. * 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
  56498. * When updating an instance, remember that only point positions can change, not the number of points.
  56499. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56500. */
  56501. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56502. if (scene === void 0) { scene = null; }
  56503. var points = options.points;
  56504. var instance = options.instance;
  56505. var gapSize = options.gapSize || 1;
  56506. var dashSize = options.dashSize || 3;
  56507. if (instance) {
  56508. var positionFunction = function (positions) {
  56509. var curvect = BABYLON.Vector3.Zero();
  56510. var nbSeg = positions.length / 6;
  56511. var lg = 0;
  56512. var nb = 0;
  56513. var shft = 0;
  56514. var dashshft = 0;
  56515. var curshft = 0;
  56516. var p = 0;
  56517. var i = 0;
  56518. var j = 0;
  56519. for (i = 0; i < points.length - 1; i++) {
  56520. points[i + 1].subtractToRef(points[i], curvect);
  56521. lg += curvect.length();
  56522. }
  56523. shft = lg / nbSeg;
  56524. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56525. for (i = 0; i < points.length - 1; i++) {
  56526. points[i + 1].subtractToRef(points[i], curvect);
  56527. nb = Math.floor(curvect.length() / shft);
  56528. curvect.normalize();
  56529. j = 0;
  56530. while (j < nb && p < positions.length) {
  56531. curshft = shft * j;
  56532. positions[p] = points[i].x + curshft * curvect.x;
  56533. positions[p + 1] = points[i].y + curshft * curvect.y;
  56534. positions[p + 2] = points[i].z + curshft * curvect.z;
  56535. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56536. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56537. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56538. p += 6;
  56539. j++;
  56540. }
  56541. }
  56542. while (p < positions.length) {
  56543. positions[p] = points[i].x;
  56544. positions[p + 1] = points[i].y;
  56545. positions[p + 2] = points[i].z;
  56546. p += 3;
  56547. }
  56548. };
  56549. instance.updateMeshPositions(positionFunction, false);
  56550. return instance;
  56551. }
  56552. // dashed lines creation
  56553. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56554. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56555. vertexData.applyToMesh(dashedLines, options.updatable);
  56556. dashedLines.dashSize = dashSize;
  56557. dashedLines.gapSize = gapSize;
  56558. return dashedLines;
  56559. };
  56560. /**
  56561. * Creates an extruded shape mesh.
  56562. * 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.
  56563. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56564. *
  56565. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56566. * 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
  56567. * extruded along the Z axis.
  56568. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56569. * 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.
  56570. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56571. * 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
  56572. * 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
  56573. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56574. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56575. * 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).
  56576. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56577. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56579. */
  56580. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56581. if (scene === void 0) { scene = null; }
  56582. var path = options.path;
  56583. var shape = options.shape;
  56584. var scale = options.scale || 1;
  56585. var rotation = options.rotation || 0;
  56586. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56587. var updatable = options.updatable;
  56588. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56589. var instance = options.instance || null;
  56590. var invertUV = options.invertUV || false;
  56591. 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);
  56592. };
  56593. /**
  56594. * Creates an custom extruded shape mesh.
  56595. * 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.
  56596. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56597. *
  56598. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56599. * 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
  56600. * extruded along the Z axis.
  56601. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56602. * 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
  56603. * and the distance of this point from the begining of the path :
  56604. * ```javascript
  56605. * var rotationFunction = function(i, distance) {
  56606. * // do things
  56607. * return rotationValue; }
  56608. * ```
  56609. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56610. * 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
  56611. * and the distance of this point from the begining of the path :
  56612. * ```javascript
  56613. * var scaleFunction = function(i, distance) {
  56614. * // do things
  56615. * return scaleValue;}
  56616. * ```
  56617. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56618. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56619. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56620. * 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
  56621. * 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
  56622. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56624. * 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).
  56625. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56626. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56628. */
  56629. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56630. var path = options.path;
  56631. var shape = options.shape;
  56632. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56633. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56634. var ribbonCloseArray = options.ribbonCloseArray || false;
  56635. var ribbonClosePath = options.ribbonClosePath || false;
  56636. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56637. var updatable = options.updatable;
  56638. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56639. var instance = options.instance;
  56640. var invertUV = options.invertUV || false;
  56641. 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);
  56642. };
  56643. /**
  56644. * Creates lathe mesh.
  56645. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56646. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56647. *
  56648. * 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
  56649. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56650. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56651. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56652. * 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.
  56653. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56654. * 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
  56655. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56656. * 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).
  56657. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56658. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56660. */
  56661. MeshBuilder.CreateLathe = function (name, options, scene) {
  56662. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56663. var closed = (options.closed === undefined) ? true : options.closed;
  56664. var shape = options.shape;
  56665. var radius = options.radius || 1;
  56666. var tessellation = options.tessellation || 64;
  56667. var updatable = options.updatable;
  56668. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56669. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56670. var pi2 = Math.PI * 2;
  56671. var paths = new Array();
  56672. var invertUV = options.invertUV || false;
  56673. var i = 0;
  56674. var p = 0;
  56675. var step = pi2 / tessellation * arc;
  56676. var rotated;
  56677. var path = new Array();
  56678. ;
  56679. for (i = 0; i <= tessellation; i++) {
  56680. var path = [];
  56681. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56682. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56683. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56684. }
  56685. for (p = 0; p < shape.length; p++) {
  56686. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56687. path.push(rotated);
  56688. }
  56689. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56690. 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));
  56691. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56692. }
  56693. paths.push(path);
  56694. }
  56695. // lathe ribbon
  56696. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56697. return lathe;
  56698. };
  56699. /**
  56700. * Creates a plane mesh.
  56701. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56702. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56703. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56704. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56705. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56706. * 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).
  56707. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56709. */
  56710. MeshBuilder.CreatePlane = function (name, options, scene) {
  56711. var plane = new BABYLON.Mesh(name, scene);
  56712. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56713. plane._originalBuilderSideOrientation = options.sideOrientation;
  56714. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56715. vertexData.applyToMesh(plane, options.updatable);
  56716. if (options.sourcePlane) {
  56717. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56718. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56719. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56720. plane.rotate(vectorProduct, product);
  56721. }
  56722. return plane;
  56723. };
  56724. /**
  56725. * Creates a ground mesh.
  56726. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56727. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56728. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56730. */
  56731. MeshBuilder.CreateGround = function (name, options, scene) {
  56732. var ground = new BABYLON.GroundMesh(name, scene);
  56733. ground._setReady(false);
  56734. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56735. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56736. ground._width = options.width || 1;
  56737. ground._height = options.height || 1;
  56738. ground._maxX = ground._width / 2;
  56739. ground._maxZ = ground._height / 2;
  56740. ground._minX = -ground._maxX;
  56741. ground._minZ = -ground._maxZ;
  56742. var vertexData = BABYLON.VertexData.CreateGround(options);
  56743. vertexData.applyToMesh(ground, options.updatable);
  56744. ground._setReady(true);
  56745. return ground;
  56746. };
  56747. /**
  56748. * Creates a tiled ground mesh.
  56749. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56750. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56751. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56752. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56753. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56754. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56755. * numbers of subdivisions on the ground width and height of each tile.
  56756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56757. */
  56758. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56759. var tiledGround = new BABYLON.Mesh(name, scene);
  56760. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56761. vertexData.applyToMesh(tiledGround, options.updatable);
  56762. return tiledGround;
  56763. };
  56764. /**
  56765. * Creates a ground mesh from a height map.
  56766. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56767. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56768. * The parameter `url` sets the URL of the height map image resource.
  56769. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56770. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56771. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56772. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56773. * 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.
  56774. * 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).
  56775. * This function is passed the newly built mesh :
  56776. * ```javascript
  56777. * function(mesh) { // do things
  56778. * return; }
  56779. * ```
  56780. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56781. */
  56782. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56783. var width = options.width || 10.0;
  56784. var height = options.height || 10.0;
  56785. var subdivisions = options.subdivisions || 1 | 0;
  56786. var minHeight = options.minHeight || 0.0;
  56787. var maxHeight = options.maxHeight || 1.0;
  56788. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56789. var updatable = options.updatable;
  56790. var onReady = options.onReady;
  56791. var ground = new BABYLON.GroundMesh(name, scene);
  56792. ground._subdivisionsX = subdivisions;
  56793. ground._subdivisionsY = subdivisions;
  56794. ground._width = width;
  56795. ground._height = height;
  56796. ground._maxX = ground._width / 2.0;
  56797. ground._maxZ = ground._height / 2.0;
  56798. ground._minX = -ground._maxX;
  56799. ground._minZ = -ground._maxZ;
  56800. ground._setReady(false);
  56801. var onload = function (img) {
  56802. // Getting height map data
  56803. var canvas = document.createElement("canvas");
  56804. var context = canvas.getContext("2d");
  56805. if (!context) {
  56806. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56807. }
  56808. if (scene.isDisposed) {
  56809. return;
  56810. }
  56811. var bufferWidth = img.width;
  56812. var bufferHeight = img.height;
  56813. canvas.width = bufferWidth;
  56814. canvas.height = bufferHeight;
  56815. context.drawImage(img, 0, 0);
  56816. // Create VertexData from map data
  56817. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56818. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56819. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56820. width: width, height: height,
  56821. subdivisions: subdivisions,
  56822. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56823. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56824. });
  56825. vertexData.applyToMesh(ground, updatable);
  56826. //execute ready callback, if set
  56827. if (onReady) {
  56828. onReady(ground);
  56829. }
  56830. ground._setReady(true);
  56831. };
  56832. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56833. return ground;
  56834. };
  56835. /**
  56836. * Creates a polygon mesh.
  56837. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56838. * 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.
  56839. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56841. * 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).
  56842. * Remember you can only change the shape positions, not their number when updating a polygon.
  56843. */
  56844. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56845. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56846. var shape = options.shape;
  56847. var holes = options.holes || [];
  56848. var depth = options.depth || 0;
  56849. var contours = [];
  56850. var hole = [];
  56851. for (var i = 0; i < shape.length; i++) {
  56852. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56853. }
  56854. var epsilon = 0.00000001;
  56855. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56856. contours.pop();
  56857. }
  56858. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56859. for (var hNb = 0; hNb < holes.length; hNb++) {
  56860. hole = [];
  56861. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56862. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56863. }
  56864. polygonTriangulation.addHole(hole);
  56865. }
  56866. var polygon = polygonTriangulation.build(options.updatable, depth);
  56867. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56868. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56869. vertexData.applyToMesh(polygon, options.updatable);
  56870. return polygon;
  56871. };
  56872. ;
  56873. /**
  56874. * Creates an extruded polygon mesh, with depth in the Y direction.
  56875. * 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).
  56876. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56877. */
  56878. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56879. return MeshBuilder.CreatePolygon(name, options, scene);
  56880. };
  56881. ;
  56882. /**
  56883. * Creates a tube mesh.
  56884. * 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.
  56885. *
  56886. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56887. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56888. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56889. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56890. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56891. * 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.
  56892. * It must return a radius value (positive float) :
  56893. * ```javascript
  56894. * var radiusFunction = function(i, distance) {
  56895. * // do things
  56896. * return radius; }
  56897. * ```
  56898. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56899. * 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
  56900. * 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
  56901. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56902. * 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).
  56903. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56904. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56905. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56906. */
  56907. MeshBuilder.CreateTube = function (name, options, scene) {
  56908. var path = options.path;
  56909. var instance = options.instance;
  56910. var radius = 1.0;
  56911. if (instance) {
  56912. radius = instance.radius;
  56913. }
  56914. if (options.radius !== undefined) {
  56915. radius = options.radius;
  56916. }
  56917. ;
  56918. var tessellation = options.tessellation || 64 | 0;
  56919. var radiusFunction = options.radiusFunction || null;
  56920. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56921. var invertUV = options.invertUV || false;
  56922. var updatable = options.updatable;
  56923. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56924. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56925. // tube geometry
  56926. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56927. var tangents = path3D.getTangents();
  56928. var normals = path3D.getNormals();
  56929. var distances = path3D.getDistances();
  56930. var pi2 = Math.PI * 2;
  56931. var step = pi2 / tessellation * arc;
  56932. var returnRadius = function () { return radius; };
  56933. var radiusFunctionFinal = radiusFunction || returnRadius;
  56934. var circlePath;
  56935. var rad;
  56936. var normal;
  56937. var rotated;
  56938. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56939. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56940. for (var i = 0; i < path.length; i++) {
  56941. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56942. circlePath = Array(); // current circle array
  56943. normal = normals[i]; // current normal
  56944. for (var t = 0; t < tessellation; t++) {
  56945. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56946. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56947. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56948. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56949. circlePath[t] = rotated;
  56950. }
  56951. circlePaths[index] = circlePath;
  56952. index++;
  56953. }
  56954. // cap
  56955. var capPath = function (nbPoints, pathIndex) {
  56956. var pointCap = Array();
  56957. for (var i = 0; i < nbPoints; i++) {
  56958. pointCap.push(path[pathIndex]);
  56959. }
  56960. return pointCap;
  56961. };
  56962. switch (cap) {
  56963. case BABYLON.Mesh.NO_CAP:
  56964. break;
  56965. case BABYLON.Mesh.CAP_START:
  56966. circlePaths[0] = capPath(tessellation, 0);
  56967. circlePaths[1] = circlePaths[2].slice(0);
  56968. break;
  56969. case BABYLON.Mesh.CAP_END:
  56970. circlePaths[index] = circlePaths[index - 1].slice(0);
  56971. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56972. break;
  56973. case BABYLON.Mesh.CAP_ALL:
  56974. circlePaths[0] = capPath(tessellation, 0);
  56975. circlePaths[1] = circlePaths[2].slice(0);
  56976. circlePaths[index] = circlePaths[index - 1].slice(0);
  56977. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56978. break;
  56979. default:
  56980. break;
  56981. }
  56982. return circlePaths;
  56983. };
  56984. var path3D;
  56985. var pathArray;
  56986. if (instance) {
  56987. var arc = options.arc || instance.arc;
  56988. path3D = (instance.path3D).update(path);
  56989. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56990. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56991. instance.path3D = path3D;
  56992. instance.pathArray = pathArray;
  56993. instance.arc = arc;
  56994. instance.radius = radius;
  56995. return instance;
  56996. }
  56997. // tube creation
  56998. path3D = new BABYLON.Path3D(path);
  56999. var newPathArray = new Array();
  57000. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57001. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57002. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57003. tube.pathArray = pathArray;
  57004. tube.path3D = path3D;
  57005. tube.tessellation = tessellation;
  57006. tube.cap = cap;
  57007. tube.arc = options.arc;
  57008. tube.radius = radius;
  57009. return tube;
  57010. };
  57011. /**
  57012. * Creates a polyhedron mesh.
  57013. *
  57014. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57015. * 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
  57016. * to choose the wanted type.
  57017. * The parameter `size` (positive float, default 1) sets the polygon size.
  57018. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57019. * 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`.
  57020. * 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
  57021. * 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)`).
  57022. * 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
  57023. * 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.
  57024. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57025. * 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).
  57026. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57028. */
  57029. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57030. var polyhedron = new BABYLON.Mesh(name, scene);
  57031. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57032. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57033. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57034. vertexData.applyToMesh(polyhedron, options.updatable);
  57035. return polyhedron;
  57036. };
  57037. /**
  57038. * Creates a decal mesh.
  57039. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57040. * 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.
  57041. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57042. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57043. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57044. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57045. */
  57046. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57047. var indices = sourceMesh.getIndices();
  57048. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57049. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57050. var position = options.position || BABYLON.Vector3.Zero();
  57051. var normal = options.normal || BABYLON.Vector3.Up();
  57052. var size = options.size || BABYLON.Vector3.One();
  57053. var angle = options.angle || 0;
  57054. // Getting correct rotation
  57055. if (!normal) {
  57056. var target = new BABYLON.Vector3(0, 0, 1);
  57057. var camera = sourceMesh.getScene().activeCamera;
  57058. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57059. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57060. }
  57061. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57062. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57063. var pitch = Math.atan2(normal.y, len);
  57064. // Matrix
  57065. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57066. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57067. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57068. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57069. var vertexData = new BABYLON.VertexData();
  57070. vertexData.indices = [];
  57071. vertexData.positions = [];
  57072. vertexData.normals = [];
  57073. vertexData.uvs = [];
  57074. var currentVertexDataIndex = 0;
  57075. var extractDecalVector3 = function (indexId) {
  57076. var result = new BABYLON.PositionNormalVertex();
  57077. if (!indices || !positions || !normals) {
  57078. return result;
  57079. }
  57080. var vertexId = indices[indexId];
  57081. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57082. // Send vector to decal local world
  57083. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57084. // Get normal
  57085. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57086. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57087. return result;
  57088. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57089. var clip = function (vertices, axis) {
  57090. if (vertices.length === 0) {
  57091. return vertices;
  57092. }
  57093. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57094. var clipVertices = function (v0, v1) {
  57095. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57096. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57097. };
  57098. var result = new Array();
  57099. for (var index = 0; index < vertices.length; index += 3) {
  57100. var v1Out;
  57101. var v2Out;
  57102. var v3Out;
  57103. var total = 0;
  57104. var nV1 = null;
  57105. var nV2 = null;
  57106. var nV3 = null;
  57107. var nV4 = null;
  57108. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57109. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57110. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57111. v1Out = d1 > 0;
  57112. v2Out = d2 > 0;
  57113. v3Out = d3 > 0;
  57114. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57115. switch (total) {
  57116. case 0:
  57117. result.push(vertices[index]);
  57118. result.push(vertices[index + 1]);
  57119. result.push(vertices[index + 2]);
  57120. break;
  57121. case 1:
  57122. if (v1Out) {
  57123. nV1 = vertices[index + 1];
  57124. nV2 = vertices[index + 2];
  57125. nV3 = clipVertices(vertices[index], nV1);
  57126. nV4 = clipVertices(vertices[index], nV2);
  57127. }
  57128. if (v2Out) {
  57129. nV1 = vertices[index];
  57130. nV2 = vertices[index + 2];
  57131. nV3 = clipVertices(vertices[index + 1], nV1);
  57132. nV4 = clipVertices(vertices[index + 1], nV2);
  57133. result.push(nV3);
  57134. result.push(nV2.clone());
  57135. result.push(nV1.clone());
  57136. result.push(nV2.clone());
  57137. result.push(nV3.clone());
  57138. result.push(nV4);
  57139. break;
  57140. }
  57141. if (v3Out) {
  57142. nV1 = vertices[index];
  57143. nV2 = vertices[index + 1];
  57144. nV3 = clipVertices(vertices[index + 2], nV1);
  57145. nV4 = clipVertices(vertices[index + 2], nV2);
  57146. }
  57147. if (nV1 && nV2 && nV3 && nV4) {
  57148. result.push(nV1.clone());
  57149. result.push(nV2.clone());
  57150. result.push(nV3);
  57151. result.push(nV4);
  57152. result.push(nV3.clone());
  57153. result.push(nV2.clone());
  57154. }
  57155. break;
  57156. case 2:
  57157. if (!v1Out) {
  57158. nV1 = vertices[index].clone();
  57159. nV2 = clipVertices(nV1, vertices[index + 1]);
  57160. nV3 = clipVertices(nV1, vertices[index + 2]);
  57161. result.push(nV1);
  57162. result.push(nV2);
  57163. result.push(nV3);
  57164. }
  57165. if (!v2Out) {
  57166. nV1 = vertices[index + 1].clone();
  57167. nV2 = clipVertices(nV1, vertices[index + 2]);
  57168. nV3 = clipVertices(nV1, vertices[index]);
  57169. result.push(nV1);
  57170. result.push(nV2);
  57171. result.push(nV3);
  57172. }
  57173. if (!v3Out) {
  57174. nV1 = vertices[index + 2].clone();
  57175. nV2 = clipVertices(nV1, vertices[index]);
  57176. nV3 = clipVertices(nV1, vertices[index + 1]);
  57177. result.push(nV1);
  57178. result.push(nV2);
  57179. result.push(nV3);
  57180. }
  57181. break;
  57182. case 3:
  57183. break;
  57184. }
  57185. }
  57186. return result;
  57187. };
  57188. for (var index = 0; index < indices.length; index += 3) {
  57189. var faceVertices = new Array();
  57190. faceVertices.push(extractDecalVector3(index));
  57191. faceVertices.push(extractDecalVector3(index + 1));
  57192. faceVertices.push(extractDecalVector3(index + 2));
  57193. // Clip
  57194. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57195. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57196. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57197. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57198. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57199. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57200. if (faceVertices.length === 0) {
  57201. continue;
  57202. }
  57203. // Add UVs and get back to world
  57204. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57205. var vertex = faceVertices[vIndex];
  57206. //TODO check for Int32Array | Uint32Array | Uint16Array
  57207. vertexData.indices.push(currentVertexDataIndex);
  57208. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57209. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57210. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57211. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57212. currentVertexDataIndex++;
  57213. }
  57214. }
  57215. // Return mesh
  57216. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57217. vertexData.applyToMesh(decal);
  57218. decal.position = position.clone();
  57219. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57220. return decal;
  57221. };
  57222. // Privates
  57223. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57224. // extrusion geometry
  57225. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57226. var tangents = path3D.getTangents();
  57227. var normals = path3D.getNormals();
  57228. var binormals = path3D.getBinormals();
  57229. var distances = path3D.getDistances();
  57230. var angle = 0;
  57231. var returnScale = function () { return scale !== null ? scale : 1; };
  57232. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57233. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57234. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57235. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57236. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57237. for (var i = 0; i < curve.length; i++) {
  57238. var shapePath = new Array();
  57239. var angleStep = rotate(i, distances[i]);
  57240. var scaleRatio = scl(i, distances[i]);
  57241. for (var p = 0; p < shape.length; p++) {
  57242. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57243. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57244. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57245. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57246. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57247. shapePath[p] = rotated;
  57248. }
  57249. shapePaths[index] = shapePath;
  57250. angle += angleStep;
  57251. index++;
  57252. }
  57253. // cap
  57254. var capPath = function (shapePath) {
  57255. var pointCap = Array();
  57256. var barycenter = BABYLON.Vector3.Zero();
  57257. var i;
  57258. for (i = 0; i < shapePath.length; i++) {
  57259. barycenter.addInPlace(shapePath[i]);
  57260. }
  57261. barycenter.scaleInPlace(1.0 / shapePath.length);
  57262. for (i = 0; i < shapePath.length; i++) {
  57263. pointCap.push(barycenter);
  57264. }
  57265. return pointCap;
  57266. };
  57267. switch (cap) {
  57268. case BABYLON.Mesh.NO_CAP:
  57269. break;
  57270. case BABYLON.Mesh.CAP_START:
  57271. shapePaths[0] = capPath(shapePaths[2]);
  57272. shapePaths[1] = shapePaths[2];
  57273. break;
  57274. case BABYLON.Mesh.CAP_END:
  57275. shapePaths[index] = shapePaths[index - 1];
  57276. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57277. break;
  57278. case BABYLON.Mesh.CAP_ALL:
  57279. shapePaths[0] = capPath(shapePaths[2]);
  57280. shapePaths[1] = shapePaths[2];
  57281. shapePaths[index] = shapePaths[index - 1];
  57282. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57283. break;
  57284. default:
  57285. break;
  57286. }
  57287. return shapePaths;
  57288. };
  57289. var path3D;
  57290. var pathArray;
  57291. if (instance) {
  57292. path3D = (instance.path3D).update(curve);
  57293. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57294. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57295. return instance;
  57296. }
  57297. // extruded shape creation
  57298. path3D = new BABYLON.Path3D(curve);
  57299. var newShapePaths = new Array();
  57300. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57301. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57302. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57303. extrudedGeneric.pathArray = pathArray;
  57304. extrudedGeneric.path3D = path3D;
  57305. extrudedGeneric.cap = cap;
  57306. return extrudedGeneric;
  57307. };
  57308. return MeshBuilder;
  57309. }());
  57310. BABYLON.MeshBuilder = MeshBuilder;
  57311. })(BABYLON || (BABYLON = {}));
  57312. //# sourceMappingURL=babylon.meshBuilder.js.map
  57313. var BABYLON;
  57314. (function (BABYLON) {
  57315. /**
  57316. * Draco compression (https://google.github.io/draco/)
  57317. */
  57318. var DracoCompression = /** @class */ (function () {
  57319. /**
  57320. * Constructor
  57321. * @param numWorkers The number of workers for async operations
  57322. */
  57323. function DracoCompression(numWorkers) {
  57324. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57325. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57326. if (!workerBlobUrl || !Worker) {
  57327. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57328. return;
  57329. }
  57330. var workers = new Array(numWorkers);
  57331. for (var i = 0; i < workers.length; i++) {
  57332. var worker = new Worker(workerBlobUrl);
  57333. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57334. workers[i] = worker;
  57335. }
  57336. this._workerPool = new BABYLON.WorkerPool(workers);
  57337. }
  57338. /**
  57339. * Stop all async operations and release resources.
  57340. */
  57341. DracoCompression.prototype.dispose = function () {
  57342. this._workerPool.dispose();
  57343. delete this._workerPool;
  57344. };
  57345. /**
  57346. * Decode Draco compressed mesh data to vertex data.
  57347. * @param data The array buffer view for the Draco compression data
  57348. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57349. * @returns A promise that resolves with the decoded vertex data
  57350. */
  57351. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57352. var _this = this;
  57353. return new Promise(function (resolve, reject) {
  57354. _this._workerPool.push(function (worker, onComplete) {
  57355. var vertexData = new BABYLON.VertexData();
  57356. var onError = function (error) {
  57357. worker.removeEventListener("error", onError);
  57358. worker.removeEventListener("message", onMessage);
  57359. reject(error);
  57360. onComplete();
  57361. };
  57362. var onMessage = function (message) {
  57363. if (message.data === "done") {
  57364. worker.removeEventListener("error", onError);
  57365. worker.removeEventListener("message", onMessage);
  57366. resolve(vertexData);
  57367. onComplete();
  57368. }
  57369. else if (message.data.id === "indices") {
  57370. vertexData.indices = message.data.value;
  57371. }
  57372. else {
  57373. vertexData.set(message.data.value, message.data.id);
  57374. }
  57375. };
  57376. worker.addEventListener("error", onError);
  57377. worker.addEventListener("message", onMessage);
  57378. var dataCopy = new Uint8Array(data.byteLength);
  57379. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57380. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57381. });
  57382. });
  57383. };
  57384. /**
  57385. * The worker function that gets converted to a blob url to pass into a worker.
  57386. */
  57387. DracoCompression._Worker = function () {
  57388. // self is actually a DedicatedWorkerGlobalScope
  57389. var _self = self;
  57390. var decodeMesh = function (data, attributes) {
  57391. var dracoModule = new DracoDecoderModule();
  57392. var buffer = new dracoModule.DecoderBuffer();
  57393. buffer.Init(data, data.byteLength);
  57394. var decoder = new dracoModule.Decoder();
  57395. var geometry;
  57396. var status;
  57397. try {
  57398. var type = decoder.GetEncodedGeometryType(buffer);
  57399. switch (type) {
  57400. case dracoModule.TRIANGULAR_MESH:
  57401. geometry = new dracoModule.Mesh();
  57402. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57403. break;
  57404. case dracoModule.POINT_CLOUD:
  57405. geometry = new dracoModule.PointCloud();
  57406. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57407. break;
  57408. default:
  57409. throw new Error("Invalid geometry type " + type);
  57410. }
  57411. if (!status.ok() || !geometry.ptr) {
  57412. throw new Error(status.error_msg());
  57413. }
  57414. var numPoints = geometry.num_points();
  57415. if (type === dracoModule.TRIANGULAR_MESH) {
  57416. var numFaces = geometry.num_faces();
  57417. var faceIndices = new dracoModule.DracoInt32Array();
  57418. try {
  57419. var indices = new Uint32Array(numFaces * 3);
  57420. for (var i = 0; i < numFaces; i++) {
  57421. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57422. var offset = i * 3;
  57423. indices[offset + 0] = faceIndices.GetValue(0);
  57424. indices[offset + 1] = faceIndices.GetValue(1);
  57425. indices[offset + 2] = faceIndices.GetValue(2);
  57426. }
  57427. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57428. }
  57429. finally {
  57430. dracoModule.destroy(faceIndices);
  57431. }
  57432. }
  57433. for (var kind in attributes) {
  57434. var uniqueId = attributes[kind];
  57435. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57436. var dracoData = new dracoModule.DracoFloat32Array();
  57437. try {
  57438. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57439. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57440. for (var i = 0; i < babylonData.length; i++) {
  57441. babylonData[i] = dracoData.GetValue(i);
  57442. }
  57443. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57444. }
  57445. finally {
  57446. dracoModule.destroy(dracoData);
  57447. }
  57448. }
  57449. }
  57450. finally {
  57451. if (geometry) {
  57452. dracoModule.destroy(geometry);
  57453. }
  57454. dracoModule.destroy(decoder);
  57455. dracoModule.destroy(buffer);
  57456. }
  57457. _self.postMessage("done");
  57458. };
  57459. _self.onmessage = function (event) {
  57460. switch (event.data.id) {
  57461. case "initDecoder": {
  57462. importScripts(event.data.url);
  57463. break;
  57464. }
  57465. case "decodeMesh": {
  57466. decodeMesh(event.data.data, event.data.attributes);
  57467. break;
  57468. }
  57469. }
  57470. };
  57471. };
  57472. DracoCompression._GetDefaultDecoderUrl = function () {
  57473. if (!BABYLON.Tools.IsWindowObjectExist) {
  57474. return null;
  57475. }
  57476. for (var i = 0; i < document.scripts.length; i++) {
  57477. if (document.scripts[i].type === "text/x-draco-decoder") {
  57478. return document.scripts[i].src;
  57479. }
  57480. }
  57481. return null;
  57482. };
  57483. /**
  57484. * Gets the url to the draco decoder if available.
  57485. */
  57486. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57487. return DracoCompression;
  57488. }());
  57489. BABYLON.DracoCompression = DracoCompression;
  57490. })(BABYLON || (BABYLON = {}));
  57491. //# sourceMappingURL=babylon.dracoCompression.js.map
  57492. var BABYLON;
  57493. (function (BABYLON) {
  57494. var AudioEngine = /** @class */ (function () {
  57495. function AudioEngine() {
  57496. this._audioContext = null;
  57497. this._audioContextInitialized = false;
  57498. this.canUseWebAudio = false;
  57499. this.WarnedWebAudioUnsupported = false;
  57500. this.unlocked = false;
  57501. this.isMP3supported = false;
  57502. this.isOGGsupported = false;
  57503. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57504. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57505. this.canUseWebAudio = true;
  57506. }
  57507. var audioElem = document.createElement('audio');
  57508. try {
  57509. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57510. this.isMP3supported = true;
  57511. }
  57512. }
  57513. catch (e) {
  57514. // protect error during capability check.
  57515. }
  57516. try {
  57517. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57518. this.isOGGsupported = true;
  57519. }
  57520. }
  57521. catch (e) {
  57522. // protect error during capability check.
  57523. }
  57524. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57525. this._unlockiOSaudio();
  57526. }
  57527. else {
  57528. this.unlocked = true;
  57529. }
  57530. }
  57531. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57532. get: function () {
  57533. if (!this._audioContextInitialized) {
  57534. this._initializeAudioContext();
  57535. }
  57536. return this._audioContext;
  57537. },
  57538. enumerable: true,
  57539. configurable: true
  57540. });
  57541. AudioEngine.prototype._unlockiOSaudio = function () {
  57542. var _this = this;
  57543. var unlockaudio = function () {
  57544. if (!_this.audioContext) {
  57545. return;
  57546. }
  57547. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57548. var source = _this.audioContext.createBufferSource();
  57549. source.buffer = buffer;
  57550. source.connect(_this.audioContext.destination);
  57551. source.start(0);
  57552. setTimeout(function () {
  57553. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57554. _this.unlocked = true;
  57555. window.removeEventListener('touchend', unlockaudio, false);
  57556. if (_this.onAudioUnlocked) {
  57557. _this.onAudioUnlocked();
  57558. }
  57559. }
  57560. }, 0);
  57561. };
  57562. window.addEventListener('touchend', unlockaudio, false);
  57563. };
  57564. AudioEngine.prototype._initializeAudioContext = function () {
  57565. try {
  57566. if (this.canUseWebAudio) {
  57567. this._audioContext = new AudioContext();
  57568. // create a global volume gain node
  57569. this.masterGain = this._audioContext.createGain();
  57570. this.masterGain.gain.value = 1;
  57571. this.masterGain.connect(this._audioContext.destination);
  57572. this._audioContextInitialized = true;
  57573. }
  57574. }
  57575. catch (e) {
  57576. this.canUseWebAudio = false;
  57577. BABYLON.Tools.Error("Web Audio: " + e.message);
  57578. }
  57579. };
  57580. AudioEngine.prototype.dispose = function () {
  57581. if (this.canUseWebAudio && this._audioContextInitialized) {
  57582. if (this._connectedAnalyser && this._audioContext) {
  57583. this._connectedAnalyser.stopDebugCanvas();
  57584. this._connectedAnalyser.dispose();
  57585. this.masterGain.disconnect();
  57586. this.masterGain.connect(this._audioContext.destination);
  57587. this._connectedAnalyser = null;
  57588. }
  57589. this.masterGain.gain.value = 1;
  57590. }
  57591. this.WarnedWebAudioUnsupported = false;
  57592. };
  57593. AudioEngine.prototype.getGlobalVolume = function () {
  57594. if (this.canUseWebAudio && this._audioContextInitialized) {
  57595. return this.masterGain.gain.value;
  57596. }
  57597. else {
  57598. return -1;
  57599. }
  57600. };
  57601. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57602. if (this.canUseWebAudio && this._audioContextInitialized) {
  57603. this.masterGain.gain.value = newVolume;
  57604. }
  57605. };
  57606. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57607. if (this._connectedAnalyser) {
  57608. this._connectedAnalyser.stopDebugCanvas();
  57609. }
  57610. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57611. this._connectedAnalyser = analyser;
  57612. this.masterGain.disconnect();
  57613. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57614. }
  57615. };
  57616. return AudioEngine;
  57617. }());
  57618. BABYLON.AudioEngine = AudioEngine;
  57619. })(BABYLON || (BABYLON = {}));
  57620. //# sourceMappingURL=babylon.audioEngine.js.map
  57621. var BABYLON;
  57622. (function (BABYLON) {
  57623. var Sound = /** @class */ (function () {
  57624. /**
  57625. * Create a sound and attach it to a scene
  57626. * @param name Name of your sound
  57627. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57628. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57629. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57630. */
  57631. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57632. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57633. var _this = this;
  57634. this.autoplay = false;
  57635. this.loop = false;
  57636. this.useCustomAttenuation = false;
  57637. this.spatialSound = false;
  57638. this.refDistance = 1;
  57639. this.rolloffFactor = 1;
  57640. this.maxDistance = 100;
  57641. this.distanceModel = "linear";
  57642. this._panningModel = "equalpower";
  57643. this._playbackRate = 1;
  57644. this._streaming = false;
  57645. this._startTime = 0;
  57646. this._startOffset = 0;
  57647. this._position = BABYLON.Vector3.Zero();
  57648. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57649. this._volume = 1;
  57650. this._isReadyToPlay = false;
  57651. this.isPlaying = false;
  57652. this.isPaused = false;
  57653. this._isDirectional = false;
  57654. // Used if you'd like to create a directional sound.
  57655. // If not set, the sound will be omnidirectional
  57656. this._coneInnerAngle = 360;
  57657. this._coneOuterAngle = 360;
  57658. this._coneOuterGain = 0;
  57659. this._isOutputConnected = false;
  57660. this._urlType = "Unknown";
  57661. this.name = name;
  57662. this._scene = scene;
  57663. this._readyToPlayCallback = readyToPlayCallback;
  57664. // Default custom attenuation function is a linear attenuation
  57665. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57666. if (currentDistance < maxDistance) {
  57667. return currentVolume * (1 - currentDistance / maxDistance);
  57668. }
  57669. else {
  57670. return 0;
  57671. }
  57672. };
  57673. if (options) {
  57674. this.autoplay = options.autoplay || false;
  57675. this.loop = options.loop || false;
  57676. // if volume === 0, we need another way to check this option
  57677. if (options.volume !== undefined) {
  57678. this._volume = options.volume;
  57679. }
  57680. this.spatialSound = options.spatialSound || false;
  57681. this.maxDistance = options.maxDistance || 100;
  57682. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57683. this.rolloffFactor = options.rolloffFactor || 1;
  57684. this.refDistance = options.refDistance || 1;
  57685. this.distanceModel = options.distanceModel || "linear";
  57686. this._playbackRate = options.playbackRate || 1;
  57687. this._streaming = options.streaming || false;
  57688. }
  57689. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57690. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57691. this._soundGain.gain.value = this._volume;
  57692. this._inputAudioNode = this._soundGain;
  57693. this._ouputAudioNode = this._soundGain;
  57694. if (this.spatialSound) {
  57695. this._createSpatialParameters();
  57696. }
  57697. this._scene.mainSoundTrack.AddSound(this);
  57698. var validParameter = true;
  57699. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57700. if (urlOrArrayBuffer) {
  57701. if (typeof (urlOrArrayBuffer) === "string")
  57702. this._urlType = "String";
  57703. if (Array.isArray(urlOrArrayBuffer))
  57704. this._urlType = "Array";
  57705. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57706. this._urlType = "ArrayBuffer";
  57707. var urls = [];
  57708. var codecSupportedFound = false;
  57709. switch (this._urlType) {
  57710. case "ArrayBuffer":
  57711. if (urlOrArrayBuffer.byteLength > 0) {
  57712. codecSupportedFound = true;
  57713. this._soundLoaded(urlOrArrayBuffer);
  57714. }
  57715. break;
  57716. case "String":
  57717. urls.push(urlOrArrayBuffer);
  57718. case "Array":
  57719. if (urls.length === 0)
  57720. urls = urlOrArrayBuffer;
  57721. // If we found a supported format, we load it immediately and stop the loop
  57722. for (var i = 0; i < urls.length; i++) {
  57723. var url = urls[i];
  57724. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57725. codecSupportedFound = true;
  57726. }
  57727. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57728. codecSupportedFound = true;
  57729. }
  57730. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57731. codecSupportedFound = true;
  57732. }
  57733. if (url.indexOf("blob:") !== -1) {
  57734. codecSupportedFound = true;
  57735. }
  57736. if (codecSupportedFound) {
  57737. // Loading sound using XHR2
  57738. if (!this._streaming) {
  57739. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57740. }
  57741. else {
  57742. this._htmlAudioElement = new Audio(url);
  57743. this._htmlAudioElement.controls = false;
  57744. this._htmlAudioElement.loop = this.loop;
  57745. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57746. this._htmlAudioElement.preload = "auto";
  57747. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57748. _this._isReadyToPlay = true;
  57749. if (_this.autoplay) {
  57750. _this.play();
  57751. }
  57752. if (_this._readyToPlayCallback) {
  57753. _this._readyToPlayCallback();
  57754. }
  57755. });
  57756. document.body.appendChild(this._htmlAudioElement);
  57757. }
  57758. break;
  57759. }
  57760. }
  57761. break;
  57762. default:
  57763. validParameter = false;
  57764. break;
  57765. }
  57766. if (!validParameter) {
  57767. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57768. }
  57769. else {
  57770. if (!codecSupportedFound) {
  57771. this._isReadyToPlay = true;
  57772. // Simulating a ready to play event to avoid breaking code path
  57773. if (this._readyToPlayCallback) {
  57774. window.setTimeout(function () {
  57775. if (_this._readyToPlayCallback) {
  57776. _this._readyToPlayCallback();
  57777. }
  57778. }, 1000);
  57779. }
  57780. }
  57781. }
  57782. }
  57783. }
  57784. else {
  57785. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57786. this._scene.mainSoundTrack.AddSound(this);
  57787. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57788. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57789. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57790. }
  57791. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57792. if (this._readyToPlayCallback) {
  57793. window.setTimeout(function () {
  57794. if (_this._readyToPlayCallback) {
  57795. _this._readyToPlayCallback();
  57796. }
  57797. }, 1000);
  57798. }
  57799. }
  57800. }
  57801. Sound.prototype.dispose = function () {
  57802. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57803. if (this.isPlaying) {
  57804. this.stop();
  57805. }
  57806. this._isReadyToPlay = false;
  57807. if (this.soundTrackId === -1) {
  57808. this._scene.mainSoundTrack.RemoveSound(this);
  57809. }
  57810. else {
  57811. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57812. }
  57813. if (this._soundGain) {
  57814. this._soundGain.disconnect();
  57815. this._soundGain = null;
  57816. }
  57817. if (this._soundPanner) {
  57818. this._soundPanner.disconnect();
  57819. this._soundPanner = null;
  57820. }
  57821. if (this._soundSource) {
  57822. this._soundSource.disconnect();
  57823. this._soundSource = null;
  57824. }
  57825. this._audioBuffer = null;
  57826. if (this._htmlAudioElement) {
  57827. this._htmlAudioElement.pause();
  57828. this._htmlAudioElement.src = "";
  57829. document.body.removeChild(this._htmlAudioElement);
  57830. }
  57831. if (this._connectedMesh && this._registerFunc) {
  57832. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57833. this._connectedMesh = null;
  57834. }
  57835. }
  57836. };
  57837. Sound.prototype.isReady = function () {
  57838. return this._isReadyToPlay;
  57839. };
  57840. Sound.prototype._soundLoaded = function (audioData) {
  57841. var _this = this;
  57842. if (!BABYLON.Engine.audioEngine.audioContext) {
  57843. return;
  57844. }
  57845. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57846. _this._audioBuffer = buffer;
  57847. _this._isReadyToPlay = true;
  57848. if (_this.autoplay) {
  57849. _this.play();
  57850. }
  57851. if (_this._readyToPlayCallback) {
  57852. _this._readyToPlayCallback();
  57853. }
  57854. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57855. };
  57856. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57857. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57858. this._audioBuffer = audioBuffer;
  57859. this._isReadyToPlay = true;
  57860. }
  57861. };
  57862. Sound.prototype.updateOptions = function (options) {
  57863. if (options) {
  57864. this.loop = options.loop || this.loop;
  57865. this.maxDistance = options.maxDistance || this.maxDistance;
  57866. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57867. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57868. this.refDistance = options.refDistance || this.refDistance;
  57869. this.distanceModel = options.distanceModel || this.distanceModel;
  57870. this._playbackRate = options.playbackRate || this._playbackRate;
  57871. this._updateSpatialParameters();
  57872. if (this.isPlaying) {
  57873. if (this._streaming) {
  57874. this._htmlAudioElement.playbackRate = this._playbackRate;
  57875. }
  57876. else {
  57877. if (this._soundSource) {
  57878. this._soundSource.playbackRate.value = this._playbackRate;
  57879. }
  57880. }
  57881. }
  57882. }
  57883. };
  57884. Sound.prototype._createSpatialParameters = function () {
  57885. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57886. if (this._scene.headphone) {
  57887. this._panningModel = "HRTF";
  57888. }
  57889. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57890. this._updateSpatialParameters();
  57891. this._soundPanner.connect(this._ouputAudioNode);
  57892. this._inputAudioNode = this._soundPanner;
  57893. }
  57894. };
  57895. Sound.prototype._updateSpatialParameters = function () {
  57896. if (this.spatialSound && this._soundPanner) {
  57897. if (this.useCustomAttenuation) {
  57898. // Tricks to disable in a way embedded Web Audio attenuation
  57899. this._soundPanner.distanceModel = "linear";
  57900. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57901. this._soundPanner.refDistance = 1;
  57902. this._soundPanner.rolloffFactor = 1;
  57903. this._soundPanner.panningModel = this._panningModel;
  57904. }
  57905. else {
  57906. this._soundPanner.distanceModel = this.distanceModel;
  57907. this._soundPanner.maxDistance = this.maxDistance;
  57908. this._soundPanner.refDistance = this.refDistance;
  57909. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57910. this._soundPanner.panningModel = this._panningModel;
  57911. }
  57912. }
  57913. };
  57914. Sound.prototype.switchPanningModelToHRTF = function () {
  57915. this._panningModel = "HRTF";
  57916. this._switchPanningModel();
  57917. };
  57918. Sound.prototype.switchPanningModelToEqualPower = function () {
  57919. this._panningModel = "equalpower";
  57920. this._switchPanningModel();
  57921. };
  57922. Sound.prototype._switchPanningModel = function () {
  57923. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57924. this._soundPanner.panningModel = this._panningModel;
  57925. }
  57926. };
  57927. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57928. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57929. if (this._isOutputConnected) {
  57930. this._ouputAudioNode.disconnect();
  57931. }
  57932. this._ouputAudioNode.connect(soundTrackAudioNode);
  57933. this._isOutputConnected = true;
  57934. }
  57935. };
  57936. /**
  57937. * Transform this sound into a directional source
  57938. * @param coneInnerAngle Size of the inner cone in degree
  57939. * @param coneOuterAngle Size of the outer cone in degree
  57940. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57941. */
  57942. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57943. if (coneOuterAngle < coneInnerAngle) {
  57944. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57945. return;
  57946. }
  57947. this._coneInnerAngle = coneInnerAngle;
  57948. this._coneOuterAngle = coneOuterAngle;
  57949. this._coneOuterGain = coneOuterGain;
  57950. this._isDirectional = true;
  57951. if (this.isPlaying && this.loop) {
  57952. this.stop();
  57953. this.play();
  57954. }
  57955. };
  57956. Sound.prototype.setPosition = function (newPosition) {
  57957. this._position = newPosition;
  57958. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57959. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57960. }
  57961. };
  57962. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57963. this._localDirection = newLocalDirection;
  57964. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57965. this._updateDirection();
  57966. }
  57967. };
  57968. Sound.prototype._updateDirection = function () {
  57969. if (!this._connectedMesh || !this._soundPanner) {
  57970. return;
  57971. }
  57972. var mat = this._connectedMesh.getWorldMatrix();
  57973. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57974. direction.normalize();
  57975. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57976. };
  57977. Sound.prototype.updateDistanceFromListener = function () {
  57978. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57979. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57980. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57981. }
  57982. };
  57983. Sound.prototype.setAttenuationFunction = function (callback) {
  57984. this._customAttenuationFunction = callback;
  57985. };
  57986. /**
  57987. * Play the sound
  57988. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57989. * @param offset (optional) Start the sound setting it at a specific time
  57990. */
  57991. Sound.prototype.play = function (time, offset) {
  57992. var _this = this;
  57993. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57994. try {
  57995. if (this._startOffset < 0) {
  57996. time = -this._startOffset;
  57997. this._startOffset = 0;
  57998. }
  57999. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58000. if (!this._soundSource || !this._streamingSource) {
  58001. if (this.spatialSound && this._soundPanner) {
  58002. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58003. if (this._isDirectional) {
  58004. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58005. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58006. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58007. if (this._connectedMesh) {
  58008. this._updateDirection();
  58009. }
  58010. else {
  58011. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58012. }
  58013. }
  58014. }
  58015. }
  58016. if (this._streaming) {
  58017. if (!this._streamingSource) {
  58018. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58019. this._htmlAudioElement.onended = function () { _this._onended(); };
  58020. this._htmlAudioElement.playbackRate = this._playbackRate;
  58021. }
  58022. this._streamingSource.disconnect();
  58023. this._streamingSource.connect(this._inputAudioNode);
  58024. this._htmlAudioElement.play();
  58025. }
  58026. else {
  58027. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58028. this._soundSource.buffer = this._audioBuffer;
  58029. this._soundSource.connect(this._inputAudioNode);
  58030. this._soundSource.loop = this.loop;
  58031. this._soundSource.playbackRate.value = this._playbackRate;
  58032. this._soundSource.onended = function () { _this._onended(); };
  58033. if (this._soundSource.buffer) {
  58034. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58035. }
  58036. }
  58037. this._startTime = startTime;
  58038. this.isPlaying = true;
  58039. this.isPaused = false;
  58040. }
  58041. catch (ex) {
  58042. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58043. }
  58044. }
  58045. };
  58046. Sound.prototype._onended = function () {
  58047. this.isPlaying = false;
  58048. if (this.onended) {
  58049. this.onended();
  58050. }
  58051. };
  58052. /**
  58053. * Stop the sound
  58054. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58055. */
  58056. Sound.prototype.stop = function (time) {
  58057. if (this.isPlaying) {
  58058. if (this._streaming) {
  58059. this._htmlAudioElement.pause();
  58060. // Test needed for Firefox or it will generate an Invalid State Error
  58061. if (this._htmlAudioElement.currentTime > 0) {
  58062. this._htmlAudioElement.currentTime = 0;
  58063. }
  58064. }
  58065. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58066. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58067. this._soundSource.stop(stopTime);
  58068. this._soundSource.onended = function () { };
  58069. if (!this.isPaused) {
  58070. this._startOffset = 0;
  58071. }
  58072. }
  58073. this.isPlaying = false;
  58074. }
  58075. };
  58076. Sound.prototype.pause = function () {
  58077. if (this.isPlaying) {
  58078. this.isPaused = true;
  58079. if (this._streaming) {
  58080. this._htmlAudioElement.pause();
  58081. }
  58082. else if (BABYLON.Engine.audioEngine.audioContext) {
  58083. this.stop(0);
  58084. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58085. }
  58086. }
  58087. };
  58088. Sound.prototype.setVolume = function (newVolume, time) {
  58089. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58090. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58091. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58092. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58093. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58094. }
  58095. else {
  58096. this._soundGain.gain.value = newVolume;
  58097. }
  58098. }
  58099. this._volume = newVolume;
  58100. };
  58101. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58102. this._playbackRate = newPlaybackRate;
  58103. if (this.isPlaying) {
  58104. if (this._streaming) {
  58105. this._htmlAudioElement.playbackRate = this._playbackRate;
  58106. }
  58107. else if (this._soundSource) {
  58108. this._soundSource.playbackRate.value = this._playbackRate;
  58109. }
  58110. }
  58111. };
  58112. Sound.prototype.getVolume = function () {
  58113. return this._volume;
  58114. };
  58115. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58116. var _this = this;
  58117. if (this._connectedMesh && this._registerFunc) {
  58118. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58119. this._registerFunc = null;
  58120. }
  58121. this._connectedMesh = meshToConnectTo;
  58122. if (!this.spatialSound) {
  58123. this.spatialSound = true;
  58124. this._createSpatialParameters();
  58125. if (this.isPlaying && this.loop) {
  58126. this.stop();
  58127. this.play();
  58128. }
  58129. }
  58130. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58131. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58132. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58133. };
  58134. Sound.prototype.detachFromMesh = function () {
  58135. if (this._connectedMesh && this._registerFunc) {
  58136. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58137. this._registerFunc = null;
  58138. this._connectedMesh = null;
  58139. }
  58140. };
  58141. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58142. if (!node.getBoundingInfo) {
  58143. return;
  58144. }
  58145. var mesh = node;
  58146. var boundingInfo = mesh.getBoundingInfo();
  58147. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58148. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58149. this._updateDirection();
  58150. }
  58151. };
  58152. Sound.prototype.clone = function () {
  58153. var _this = this;
  58154. if (!this._streaming) {
  58155. var setBufferAndRun = function () {
  58156. if (_this._isReadyToPlay) {
  58157. clonedSound._audioBuffer = _this.getAudioBuffer();
  58158. clonedSound._isReadyToPlay = true;
  58159. if (clonedSound.autoplay) {
  58160. clonedSound.play();
  58161. }
  58162. }
  58163. else {
  58164. window.setTimeout(setBufferAndRun, 300);
  58165. }
  58166. };
  58167. var currentOptions = {
  58168. autoplay: this.autoplay, loop: this.loop,
  58169. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58170. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58171. refDistance: this.refDistance, distanceModel: this.distanceModel
  58172. };
  58173. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58174. if (this.useCustomAttenuation) {
  58175. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58176. }
  58177. clonedSound.setPosition(this._position);
  58178. clonedSound.setPlaybackRate(this._playbackRate);
  58179. setBufferAndRun();
  58180. return clonedSound;
  58181. }
  58182. else {
  58183. return null;
  58184. }
  58185. };
  58186. Sound.prototype.getAudioBuffer = function () {
  58187. return this._audioBuffer;
  58188. };
  58189. Sound.prototype.serialize = function () {
  58190. var serializationObject = {
  58191. name: this.name,
  58192. url: this.name,
  58193. autoplay: this.autoplay,
  58194. loop: this.loop,
  58195. volume: this._volume,
  58196. spatialSound: this.spatialSound,
  58197. maxDistance: this.maxDistance,
  58198. rolloffFactor: this.rolloffFactor,
  58199. refDistance: this.refDistance,
  58200. distanceModel: this.distanceModel,
  58201. playbackRate: this._playbackRate,
  58202. panningModel: this._panningModel,
  58203. soundTrackId: this.soundTrackId
  58204. };
  58205. if (this.spatialSound) {
  58206. if (this._connectedMesh)
  58207. serializationObject.connectedMeshId = this._connectedMesh.id;
  58208. serializationObject.position = this._position.asArray();
  58209. serializationObject.refDistance = this.refDistance;
  58210. serializationObject.distanceModel = this.distanceModel;
  58211. serializationObject.isDirectional = this._isDirectional;
  58212. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58213. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58214. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58215. serializationObject.coneOuterGain = this._coneOuterGain;
  58216. }
  58217. return serializationObject;
  58218. };
  58219. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58220. var soundName = parsedSound.name;
  58221. var soundUrl;
  58222. if (parsedSound.url) {
  58223. soundUrl = rootUrl + parsedSound.url;
  58224. }
  58225. else {
  58226. soundUrl = rootUrl + soundName;
  58227. }
  58228. var options = {
  58229. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58230. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58231. rolloffFactor: parsedSound.rolloffFactor,
  58232. refDistance: parsedSound.refDistance,
  58233. distanceModel: parsedSound.distanceModel,
  58234. playbackRate: parsedSound.playbackRate
  58235. };
  58236. var newSound;
  58237. if (!sourceSound) {
  58238. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58239. scene._addPendingData(newSound);
  58240. }
  58241. else {
  58242. var setBufferAndRun = function () {
  58243. if (sourceSound._isReadyToPlay) {
  58244. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58245. newSound._isReadyToPlay = true;
  58246. if (newSound.autoplay) {
  58247. newSound.play();
  58248. }
  58249. }
  58250. else {
  58251. window.setTimeout(setBufferAndRun, 300);
  58252. }
  58253. };
  58254. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58255. setBufferAndRun();
  58256. }
  58257. if (parsedSound.position) {
  58258. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58259. newSound.setPosition(soundPosition);
  58260. }
  58261. if (parsedSound.isDirectional) {
  58262. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58263. if (parsedSound.localDirectionToMesh) {
  58264. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58265. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58266. }
  58267. }
  58268. if (parsedSound.connectedMeshId) {
  58269. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58270. if (connectedMesh) {
  58271. newSound.attachToMesh(connectedMesh);
  58272. }
  58273. }
  58274. return newSound;
  58275. };
  58276. return Sound;
  58277. }());
  58278. BABYLON.Sound = Sound;
  58279. })(BABYLON || (BABYLON = {}));
  58280. //# sourceMappingURL=babylon.sound.js.map
  58281. var BABYLON;
  58282. (function (BABYLON) {
  58283. var SoundTrack = /** @class */ (function () {
  58284. function SoundTrack(scene, options) {
  58285. this.id = -1;
  58286. this._isMainTrack = false;
  58287. this._isInitialized = false;
  58288. this._scene = scene;
  58289. this.soundCollection = new Array();
  58290. this._options = options;
  58291. if (!this._isMainTrack) {
  58292. this._scene.soundTracks.push(this);
  58293. this.id = this._scene.soundTracks.length - 1;
  58294. }
  58295. }
  58296. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58297. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58298. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58299. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58300. if (this._options) {
  58301. if (this._options.volume) {
  58302. this._outputAudioNode.gain.value = this._options.volume;
  58303. }
  58304. if (this._options.mainTrack) {
  58305. this._isMainTrack = this._options.mainTrack;
  58306. }
  58307. }
  58308. this._isInitialized = true;
  58309. }
  58310. };
  58311. SoundTrack.prototype.dispose = function () {
  58312. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58313. if (this._connectedAnalyser) {
  58314. this._connectedAnalyser.stopDebugCanvas();
  58315. }
  58316. while (this.soundCollection.length) {
  58317. this.soundCollection[0].dispose();
  58318. }
  58319. if (this._outputAudioNode) {
  58320. this._outputAudioNode.disconnect();
  58321. }
  58322. this._outputAudioNode = null;
  58323. }
  58324. };
  58325. SoundTrack.prototype.AddSound = function (sound) {
  58326. if (!this._isInitialized) {
  58327. this._initializeSoundTrackAudioGraph();
  58328. }
  58329. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58330. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58331. }
  58332. if (sound.soundTrackId) {
  58333. if (sound.soundTrackId === -1) {
  58334. this._scene.mainSoundTrack.RemoveSound(sound);
  58335. }
  58336. else {
  58337. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58338. }
  58339. }
  58340. this.soundCollection.push(sound);
  58341. sound.soundTrackId = this.id;
  58342. };
  58343. SoundTrack.prototype.RemoveSound = function (sound) {
  58344. var index = this.soundCollection.indexOf(sound);
  58345. if (index !== -1) {
  58346. this.soundCollection.splice(index, 1);
  58347. }
  58348. };
  58349. SoundTrack.prototype.setVolume = function (newVolume) {
  58350. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58351. this._outputAudioNode.gain.value = newVolume;
  58352. }
  58353. };
  58354. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58355. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58356. for (var i = 0; i < this.soundCollection.length; i++) {
  58357. this.soundCollection[i].switchPanningModelToHRTF();
  58358. }
  58359. }
  58360. };
  58361. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58362. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58363. for (var i = 0; i < this.soundCollection.length; i++) {
  58364. this.soundCollection[i].switchPanningModelToEqualPower();
  58365. }
  58366. }
  58367. };
  58368. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58369. if (this._connectedAnalyser) {
  58370. this._connectedAnalyser.stopDebugCanvas();
  58371. }
  58372. this._connectedAnalyser = analyser;
  58373. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58374. this._outputAudioNode.disconnect();
  58375. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58376. }
  58377. };
  58378. return SoundTrack;
  58379. }());
  58380. BABYLON.SoundTrack = SoundTrack;
  58381. })(BABYLON || (BABYLON = {}));
  58382. //# sourceMappingURL=babylon.soundtrack.js.map
  58383. var BABYLON;
  58384. (function (BABYLON) {
  58385. var Analyser = /** @class */ (function () {
  58386. function Analyser(scene) {
  58387. this.SMOOTHING = 0.75;
  58388. this.FFT_SIZE = 512;
  58389. this.BARGRAPHAMPLITUDE = 256;
  58390. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58391. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58392. this._scene = scene;
  58393. this._audioEngine = BABYLON.Engine.audioEngine;
  58394. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58395. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58396. this._webAudioAnalyser.minDecibels = -140;
  58397. this._webAudioAnalyser.maxDecibels = 0;
  58398. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58399. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58400. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58401. }
  58402. }
  58403. Analyser.prototype.getFrequencyBinCount = function () {
  58404. if (this._audioEngine.canUseWebAudio) {
  58405. return this._webAudioAnalyser.frequencyBinCount;
  58406. }
  58407. else {
  58408. return 0;
  58409. }
  58410. };
  58411. Analyser.prototype.getByteFrequencyData = function () {
  58412. if (this._audioEngine.canUseWebAudio) {
  58413. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58414. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58415. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58416. }
  58417. return this._byteFreqs;
  58418. };
  58419. Analyser.prototype.getByteTimeDomainData = function () {
  58420. if (this._audioEngine.canUseWebAudio) {
  58421. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58422. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58423. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58424. }
  58425. return this._byteTime;
  58426. };
  58427. Analyser.prototype.getFloatFrequencyData = function () {
  58428. if (this._audioEngine.canUseWebAudio) {
  58429. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58430. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58431. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58432. }
  58433. return this._floatFreqs;
  58434. };
  58435. Analyser.prototype.drawDebugCanvas = function () {
  58436. var _this = this;
  58437. if (this._audioEngine.canUseWebAudio) {
  58438. if (!this._debugCanvas) {
  58439. this._debugCanvas = document.createElement("canvas");
  58440. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58441. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58442. this._debugCanvas.style.position = "absolute";
  58443. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58444. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58445. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58446. document.body.appendChild(this._debugCanvas);
  58447. this._registerFunc = function () {
  58448. _this.drawDebugCanvas();
  58449. };
  58450. this._scene.registerBeforeRender(this._registerFunc);
  58451. }
  58452. if (this._registerFunc && this._debugCanvasContext) {
  58453. var workingArray = this.getByteFrequencyData();
  58454. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58455. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58456. // Draw the frequency domain chart.
  58457. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58458. var value = workingArray[i];
  58459. var percent = value / this.BARGRAPHAMPLITUDE;
  58460. var height = this.DEBUGCANVASSIZE.height * percent;
  58461. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58462. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58463. var hue = i / this.getFrequencyBinCount() * 360;
  58464. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58465. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58466. }
  58467. }
  58468. }
  58469. };
  58470. Analyser.prototype.stopDebugCanvas = function () {
  58471. if (this._debugCanvas) {
  58472. if (this._registerFunc) {
  58473. this._scene.unregisterBeforeRender(this._registerFunc);
  58474. this._registerFunc = null;
  58475. }
  58476. document.body.removeChild(this._debugCanvas);
  58477. this._debugCanvas = null;
  58478. this._debugCanvasContext = null;
  58479. }
  58480. };
  58481. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58482. if (this._audioEngine.canUseWebAudio) {
  58483. inputAudioNode.connect(this._webAudioAnalyser);
  58484. this._webAudioAnalyser.connect(outputAudioNode);
  58485. }
  58486. };
  58487. Analyser.prototype.dispose = function () {
  58488. if (this._audioEngine.canUseWebAudio) {
  58489. this._webAudioAnalyser.disconnect();
  58490. }
  58491. };
  58492. return Analyser;
  58493. }());
  58494. BABYLON.Analyser = Analyser;
  58495. })(BABYLON || (BABYLON = {}));
  58496. //# sourceMappingURL=babylon.analyser.js.map
  58497. var BABYLON;
  58498. (function (BABYLON) {
  58499. var CubeTexture = /** @class */ (function (_super) {
  58500. __extends(CubeTexture, _super);
  58501. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58502. if (extensions === void 0) { extensions = null; }
  58503. if (noMipmap === void 0) { noMipmap = false; }
  58504. if (files === void 0) { files = null; }
  58505. if (onLoad === void 0) { onLoad = null; }
  58506. if (onError === void 0) { onError = null; }
  58507. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58508. if (prefiltered === void 0) { prefiltered = false; }
  58509. if (forcedExtension === void 0) { forcedExtension = null; }
  58510. var _this = _super.call(this, scene) || this;
  58511. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58512. /**
  58513. * Gets or sets the center of the bounding box associated with the cube texture
  58514. * It must define where the camera used to render the texture was set
  58515. */
  58516. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58517. _this.name = rootUrl;
  58518. _this.url = rootUrl;
  58519. _this._noMipmap = noMipmap;
  58520. _this.hasAlpha = false;
  58521. _this._format = format;
  58522. _this._prefiltered = prefiltered;
  58523. _this.isCube = true;
  58524. _this._textureMatrix = BABYLON.Matrix.Identity();
  58525. if (prefiltered) {
  58526. _this.gammaSpace = false;
  58527. }
  58528. if (!rootUrl && !files) {
  58529. return _this;
  58530. }
  58531. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58532. var lastDot = rootUrl.lastIndexOf(".");
  58533. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58534. var isDDS = (extension === ".dds");
  58535. if (!files) {
  58536. if (!isDDS && !extensions) {
  58537. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58538. }
  58539. files = [];
  58540. if (extensions) {
  58541. for (var index = 0; index < extensions.length; index++) {
  58542. files.push(rootUrl + extensions[index]);
  58543. }
  58544. }
  58545. }
  58546. _this._files = files;
  58547. if (!_this._texture) {
  58548. if (!scene.useDelayedTextureLoading) {
  58549. if (prefiltered) {
  58550. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58551. }
  58552. else {
  58553. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58554. }
  58555. }
  58556. else {
  58557. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58558. }
  58559. }
  58560. else if (onLoad) {
  58561. if (_this._texture.isReady) {
  58562. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58563. }
  58564. else {
  58565. _this._texture.onLoadedObservable.add(onLoad);
  58566. }
  58567. }
  58568. return _this;
  58569. }
  58570. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58571. get: function () {
  58572. return this._boundingBoxSize;
  58573. },
  58574. /**
  58575. * Gets or sets the size of the bounding box associated with the cube texture
  58576. * When defined, the cubemap will switch to local mode
  58577. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58578. * @example https://www.babylonjs-playground.com/#RNASML
  58579. */
  58580. set: function (value) {
  58581. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58582. return;
  58583. }
  58584. this._boundingBoxSize = value;
  58585. var scene = this.getScene();
  58586. if (scene) {
  58587. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58588. }
  58589. },
  58590. enumerable: true,
  58591. configurable: true
  58592. });
  58593. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58594. var rootUrlKey = "";
  58595. files.forEach(function (url) { return rootUrlKey += url; });
  58596. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58597. };
  58598. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58599. if (forcedExtension === void 0) { forcedExtension = null; }
  58600. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58601. };
  58602. // Methods
  58603. CubeTexture.prototype.delayLoad = function () {
  58604. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58605. return;
  58606. }
  58607. var scene = this.getScene();
  58608. if (!scene) {
  58609. return;
  58610. }
  58611. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58612. this._texture = this._getFromCache(this.url, this._noMipmap);
  58613. if (!this._texture) {
  58614. if (this._prefiltered) {
  58615. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58616. }
  58617. else {
  58618. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58619. }
  58620. }
  58621. };
  58622. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58623. return this._textureMatrix;
  58624. };
  58625. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58626. this._textureMatrix = value;
  58627. };
  58628. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58629. var texture = BABYLON.SerializationHelper.Parse(function () {
  58630. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58631. }, parsedTexture, scene);
  58632. // Local Cubemaps
  58633. if (parsedTexture.boundingBoxPosition) {
  58634. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58635. }
  58636. if (parsedTexture.boundingBoxSize) {
  58637. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58638. }
  58639. // Animations
  58640. if (parsedTexture.animations) {
  58641. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58642. var parsedAnimation = parsedTexture.animations[animationIndex];
  58643. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58644. }
  58645. }
  58646. return texture;
  58647. };
  58648. CubeTexture.prototype.clone = function () {
  58649. var _this = this;
  58650. return BABYLON.SerializationHelper.Clone(function () {
  58651. var scene = _this.getScene();
  58652. if (!scene) {
  58653. return _this;
  58654. }
  58655. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58656. }, this);
  58657. };
  58658. return CubeTexture;
  58659. }(BABYLON.BaseTexture));
  58660. BABYLON.CubeTexture = CubeTexture;
  58661. })(BABYLON || (BABYLON = {}));
  58662. //# sourceMappingURL=babylon.cubeTexture.js.map
  58663. var BABYLON;
  58664. (function (BABYLON) {
  58665. var RenderTargetTexture = /** @class */ (function (_super) {
  58666. __extends(RenderTargetTexture, _super);
  58667. /**
  58668. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58669. * or used a shadow, depth texture...
  58670. * @param name The friendly name of the texture
  58671. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  58672. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58673. * @param generateMipMaps True if mip maps need to be generated after render.
  58674. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58675. * @param type The type of the buffer in the RTT (int, half float, float...)
  58676. * @param isCube True if a cube texture needs to be created
  58677. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58678. * @param generateDepthBuffer True to generate a depth buffer
  58679. * @param generateStencilBuffer True to generate a stencil buffer
  58680. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58681. */
  58682. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58683. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58684. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58685. if (isCube === void 0) { isCube = false; }
  58686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58687. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58688. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58689. if (isMulti === void 0) { isMulti = false; }
  58690. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58691. _this.isCube = isCube;
  58692. /**
  58693. * Use this list to define the list of mesh you want to render.
  58694. */
  58695. _this.renderList = new Array();
  58696. _this.renderParticles = true;
  58697. _this.renderSprites = false;
  58698. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58699. _this.ignoreCameraViewport = false;
  58700. // Events
  58701. /**
  58702. * An event triggered when the texture is unbind.
  58703. * @type {BABYLON.Observable}
  58704. */
  58705. _this.onBeforeBindObservable = new BABYLON.Observable();
  58706. /**
  58707. * An event triggered when the texture is unbind.
  58708. * @type {BABYLON.Observable}
  58709. */
  58710. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58711. /**
  58712. * An event triggered before rendering the texture
  58713. * @type {BABYLON.Observable}
  58714. */
  58715. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58716. /**
  58717. * An event triggered after rendering the texture
  58718. * @type {BABYLON.Observable}
  58719. */
  58720. _this.onAfterRenderObservable = new BABYLON.Observable();
  58721. /**
  58722. * An event triggered after the texture clear
  58723. * @type {BABYLON.Observable}
  58724. */
  58725. _this.onClearObservable = new BABYLON.Observable();
  58726. _this._currentRefreshId = -1;
  58727. _this._refreshRate = 1;
  58728. _this._samples = 1;
  58729. /**
  58730. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58731. * It must define where the camera used to render the texture is set
  58732. */
  58733. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58734. scene = _this.getScene();
  58735. if (!scene) {
  58736. return _this;
  58737. }
  58738. _this._engine = scene.getEngine();
  58739. _this.name = name;
  58740. _this.isRenderTarget = true;
  58741. _this._initialSizeParameter = size;
  58742. _this._processSizeParameter(size);
  58743. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58744. });
  58745. _this._generateMipMaps = generateMipMaps ? true : false;
  58746. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58747. // Rendering groups
  58748. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58749. if (isMulti) {
  58750. return _this;
  58751. }
  58752. _this._renderTargetOptions = {
  58753. generateMipMaps: generateMipMaps,
  58754. type: type,
  58755. samplingMode: samplingMode,
  58756. generateDepthBuffer: generateDepthBuffer,
  58757. generateStencilBuffer: generateStencilBuffer
  58758. };
  58759. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58760. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58761. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58762. }
  58763. if (isCube) {
  58764. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58765. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58766. _this._textureMatrix = BABYLON.Matrix.Identity();
  58767. }
  58768. else {
  58769. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58770. }
  58771. return _this;
  58772. }
  58773. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58774. get: function () {
  58775. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58776. },
  58777. enumerable: true,
  58778. configurable: true
  58779. });
  58780. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58781. get: function () {
  58782. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58783. },
  58784. enumerable: true,
  58785. configurable: true
  58786. });
  58787. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58788. get: function () {
  58789. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58790. },
  58791. enumerable: true,
  58792. configurable: true
  58793. });
  58794. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58795. set: function (callback) {
  58796. if (this._onAfterUnbindObserver) {
  58797. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58798. }
  58799. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58800. },
  58801. enumerable: true,
  58802. configurable: true
  58803. });
  58804. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58805. set: function (callback) {
  58806. if (this._onBeforeRenderObserver) {
  58807. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58808. }
  58809. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58810. },
  58811. enumerable: true,
  58812. configurable: true
  58813. });
  58814. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58815. set: function (callback) {
  58816. if (this._onAfterRenderObserver) {
  58817. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58818. }
  58819. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58820. },
  58821. enumerable: true,
  58822. configurable: true
  58823. });
  58824. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58825. set: function (callback) {
  58826. if (this._onClearObserver) {
  58827. this.onClearObservable.remove(this._onClearObserver);
  58828. }
  58829. this._onClearObserver = this.onClearObservable.add(callback);
  58830. },
  58831. enumerable: true,
  58832. configurable: true
  58833. });
  58834. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58835. get: function () {
  58836. return this._renderTargetOptions;
  58837. },
  58838. enumerable: true,
  58839. configurable: true
  58840. });
  58841. RenderTargetTexture.prototype._onRatioRescale = function () {
  58842. if (this._sizeRatio) {
  58843. this.resize(this._initialSizeParameter);
  58844. }
  58845. };
  58846. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58847. get: function () {
  58848. return this._boundingBoxSize;
  58849. },
  58850. /**
  58851. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58852. * When defined, the cubemap will switch to local mode
  58853. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58854. * @example https://www.babylonjs-playground.com/#RNASML
  58855. */
  58856. set: function (value) {
  58857. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58858. return;
  58859. }
  58860. this._boundingBoxSize = value;
  58861. var scene = this.getScene();
  58862. if (scene) {
  58863. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58864. }
  58865. },
  58866. enumerable: true,
  58867. configurable: true
  58868. });
  58869. /**
  58870. * Creates a depth stencil texture.
  58871. * This is only available in WebGL 2 or with the depth texture extension available.
  58872. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  58873. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  58874. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  58875. */
  58876. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  58877. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  58878. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  58879. if (generateStencil === void 0) { generateStencil = false; }
  58880. if (!this.getScene()) {
  58881. return;
  58882. }
  58883. var engine = this.getScene().getEngine();
  58884. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  58885. bilinearFiltering: bilinearFiltering,
  58886. comparisonFunction: comparisonFunction,
  58887. generateStencil: generateStencil,
  58888. isCube: this.isCube
  58889. });
  58890. engine.setFrameBufferDepthStencilTexture(this);
  58891. };
  58892. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58893. if (size.ratio) {
  58894. this._sizeRatio = size.ratio;
  58895. this._size = {
  58896. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58897. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58898. };
  58899. }
  58900. else {
  58901. this._size = size;
  58902. }
  58903. };
  58904. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58905. get: function () {
  58906. return this._samples;
  58907. },
  58908. set: function (value) {
  58909. if (this._samples === value) {
  58910. return;
  58911. }
  58912. var scene = this.getScene();
  58913. if (!scene) {
  58914. return;
  58915. }
  58916. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58917. },
  58918. enumerable: true,
  58919. configurable: true
  58920. });
  58921. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58922. this._currentRefreshId = -1;
  58923. };
  58924. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58925. get: function () {
  58926. return this._refreshRate;
  58927. },
  58928. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58929. set: function (value) {
  58930. this._refreshRate = value;
  58931. this.resetRefreshCounter();
  58932. },
  58933. enumerable: true,
  58934. configurable: true
  58935. });
  58936. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58937. if (!this._postProcessManager) {
  58938. var scene = this.getScene();
  58939. if (!scene) {
  58940. return;
  58941. }
  58942. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58943. this._postProcesses = new Array();
  58944. }
  58945. this._postProcesses.push(postProcess);
  58946. this._postProcesses[0].autoClear = false;
  58947. };
  58948. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58949. if (!this._postProcesses) {
  58950. return;
  58951. }
  58952. if (dispose) {
  58953. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58954. var postProcess = _a[_i];
  58955. postProcess.dispose();
  58956. }
  58957. }
  58958. this._postProcesses = [];
  58959. };
  58960. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58961. if (!this._postProcesses) {
  58962. return;
  58963. }
  58964. var index = this._postProcesses.indexOf(postProcess);
  58965. if (index === -1) {
  58966. return;
  58967. }
  58968. this._postProcesses.splice(index, 1);
  58969. if (this._postProcesses.length > 0) {
  58970. this._postProcesses[0].autoClear = false;
  58971. }
  58972. };
  58973. RenderTargetTexture.prototype._shouldRender = function () {
  58974. if (this._currentRefreshId === -1) {
  58975. this._currentRefreshId = 1;
  58976. return true;
  58977. }
  58978. if (this.refreshRate === this._currentRefreshId) {
  58979. this._currentRefreshId = 1;
  58980. return true;
  58981. }
  58982. this._currentRefreshId++;
  58983. return false;
  58984. };
  58985. RenderTargetTexture.prototype.getRenderSize = function () {
  58986. if (this._size.width) {
  58987. return this._size.width;
  58988. }
  58989. return this._size;
  58990. };
  58991. RenderTargetTexture.prototype.getRenderWidth = function () {
  58992. if (this._size.width) {
  58993. return this._size.width;
  58994. }
  58995. return this._size;
  58996. };
  58997. RenderTargetTexture.prototype.getRenderHeight = function () {
  58998. if (this._size.width) {
  58999. return this._size.height;
  59000. }
  59001. return this._size;
  59002. };
  59003. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59004. get: function () {
  59005. return true;
  59006. },
  59007. enumerable: true,
  59008. configurable: true
  59009. });
  59010. RenderTargetTexture.prototype.scale = function (ratio) {
  59011. var newSize = this.getRenderSize() * ratio;
  59012. this.resize(newSize);
  59013. };
  59014. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59015. if (this.isCube) {
  59016. return this._textureMatrix;
  59017. }
  59018. return _super.prototype.getReflectionTextureMatrix.call(this);
  59019. };
  59020. RenderTargetTexture.prototype.resize = function (size) {
  59021. this.releaseInternalTexture();
  59022. var scene = this.getScene();
  59023. if (!scene) {
  59024. return;
  59025. }
  59026. this._processSizeParameter(size);
  59027. if (this.isCube) {
  59028. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59029. }
  59030. else {
  59031. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59032. }
  59033. };
  59034. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59035. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59036. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59037. var scene = this.getScene();
  59038. if (!scene) {
  59039. return;
  59040. }
  59041. var engine = scene.getEngine();
  59042. if (this.useCameraPostProcesses !== undefined) {
  59043. useCameraPostProcess = this.useCameraPostProcesses;
  59044. }
  59045. if (this._waitingRenderList) {
  59046. this.renderList = [];
  59047. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59048. var id = this._waitingRenderList[index];
  59049. var mesh_1 = scene.getMeshByID(id);
  59050. if (mesh_1) {
  59051. this.renderList.push(mesh_1);
  59052. }
  59053. }
  59054. delete this._waitingRenderList;
  59055. }
  59056. // Is predicate defined?
  59057. if (this.renderListPredicate) {
  59058. if (this.renderList) {
  59059. this.renderList.splice(0); // Clear previous renderList
  59060. }
  59061. else {
  59062. this.renderList = [];
  59063. }
  59064. var scene = this.getScene();
  59065. if (!scene) {
  59066. return;
  59067. }
  59068. var sceneMeshes = scene.meshes;
  59069. for (var index = 0; index < sceneMeshes.length; index++) {
  59070. var mesh = sceneMeshes[index];
  59071. if (this.renderListPredicate(mesh)) {
  59072. this.renderList.push(mesh);
  59073. }
  59074. }
  59075. }
  59076. this.onBeforeBindObservable.notifyObservers(this);
  59077. // Set custom projection.
  59078. // Needs to be before binding to prevent changing the aspect ratio.
  59079. var camera;
  59080. if (this.activeCamera) {
  59081. camera = this.activeCamera;
  59082. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59083. if (this.activeCamera !== scene.activeCamera) {
  59084. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59085. }
  59086. }
  59087. else {
  59088. camera = scene.activeCamera;
  59089. if (camera) {
  59090. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59091. }
  59092. }
  59093. // Prepare renderingManager
  59094. this._renderingManager.reset();
  59095. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59096. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59097. var sceneRenderId = scene.getRenderId();
  59098. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59099. var mesh = currentRenderList[meshIndex];
  59100. if (mesh) {
  59101. if (!mesh.isReady(this.refreshRate === 0)) {
  59102. this.resetRefreshCounter();
  59103. continue;
  59104. }
  59105. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59106. var isMasked = void 0;
  59107. if (!this.renderList && camera) {
  59108. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59109. }
  59110. else {
  59111. isMasked = false;
  59112. }
  59113. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59114. mesh._activate(sceneRenderId);
  59115. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59116. var subMesh = mesh.subMeshes[subIndex];
  59117. scene._activeIndices.addCount(subMesh.indexCount, false);
  59118. this._renderingManager.dispatch(subMesh, mesh);
  59119. }
  59120. }
  59121. }
  59122. }
  59123. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59124. var particleSystem = scene.particleSystems[particleIndex];
  59125. var emitter = particleSystem.emitter;
  59126. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59127. continue;
  59128. }
  59129. if (currentRenderList.indexOf(emitter) >= 0) {
  59130. this._renderingManager.dispatchParticles(particleSystem);
  59131. }
  59132. }
  59133. if (this.isCube) {
  59134. for (var face = 0; face < 6; face++) {
  59135. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59136. scene.incrementRenderId();
  59137. scene.resetCachedMaterial();
  59138. }
  59139. }
  59140. else {
  59141. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59142. }
  59143. this.onAfterUnbindObservable.notifyObservers(this);
  59144. if (scene.activeCamera) {
  59145. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59146. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59147. }
  59148. engine.setViewport(scene.activeCamera.viewport);
  59149. }
  59150. scene.resetCachedMaterial();
  59151. };
  59152. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59153. var minimum = 128;
  59154. var x = renderDimension * scale;
  59155. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59156. // Ensure we don't exceed the render dimension (while staying POT)
  59157. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59158. };
  59159. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59160. var _this = this;
  59161. if (!this._texture) {
  59162. return;
  59163. }
  59164. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59165. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59166. });
  59167. };
  59168. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59169. var scene = this.getScene();
  59170. if (!scene) {
  59171. return;
  59172. }
  59173. var engine = scene.getEngine();
  59174. if (!this._texture) {
  59175. return;
  59176. }
  59177. // Bind
  59178. if (this._postProcessManager) {
  59179. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59180. }
  59181. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59182. if (this._texture) {
  59183. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59184. }
  59185. }
  59186. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59187. // Clear
  59188. if (this.onClearObservable.hasObservers()) {
  59189. this.onClearObservable.notifyObservers(engine);
  59190. }
  59191. else {
  59192. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59193. }
  59194. if (!this._doNotChangeAspectRatio) {
  59195. scene.updateTransformMatrix(true);
  59196. }
  59197. // Render
  59198. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59199. if (this._postProcessManager) {
  59200. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59201. }
  59202. else if (useCameraPostProcess) {
  59203. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59204. }
  59205. if (!this._doNotChangeAspectRatio) {
  59206. scene.updateTransformMatrix(true);
  59207. }
  59208. // Dump ?
  59209. if (dumpForDebug) {
  59210. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59211. }
  59212. // Unbind
  59213. if (!this.isCube || faceIndex === 5) {
  59214. if (this.isCube) {
  59215. if (faceIndex === 5) {
  59216. engine.generateMipMapsForCubemap(this._texture);
  59217. }
  59218. }
  59219. this.unbindFrameBuffer(engine, faceIndex);
  59220. }
  59221. else {
  59222. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59223. }
  59224. };
  59225. /**
  59226. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59227. * This allowed control for front to back rendering or reversly depending of the special needs.
  59228. *
  59229. * @param renderingGroupId The rendering group id corresponding to its index
  59230. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59231. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59232. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59233. */
  59234. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59235. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59236. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59237. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59238. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59239. };
  59240. /**
  59241. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59242. *
  59243. * @param renderingGroupId The rendering group id corresponding to its index
  59244. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59245. */
  59246. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59247. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59248. };
  59249. RenderTargetTexture.prototype.clone = function () {
  59250. var textureSize = this.getSize();
  59251. 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);
  59252. // Base texture
  59253. newTexture.hasAlpha = this.hasAlpha;
  59254. newTexture.level = this.level;
  59255. // RenderTarget Texture
  59256. newTexture.coordinatesMode = this.coordinatesMode;
  59257. if (this.renderList) {
  59258. newTexture.renderList = this.renderList.slice(0);
  59259. }
  59260. return newTexture;
  59261. };
  59262. RenderTargetTexture.prototype.serialize = function () {
  59263. if (!this.name) {
  59264. return null;
  59265. }
  59266. var serializationObject = _super.prototype.serialize.call(this);
  59267. serializationObject.renderTargetSize = this.getRenderSize();
  59268. serializationObject.renderList = [];
  59269. if (this.renderList) {
  59270. for (var index = 0; index < this.renderList.length; index++) {
  59271. serializationObject.renderList.push(this.renderList[index].id);
  59272. }
  59273. }
  59274. return serializationObject;
  59275. };
  59276. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59277. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59278. var objBuffer = this.getInternalTexture();
  59279. var scene = this.getScene();
  59280. if (objBuffer && scene) {
  59281. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59282. }
  59283. };
  59284. RenderTargetTexture.prototype.dispose = function () {
  59285. if (this._postProcessManager) {
  59286. this._postProcessManager.dispose();
  59287. this._postProcessManager = null;
  59288. }
  59289. this.clearPostProcesses(true);
  59290. if (this._resizeObserver) {
  59291. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59292. this._resizeObserver = null;
  59293. }
  59294. this.renderList = null;
  59295. // Remove from custom render targets
  59296. var scene = this.getScene();
  59297. if (!scene) {
  59298. return;
  59299. }
  59300. var index = scene.customRenderTargets.indexOf(this);
  59301. if (index >= 0) {
  59302. scene.customRenderTargets.splice(index, 1);
  59303. }
  59304. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59305. var camera = _a[_i];
  59306. index = camera.customRenderTargets.indexOf(this);
  59307. if (index >= 0) {
  59308. camera.customRenderTargets.splice(index, 1);
  59309. }
  59310. }
  59311. _super.prototype.dispose.call(this);
  59312. };
  59313. RenderTargetTexture.prototype._rebuild = function () {
  59314. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59315. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59316. }
  59317. if (this._postProcessManager) {
  59318. this._postProcessManager._rebuild();
  59319. }
  59320. };
  59321. /**
  59322. * Clear the info related to rendering groups preventing retention point in material dispose.
  59323. */
  59324. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59325. if (this._renderingManager) {
  59326. this._renderingManager.freeRenderingGroups();
  59327. }
  59328. };
  59329. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59330. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59331. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59332. return RenderTargetTexture;
  59333. }(BABYLON.Texture));
  59334. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59335. })(BABYLON || (BABYLON = {}));
  59336. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59337. var BABYLON;
  59338. (function (BABYLON) {
  59339. ;
  59340. var MultiRenderTarget = /** @class */ (function (_super) {
  59341. __extends(MultiRenderTarget, _super);
  59342. function MultiRenderTarget(name, size, count, scene, options) {
  59343. var _this = this;
  59344. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59345. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59346. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59347. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59348. _this._engine = scene.getEngine();
  59349. if (!_this.isSupported) {
  59350. _this.dispose();
  59351. return;
  59352. }
  59353. var types = [];
  59354. var samplingModes = [];
  59355. for (var i = 0; i < count; i++) {
  59356. if (options && options.types && options.types[i] !== undefined) {
  59357. types.push(options.types[i]);
  59358. }
  59359. else {
  59360. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59361. }
  59362. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59363. samplingModes.push(options.samplingModes[i]);
  59364. }
  59365. else {
  59366. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59367. }
  59368. }
  59369. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59370. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59371. _this._size = size;
  59372. _this._multiRenderTargetOptions = {
  59373. samplingModes: samplingModes,
  59374. generateMipMaps: generateMipMaps,
  59375. generateDepthBuffer: generateDepthBuffer,
  59376. generateStencilBuffer: generateStencilBuffer,
  59377. generateDepthTexture: generateDepthTexture,
  59378. types: types,
  59379. textureCount: count
  59380. };
  59381. _this._createInternalTextures();
  59382. _this._createTextures();
  59383. return _this;
  59384. }
  59385. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59386. get: function () {
  59387. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59388. },
  59389. enumerable: true,
  59390. configurable: true
  59391. });
  59392. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59393. get: function () {
  59394. return this._textures;
  59395. },
  59396. enumerable: true,
  59397. configurable: true
  59398. });
  59399. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59400. get: function () {
  59401. return this._textures[this._textures.length - 1];
  59402. },
  59403. enumerable: true,
  59404. configurable: true
  59405. });
  59406. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59407. set: function (wrap) {
  59408. if (this._textures) {
  59409. for (var i = 0; i < this._textures.length; i++) {
  59410. this._textures[i].wrapU = wrap;
  59411. }
  59412. }
  59413. },
  59414. enumerable: true,
  59415. configurable: true
  59416. });
  59417. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59418. set: function (wrap) {
  59419. if (this._textures) {
  59420. for (var i = 0; i < this._textures.length; i++) {
  59421. this._textures[i].wrapV = wrap;
  59422. }
  59423. }
  59424. },
  59425. enumerable: true,
  59426. configurable: true
  59427. });
  59428. MultiRenderTarget.prototype._rebuild = function () {
  59429. this.releaseInternalTextures();
  59430. this._createInternalTextures();
  59431. for (var i = 0; i < this._internalTextures.length; i++) {
  59432. var texture = this._textures[i];
  59433. texture._texture = this._internalTextures[i];
  59434. }
  59435. // Keeps references to frame buffer and stencil/depth buffer
  59436. this._texture = this._internalTextures[0];
  59437. };
  59438. MultiRenderTarget.prototype._createInternalTextures = function () {
  59439. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59440. };
  59441. MultiRenderTarget.prototype._createTextures = function () {
  59442. this._textures = [];
  59443. for (var i = 0; i < this._internalTextures.length; i++) {
  59444. var texture = new BABYLON.Texture(null, this.getScene());
  59445. texture._texture = this._internalTextures[i];
  59446. this._textures.push(texture);
  59447. }
  59448. // Keeps references to frame buffer and stencil/depth buffer
  59449. this._texture = this._internalTextures[0];
  59450. };
  59451. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59452. get: function () {
  59453. return this._samples;
  59454. },
  59455. set: function (value) {
  59456. if (this._samples === value) {
  59457. return;
  59458. }
  59459. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59460. },
  59461. enumerable: true,
  59462. configurable: true
  59463. });
  59464. MultiRenderTarget.prototype.resize = function (size) {
  59465. this.releaseInternalTextures();
  59466. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59467. this._createInternalTextures();
  59468. };
  59469. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59470. var _this = this;
  59471. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59472. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59473. });
  59474. };
  59475. MultiRenderTarget.prototype.dispose = function () {
  59476. this.releaseInternalTextures();
  59477. _super.prototype.dispose.call(this);
  59478. };
  59479. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59480. if (!this._internalTextures) {
  59481. return;
  59482. }
  59483. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59484. if (this._internalTextures[i] !== undefined) {
  59485. this._internalTextures[i].dispose();
  59486. this._internalTextures.splice(i, 1);
  59487. }
  59488. }
  59489. };
  59490. return MultiRenderTarget;
  59491. }(BABYLON.RenderTargetTexture));
  59492. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59493. })(BABYLON || (BABYLON = {}));
  59494. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59495. var BABYLON;
  59496. (function (BABYLON) {
  59497. var MirrorTexture = /** @class */ (function (_super) {
  59498. __extends(MirrorTexture, _super);
  59499. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59500. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59501. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59502. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59503. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59504. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59505. _this._transformMatrix = BABYLON.Matrix.Zero();
  59506. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59507. _this._adaptiveBlurKernel = 0;
  59508. _this._blurKernelX = 0;
  59509. _this._blurKernelY = 0;
  59510. _this._blurRatio = 1.0;
  59511. _this.ignoreCameraViewport = true;
  59512. _this.onBeforeRenderObservable.add(function () {
  59513. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59514. _this._savedViewMatrix = scene.getViewMatrix();
  59515. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59516. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59517. scene.clipPlane = _this.mirrorPlane;
  59518. scene.getEngine().cullBackFaces = false;
  59519. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59520. });
  59521. _this.onAfterRenderObservable.add(function () {
  59522. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59523. scene.getEngine().cullBackFaces = true;
  59524. scene._mirroredCameraPosition = null;
  59525. delete scene.clipPlane;
  59526. });
  59527. return _this;
  59528. }
  59529. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59530. get: function () {
  59531. return this._blurRatio;
  59532. },
  59533. set: function (value) {
  59534. if (this._blurRatio === value) {
  59535. return;
  59536. }
  59537. this._blurRatio = value;
  59538. this._preparePostProcesses();
  59539. },
  59540. enumerable: true,
  59541. configurable: true
  59542. });
  59543. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59544. set: function (value) {
  59545. this._adaptiveBlurKernel = value;
  59546. this._autoComputeBlurKernel();
  59547. },
  59548. enumerable: true,
  59549. configurable: true
  59550. });
  59551. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59552. set: function (value) {
  59553. this.blurKernelX = value;
  59554. this.blurKernelY = value;
  59555. },
  59556. enumerable: true,
  59557. configurable: true
  59558. });
  59559. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59560. get: function () {
  59561. return this._blurKernelX;
  59562. },
  59563. set: function (value) {
  59564. if (this._blurKernelX === value) {
  59565. return;
  59566. }
  59567. this._blurKernelX = value;
  59568. this._preparePostProcesses();
  59569. },
  59570. enumerable: true,
  59571. configurable: true
  59572. });
  59573. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59574. get: function () {
  59575. return this._blurKernelY;
  59576. },
  59577. set: function (value) {
  59578. if (this._blurKernelY === value) {
  59579. return;
  59580. }
  59581. this._blurKernelY = value;
  59582. this._preparePostProcesses();
  59583. },
  59584. enumerable: true,
  59585. configurable: true
  59586. });
  59587. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59588. var engine = this.getScene().getEngine();
  59589. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59590. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59591. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59592. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59593. };
  59594. MirrorTexture.prototype._onRatioRescale = function () {
  59595. if (this._sizeRatio) {
  59596. this.resize(this._initialSizeParameter);
  59597. if (!this._adaptiveBlurKernel) {
  59598. this._preparePostProcesses();
  59599. }
  59600. }
  59601. if (this._adaptiveBlurKernel) {
  59602. this._autoComputeBlurKernel();
  59603. }
  59604. };
  59605. MirrorTexture.prototype._preparePostProcesses = function () {
  59606. this.clearPostProcesses(true);
  59607. if (this._blurKernelX && this._blurKernelY) {
  59608. var engine = this.getScene().getEngine();
  59609. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59610. 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);
  59611. this._blurX.autoClear = false;
  59612. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59613. this._blurX.inputTexture = this._texture;
  59614. }
  59615. else {
  59616. this._blurX.alwaysForcePOT = true;
  59617. }
  59618. 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);
  59619. this._blurY.autoClear = false;
  59620. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59621. this.addPostProcess(this._blurX);
  59622. this.addPostProcess(this._blurY);
  59623. }
  59624. else {
  59625. if (this._blurY) {
  59626. this.removePostProcess(this._blurY);
  59627. this._blurY.dispose();
  59628. this._blurY = null;
  59629. }
  59630. if (this._blurX) {
  59631. this.removePostProcess(this._blurX);
  59632. this._blurX.dispose();
  59633. this._blurX = null;
  59634. }
  59635. }
  59636. };
  59637. MirrorTexture.prototype.clone = function () {
  59638. var scene = this.getScene();
  59639. if (!scene) {
  59640. return this;
  59641. }
  59642. var textureSize = this.getSize();
  59643. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59644. // Base texture
  59645. newTexture.hasAlpha = this.hasAlpha;
  59646. newTexture.level = this.level;
  59647. // Mirror Texture
  59648. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59649. if (this.renderList) {
  59650. newTexture.renderList = this.renderList.slice(0);
  59651. }
  59652. return newTexture;
  59653. };
  59654. MirrorTexture.prototype.serialize = function () {
  59655. if (!this.name) {
  59656. return null;
  59657. }
  59658. var serializationObject = _super.prototype.serialize.call(this);
  59659. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59660. return serializationObject;
  59661. };
  59662. return MirrorTexture;
  59663. }(BABYLON.RenderTargetTexture));
  59664. BABYLON.MirrorTexture = MirrorTexture;
  59665. })(BABYLON || (BABYLON = {}));
  59666. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59667. var BABYLON;
  59668. (function (BABYLON) {
  59669. /**
  59670. * Creates a refraction texture used by refraction channel of the standard material.
  59671. * @param name the texture name
  59672. * @param size size of the underlying texture
  59673. * @param scene root scene
  59674. */
  59675. var RefractionTexture = /** @class */ (function (_super) {
  59676. __extends(RefractionTexture, _super);
  59677. function RefractionTexture(name, size, scene, generateMipMaps) {
  59678. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59679. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59680. _this.depth = 2.0;
  59681. _this.onBeforeRenderObservable.add(function () {
  59682. scene.clipPlane = _this.refractionPlane;
  59683. });
  59684. _this.onAfterRenderObservable.add(function () {
  59685. delete scene.clipPlane;
  59686. });
  59687. return _this;
  59688. }
  59689. RefractionTexture.prototype.clone = function () {
  59690. var scene = this.getScene();
  59691. if (!scene) {
  59692. return this;
  59693. }
  59694. var textureSize = this.getSize();
  59695. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59696. // Base texture
  59697. newTexture.hasAlpha = this.hasAlpha;
  59698. newTexture.level = this.level;
  59699. // Refraction Texture
  59700. newTexture.refractionPlane = this.refractionPlane.clone();
  59701. if (this.renderList) {
  59702. newTexture.renderList = this.renderList.slice(0);
  59703. }
  59704. newTexture.depth = this.depth;
  59705. return newTexture;
  59706. };
  59707. RefractionTexture.prototype.serialize = function () {
  59708. if (!this.name) {
  59709. return null;
  59710. }
  59711. var serializationObject = _super.prototype.serialize.call(this);
  59712. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59713. serializationObject.depth = this.depth;
  59714. return serializationObject;
  59715. };
  59716. return RefractionTexture;
  59717. }(BABYLON.RenderTargetTexture));
  59718. BABYLON.RefractionTexture = RefractionTexture;
  59719. })(BABYLON || (BABYLON = {}));
  59720. //# sourceMappingURL=babylon.refractionTexture.js.map
  59721. var BABYLON;
  59722. (function (BABYLON) {
  59723. var DynamicTexture = /** @class */ (function (_super) {
  59724. __extends(DynamicTexture, _super);
  59725. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59726. if (scene === void 0) { scene = null; }
  59727. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59728. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59729. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59730. _this.name = name;
  59731. _this._engine = _this.getScene().getEngine();
  59732. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59733. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59734. _this._generateMipMaps = generateMipMaps;
  59735. if (options.getContext) {
  59736. _this._canvas = options;
  59737. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59738. }
  59739. else {
  59740. _this._canvas = document.createElement("canvas");
  59741. if (options.width) {
  59742. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59743. }
  59744. else {
  59745. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59746. }
  59747. }
  59748. var textureSize = _this.getSize();
  59749. _this._canvas.width = textureSize.width;
  59750. _this._canvas.height = textureSize.height;
  59751. _this._context = _this._canvas.getContext("2d");
  59752. return _this;
  59753. }
  59754. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59755. get: function () {
  59756. return true;
  59757. },
  59758. enumerable: true,
  59759. configurable: true
  59760. });
  59761. DynamicTexture.prototype._recreate = function (textureSize) {
  59762. this._canvas.width = textureSize.width;
  59763. this._canvas.height = textureSize.height;
  59764. this.releaseInternalTexture();
  59765. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59766. };
  59767. DynamicTexture.prototype.scale = function (ratio) {
  59768. var textureSize = this.getSize();
  59769. textureSize.width *= ratio;
  59770. textureSize.height *= ratio;
  59771. this._recreate(textureSize);
  59772. };
  59773. DynamicTexture.prototype.scaleTo = function (width, height) {
  59774. var textureSize = this.getSize();
  59775. textureSize.width = width;
  59776. textureSize.height = height;
  59777. this._recreate(textureSize);
  59778. };
  59779. DynamicTexture.prototype.getContext = function () {
  59780. return this._context;
  59781. };
  59782. DynamicTexture.prototype.clear = function () {
  59783. var size = this.getSize();
  59784. this._context.fillRect(0, 0, size.width, size.height);
  59785. };
  59786. DynamicTexture.prototype.update = function (invertY) {
  59787. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59788. };
  59789. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59790. if (update === void 0) { update = true; }
  59791. var size = this.getSize();
  59792. if (clearColor) {
  59793. this._context.fillStyle = clearColor;
  59794. this._context.fillRect(0, 0, size.width, size.height);
  59795. }
  59796. this._context.font = font;
  59797. if (x === null || x === undefined) {
  59798. var textSize = this._context.measureText(text);
  59799. x = (size.width - textSize.width) / 2;
  59800. }
  59801. if (y === null || y === undefined) {
  59802. var fontSize = parseInt((font.replace(/\D/g, '')));
  59803. ;
  59804. y = (size.height / 2) + (fontSize / 3.65);
  59805. }
  59806. this._context.fillStyle = color;
  59807. this._context.fillText(text, x, y);
  59808. if (update) {
  59809. this.update(invertY);
  59810. }
  59811. };
  59812. DynamicTexture.prototype.clone = function () {
  59813. var scene = this.getScene();
  59814. if (!scene) {
  59815. return this;
  59816. }
  59817. var textureSize = this.getSize();
  59818. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59819. // Base texture
  59820. newTexture.hasAlpha = this.hasAlpha;
  59821. newTexture.level = this.level;
  59822. // Dynamic Texture
  59823. newTexture.wrapU = this.wrapU;
  59824. newTexture.wrapV = this.wrapV;
  59825. return newTexture;
  59826. };
  59827. DynamicTexture.prototype._rebuild = function () {
  59828. this.update();
  59829. };
  59830. return DynamicTexture;
  59831. }(BABYLON.Texture));
  59832. BABYLON.DynamicTexture = DynamicTexture;
  59833. })(BABYLON || (BABYLON = {}));
  59834. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59835. var BABYLON;
  59836. (function (BABYLON) {
  59837. var VideoTexture = /** @class */ (function (_super) {
  59838. __extends(VideoTexture, _super);
  59839. /**
  59840. * Creates a video texture.
  59841. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59842. * @param {string | null} name optional name, will detect from video source, if not defined
  59843. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59844. * @param {BABYLON.Scene} scene is obviously the current scene.
  59845. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59846. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59847. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59848. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59849. */
  59850. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59851. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59852. if (invertY === void 0) { invertY = false; }
  59853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59854. if (settings === void 0) { settings = {
  59855. autoPlay: true,
  59856. loop: true,
  59857. autoUpdateTexture: true,
  59858. }; }
  59859. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59860. _this._createInternalTexture = function () {
  59861. if (_this._texture != null) {
  59862. return;
  59863. }
  59864. if (!_this._engine.needPOTTextures ||
  59865. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59866. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59867. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59868. }
  59869. else {
  59870. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59871. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59872. _this._generateMipMaps = false;
  59873. }
  59874. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59875. _this._texture.isReady = true;
  59876. _this._updateInternalTexture();
  59877. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59878. _this.onLoadObservable.notifyObservers(_this);
  59879. }
  59880. };
  59881. _this.reset = function () {
  59882. if (_this._texture == null) {
  59883. return;
  59884. }
  59885. _this._texture.dispose();
  59886. _this._texture = null;
  59887. };
  59888. _this._updateInternalTexture = function (e) {
  59889. if (_this._texture == null || !_this._texture.isReady) {
  59890. return;
  59891. }
  59892. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59893. return;
  59894. }
  59895. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59896. };
  59897. _this._engine = _this.getScene().getEngine();
  59898. _this._generateMipMaps = generateMipMaps;
  59899. _this._samplingMode = samplingMode;
  59900. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59901. _this.name = name || _this._getName(src);
  59902. _this.video = _this._getVideo(src);
  59903. if (settings.autoPlay !== undefined) {
  59904. _this.video.autoplay = settings.autoPlay;
  59905. }
  59906. if (settings.loop !== undefined) {
  59907. _this.video.loop = settings.loop;
  59908. }
  59909. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59910. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59911. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59912. _this.video.addEventListener("emptied", _this.reset);
  59913. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59914. _this._createInternalTexture();
  59915. }
  59916. return _this;
  59917. }
  59918. VideoTexture.prototype._getName = function (src) {
  59919. if (src instanceof HTMLVideoElement) {
  59920. return src.currentSrc;
  59921. }
  59922. if (typeof src === "object") {
  59923. return src.toString();
  59924. }
  59925. return src;
  59926. };
  59927. ;
  59928. VideoTexture.prototype._getVideo = function (src) {
  59929. if (src instanceof HTMLVideoElement) {
  59930. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59931. return src;
  59932. }
  59933. var video = document.createElement("video");
  59934. if (typeof src === "string") {
  59935. BABYLON.Tools.SetCorsBehavior(src, video);
  59936. video.src = src;
  59937. }
  59938. else {
  59939. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59940. src.forEach(function (url) {
  59941. var source = document.createElement("source");
  59942. source.src = url;
  59943. video.appendChild(source);
  59944. });
  59945. }
  59946. return video;
  59947. };
  59948. ;
  59949. /**
  59950. * Internal method to initiate `update`.
  59951. */
  59952. VideoTexture.prototype._rebuild = function () {
  59953. this.update();
  59954. };
  59955. /**
  59956. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59957. */
  59958. VideoTexture.prototype.update = function () {
  59959. if (!this.autoUpdateTexture) {
  59960. // Expecting user to call `updateTexture` manually
  59961. return;
  59962. }
  59963. this.updateTexture(true);
  59964. };
  59965. /**
  59966. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59967. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59968. */
  59969. VideoTexture.prototype.updateTexture = function (isVisible) {
  59970. if (!isVisible) {
  59971. return;
  59972. }
  59973. if (this.video.paused) {
  59974. return;
  59975. }
  59976. this._updateInternalTexture();
  59977. };
  59978. /**
  59979. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59980. * @param url New url.
  59981. */
  59982. VideoTexture.prototype.updateURL = function (url) {
  59983. this.video.src = url;
  59984. };
  59985. VideoTexture.prototype.dispose = function () {
  59986. _super.prototype.dispose.call(this);
  59987. this.video.removeEventListener("canplay", this._createInternalTexture);
  59988. this.video.removeEventListener("paused", this._updateInternalTexture);
  59989. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59990. this.video.removeEventListener("emptied", this.reset);
  59991. this.video.pause();
  59992. };
  59993. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59994. var video = document.createElement("video");
  59995. var constraintsDeviceId;
  59996. if (constraints && constraints.deviceId) {
  59997. constraintsDeviceId = {
  59998. exact: constraints.deviceId,
  59999. };
  60000. }
  60001. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60002. if (navigator.mediaDevices) {
  60003. navigator.mediaDevices.getUserMedia({ video: constraints })
  60004. .then(function (stream) {
  60005. if (video.mozSrcObject !== undefined) {
  60006. // hack for Firefox < 19
  60007. video.mozSrcObject = stream;
  60008. }
  60009. else {
  60010. video.srcObject = stream;
  60011. }
  60012. var onPlaying = function () {
  60013. if (onReady) {
  60014. onReady(new VideoTexture("video", video, scene, true, true));
  60015. }
  60016. video.removeEventListener("playing", onPlaying);
  60017. };
  60018. video.addEventListener("playing", onPlaying);
  60019. video.play();
  60020. })
  60021. .catch(function (err) {
  60022. BABYLON.Tools.Error(err.name);
  60023. });
  60024. }
  60025. else {
  60026. navigator.getUserMedia =
  60027. navigator.getUserMedia ||
  60028. navigator.webkitGetUserMedia ||
  60029. navigator.mozGetUserMedia ||
  60030. navigator.msGetUserMedia;
  60031. if (navigator.getUserMedia) {
  60032. navigator.getUserMedia({
  60033. video: {
  60034. deviceId: constraintsDeviceId,
  60035. width: {
  60036. min: (constraints && constraints.minWidth) || 256,
  60037. max: (constraints && constraints.maxWidth) || 640,
  60038. },
  60039. height: {
  60040. min: (constraints && constraints.minHeight) || 256,
  60041. max: (constraints && constraints.maxHeight) || 480,
  60042. },
  60043. },
  60044. }, function (stream) {
  60045. if (video.mozSrcObject !== undefined) {
  60046. // hack for Firefox < 19
  60047. video.mozSrcObject = stream;
  60048. }
  60049. else {
  60050. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60051. }
  60052. video.play();
  60053. if (onReady) {
  60054. onReady(new VideoTexture("video", video, scene, true, true));
  60055. }
  60056. }, function (e) {
  60057. BABYLON.Tools.Error(e.name);
  60058. });
  60059. }
  60060. }
  60061. };
  60062. return VideoTexture;
  60063. }(BABYLON.Texture));
  60064. BABYLON.VideoTexture = VideoTexture;
  60065. })(BABYLON || (BABYLON = {}));
  60066. //# sourceMappingURL=babylon.videoTexture.js.map
  60067. var BABYLON;
  60068. (function (BABYLON) {
  60069. var RawTexture = /** @class */ (function (_super) {
  60070. __extends(RawTexture, _super);
  60071. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60072. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60073. if (invertY === void 0) { invertY = false; }
  60074. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60075. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60076. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60077. _this.format = format;
  60078. _this._engine = scene.getEngine();
  60079. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60080. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60081. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60082. return _this;
  60083. }
  60084. RawTexture.prototype.update = function (data) {
  60085. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60086. };
  60087. // Statics
  60088. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60089. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60090. if (invertY === void 0) { invertY = false; }
  60091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60092. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60093. };
  60094. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60095. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60096. if (invertY === void 0) { invertY = false; }
  60097. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60098. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60099. };
  60100. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60101. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60102. if (invertY === void 0) { invertY = false; }
  60103. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60104. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60105. };
  60106. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60107. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60108. if (invertY === void 0) { invertY = false; }
  60109. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60110. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60111. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60112. };
  60113. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60114. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60115. if (invertY === void 0) { invertY = false; }
  60116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60117. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60118. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60119. };
  60120. return RawTexture;
  60121. }(BABYLON.Texture));
  60122. BABYLON.RawTexture = RawTexture;
  60123. })(BABYLON || (BABYLON = {}));
  60124. //# sourceMappingURL=babylon.rawTexture.js.map
  60125. var BABYLON;
  60126. (function (BABYLON) {
  60127. /**
  60128. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60129. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60130. */
  60131. var PostProcess = /** @class */ (function () {
  60132. /**
  60133. * Creates a new instance of @see PostProcess
  60134. * @param name The name of the PostProcess.
  60135. * @param fragmentUrl The url of the fragment shader to be used.
  60136. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60137. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60138. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60139. * @param camera The camera to apply the render pass to.
  60140. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60141. * @param engine The engine which the post process will be applied. (default: current engine)
  60142. * @param reusable If the post process can be reused on the same frame. (default: false)
  60143. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60144. * @param textureType Type of textures used when performing the post process. (default: 0)
  60145. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60146. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  60147. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60148. */
  60149. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60150. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60151. if (defines === void 0) { defines = null; }
  60152. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60153. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60154. if (blockCompilation === void 0) { blockCompilation = false; }
  60155. this.name = name;
  60156. /**
  60157. * Width of the texture to apply the post process on
  60158. */
  60159. this.width = -1;
  60160. /**
  60161. * Height of the texture to apply the post process on
  60162. */
  60163. this.height = -1;
  60164. /**
  60165. * If the buffer needs to be cleared before applying the post process. (default: true)
  60166. * Should be set to false if shader will overwrite all previous pixels.
  60167. */
  60168. this.autoClear = true;
  60169. /**
  60170. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60171. */
  60172. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60173. /**
  60174. * Animations to be used for the post processing
  60175. */
  60176. this.animations = new Array();
  60177. /**
  60178. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60179. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60180. */
  60181. this.enablePixelPerfectMode = false;
  60182. /**
  60183. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60184. */
  60185. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60186. /**
  60187. * Force textures to be a power of two (default: false)
  60188. */
  60189. this.alwaysForcePOT = false;
  60190. /**
  60191. * Number of sample textures (default: 1)
  60192. */
  60193. this.samples = 1;
  60194. /**
  60195. * Modify the scale of the post process to be the same as the viewport (default: false)
  60196. */
  60197. this.adaptScaleToCurrentViewport = false;
  60198. this._reusable = false;
  60199. /**
  60200. * Smart array of input and output textures for the post process.
  60201. */
  60202. this._textures = new BABYLON.SmartArray(2);
  60203. /**
  60204. * The index in _textures that corresponds to the output texture.
  60205. */
  60206. this._currentRenderTextureInd = 0;
  60207. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60208. this._texelSize = BABYLON.Vector2.Zero();
  60209. // Events
  60210. /**
  60211. * An event triggered when the postprocess is activated.
  60212. * @type {BABYLON.Observable}
  60213. */
  60214. this.onActivateObservable = new BABYLON.Observable();
  60215. /**
  60216. * An event triggered when the postprocess changes its size.
  60217. * @type {BABYLON.Observable}
  60218. */
  60219. this.onSizeChangedObservable = new BABYLON.Observable();
  60220. /**
  60221. * An event triggered when the postprocess applies its effect.
  60222. * @type {BABYLON.Observable}
  60223. */
  60224. this.onApplyObservable = new BABYLON.Observable();
  60225. /**
  60226. * An event triggered before rendering the postprocess
  60227. * @type {BABYLON.Observable}
  60228. */
  60229. this.onBeforeRenderObservable = new BABYLON.Observable();
  60230. /**
  60231. * An event triggered after rendering the postprocess
  60232. * @type {BABYLON.Observable}
  60233. */
  60234. this.onAfterRenderObservable = new BABYLON.Observable();
  60235. if (camera != null) {
  60236. this._camera = camera;
  60237. this._scene = camera.getScene();
  60238. camera.attachPostProcess(this);
  60239. this._engine = this._scene.getEngine();
  60240. this._scene.postProcesses.push(this);
  60241. }
  60242. else if (engine) {
  60243. this._engine = engine;
  60244. this._engine.postProcesses.push(this);
  60245. }
  60246. this._options = options;
  60247. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60248. this._reusable = reusable || false;
  60249. this._textureType = textureType;
  60250. this._samplers = samplers || [];
  60251. this._samplers.push("textureSampler");
  60252. this._fragmentUrl = fragmentUrl;
  60253. this._vertexUrl = vertexUrl;
  60254. this._parameters = parameters || [];
  60255. this._parameters.push("scale");
  60256. this._indexParameters = indexParameters;
  60257. if (!blockCompilation) {
  60258. this.updateEffect(defines);
  60259. }
  60260. }
  60261. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60262. /**
  60263. * A function that is added to the onActivateObservable
  60264. */
  60265. set: function (callback) {
  60266. if (this._onActivateObserver) {
  60267. this.onActivateObservable.remove(this._onActivateObserver);
  60268. }
  60269. if (callback) {
  60270. this._onActivateObserver = this.onActivateObservable.add(callback);
  60271. }
  60272. },
  60273. enumerable: true,
  60274. configurable: true
  60275. });
  60276. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60277. /**
  60278. * A function that is added to the onSizeChangedObservable
  60279. */
  60280. set: function (callback) {
  60281. if (this._onSizeChangedObserver) {
  60282. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60283. }
  60284. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60285. },
  60286. enumerable: true,
  60287. configurable: true
  60288. });
  60289. Object.defineProperty(PostProcess.prototype, "onApply", {
  60290. /**
  60291. * A function that is added to the onApplyObservable
  60292. */
  60293. set: function (callback) {
  60294. if (this._onApplyObserver) {
  60295. this.onApplyObservable.remove(this._onApplyObserver);
  60296. }
  60297. this._onApplyObserver = this.onApplyObservable.add(callback);
  60298. },
  60299. enumerable: true,
  60300. configurable: true
  60301. });
  60302. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60303. /**
  60304. * A function that is added to the onBeforeRenderObservable
  60305. */
  60306. set: function (callback) {
  60307. if (this._onBeforeRenderObserver) {
  60308. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60309. }
  60310. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60311. },
  60312. enumerable: true,
  60313. configurable: true
  60314. });
  60315. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60316. /**
  60317. * A function that is added to the onAfterRenderObservable
  60318. */
  60319. set: function (callback) {
  60320. if (this._onAfterRenderObserver) {
  60321. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60322. }
  60323. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60324. },
  60325. enumerable: true,
  60326. configurable: true
  60327. });
  60328. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60329. /**
  60330. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  60331. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60332. */
  60333. get: function () {
  60334. return this._textures.data[this._currentRenderTextureInd];
  60335. },
  60336. set: function (value) {
  60337. this._forcedOutputTexture = value;
  60338. },
  60339. enumerable: true,
  60340. configurable: true
  60341. });
  60342. /**
  60343. * Gets the camera which post process is applied to.
  60344. * @returns The camera the post process is applied to.
  60345. */
  60346. PostProcess.prototype.getCamera = function () {
  60347. return this._camera;
  60348. };
  60349. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60350. /**
  60351. * Gets the texel size of the postprocess.
  60352. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60353. */
  60354. get: function () {
  60355. if (this._shareOutputWithPostProcess) {
  60356. return this._shareOutputWithPostProcess.texelSize;
  60357. }
  60358. if (this._forcedOutputTexture) {
  60359. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60360. }
  60361. return this._texelSize;
  60362. },
  60363. enumerable: true,
  60364. configurable: true
  60365. });
  60366. /**
  60367. * Gets the engine which this post process belongs to.
  60368. * @returns The engine the post process was enabled with.
  60369. */
  60370. PostProcess.prototype.getEngine = function () {
  60371. return this._engine;
  60372. };
  60373. /**
  60374. * The effect that is created when initializing the post process.
  60375. * @returns The created effect corrisponding the the postprocess.
  60376. */
  60377. PostProcess.prototype.getEffect = function () {
  60378. return this._effect;
  60379. };
  60380. /**
  60381. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60382. * @param postProcess The post process to share the output with.
  60383. * @returns This post process.
  60384. */
  60385. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60386. this._disposeTextures();
  60387. this._shareOutputWithPostProcess = postProcess;
  60388. return this;
  60389. };
  60390. /**
  60391. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60392. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60393. */
  60394. PostProcess.prototype.useOwnOutput = function () {
  60395. if (this._textures.length == 0) {
  60396. this._textures = new BABYLON.SmartArray(2);
  60397. }
  60398. this._shareOutputWithPostProcess = null;
  60399. };
  60400. /**
  60401. * Updates the effect with the current post process compile time values and recompiles the shader.
  60402. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60403. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60404. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60405. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  60406. * @param onCompiled Called when the shader has been compiled.
  60407. * @param onError Called if there is an error when compiling a shader.
  60408. */
  60409. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60410. if (defines === void 0) { defines = null; }
  60411. if (uniforms === void 0) { uniforms = null; }
  60412. if (samplers === void 0) { samplers = null; }
  60413. 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);
  60414. };
  60415. /**
  60416. * The post process is reusable if it can be used multiple times within one frame.
  60417. * @returns If the post process is reusable
  60418. */
  60419. PostProcess.prototype.isReusable = function () {
  60420. return this._reusable;
  60421. };
  60422. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60423. PostProcess.prototype.markTextureDirty = function () {
  60424. this.width = -1;
  60425. };
  60426. /**
  60427. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60428. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  60429. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60430. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60431. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60432. */
  60433. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60434. var _this = this;
  60435. if (sourceTexture === void 0) { sourceTexture = null; }
  60436. camera = camera || this._camera;
  60437. var scene = camera.getScene();
  60438. var engine = scene.getEngine();
  60439. var maxSize = engine.getCaps().maxTextureSize;
  60440. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60441. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60442. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  60443. var webVRCamera = camera.parent;
  60444. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60445. requiredWidth /= 2;
  60446. }
  60447. var desiredWidth = (this._options.width || requiredWidth);
  60448. var desiredHeight = this._options.height || requiredHeight;
  60449. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60450. if (this.adaptScaleToCurrentViewport) {
  60451. var currentViewport = engine.currentViewport;
  60452. if (currentViewport) {
  60453. desiredWidth *= currentViewport.width;
  60454. desiredHeight *= currentViewport.height;
  60455. }
  60456. }
  60457. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60458. if (!this._options.width) {
  60459. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60460. }
  60461. if (!this._options.height) {
  60462. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60463. }
  60464. }
  60465. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60466. if (this._textures.length > 0) {
  60467. for (var i = 0; i < this._textures.length; i++) {
  60468. this._engine._releaseTexture(this._textures.data[i]);
  60469. }
  60470. this._textures.reset();
  60471. }
  60472. this.width = desiredWidth;
  60473. this.height = desiredHeight;
  60474. var textureSize = { width: this.width, height: this.height };
  60475. var textureOptions = {
  60476. generateMipMaps: false,
  60477. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60478. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60479. samplingMode: this.renderTargetSamplingMode,
  60480. type: this._textureType
  60481. };
  60482. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60483. if (this._reusable) {
  60484. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60485. }
  60486. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60487. this.onSizeChangedObservable.notifyObservers(this);
  60488. }
  60489. this._textures.forEach(function (texture) {
  60490. if (texture.samples !== _this.samples) {
  60491. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60492. }
  60493. });
  60494. }
  60495. var target;
  60496. if (this._shareOutputWithPostProcess) {
  60497. target = this._shareOutputWithPostProcess.inputTexture;
  60498. }
  60499. else if (this._forcedOutputTexture) {
  60500. target = this._forcedOutputTexture;
  60501. this.width = this._forcedOutputTexture.width;
  60502. this.height = this._forcedOutputTexture.height;
  60503. }
  60504. else {
  60505. target = this.inputTexture;
  60506. }
  60507. // Bind the input of this post process to be used as the output of the previous post process.
  60508. if (this.enablePixelPerfectMode) {
  60509. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60510. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60511. }
  60512. else {
  60513. this._scaleRatio.copyFromFloats(1, 1);
  60514. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60515. }
  60516. this.onActivateObservable.notifyObservers(camera);
  60517. // Clear
  60518. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60519. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60520. }
  60521. if (this._reusable) {
  60522. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60523. }
  60524. };
  60525. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60526. /**
  60527. * If the post process is supported.
  60528. */
  60529. get: function () {
  60530. return this._effect.isSupported;
  60531. },
  60532. enumerable: true,
  60533. configurable: true
  60534. });
  60535. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60536. /**
  60537. * The aspect ratio of the output texture.
  60538. */
  60539. get: function () {
  60540. if (this._shareOutputWithPostProcess) {
  60541. return this._shareOutputWithPostProcess.aspectRatio;
  60542. }
  60543. if (this._forcedOutputTexture) {
  60544. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60545. }
  60546. return this.width / this.height;
  60547. },
  60548. enumerable: true,
  60549. configurable: true
  60550. });
  60551. /**
  60552. * Get a value indicating if the post-process is ready to be used
  60553. * @returns true if the post-process is ready (shader is compiled)
  60554. */
  60555. PostProcess.prototype.isReady = function () {
  60556. return this._effect && this._effect.isReady();
  60557. };
  60558. /**
  60559. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60560. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60561. */
  60562. PostProcess.prototype.apply = function () {
  60563. // Check
  60564. if (!this._effect || !this._effect.isReady())
  60565. return null;
  60566. // States
  60567. this._engine.enableEffect(this._effect);
  60568. this._engine.setState(false);
  60569. this._engine.setDepthBuffer(false);
  60570. this._engine.setDepthWrite(false);
  60571. // Alpha
  60572. this._engine.setAlphaMode(this.alphaMode);
  60573. if (this.alphaConstants) {
  60574. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60575. }
  60576. // Bind the output texture of the preivous post process as the input to this post process.
  60577. var source;
  60578. if (this._shareOutputWithPostProcess) {
  60579. source = this._shareOutputWithPostProcess.inputTexture;
  60580. }
  60581. else if (this._forcedOutputTexture) {
  60582. source = this._forcedOutputTexture;
  60583. }
  60584. else {
  60585. source = this.inputTexture;
  60586. }
  60587. this._effect._bindTexture("textureSampler", source);
  60588. // Parameters
  60589. this._effect.setVector2("scale", this._scaleRatio);
  60590. this.onApplyObservable.notifyObservers(this._effect);
  60591. return this._effect;
  60592. };
  60593. PostProcess.prototype._disposeTextures = function () {
  60594. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60595. return;
  60596. }
  60597. if (this._textures.length > 0) {
  60598. for (var i = 0; i < this._textures.length; i++) {
  60599. this._engine._releaseTexture(this._textures.data[i]);
  60600. }
  60601. }
  60602. this._textures.dispose();
  60603. };
  60604. /**
  60605. * Disposes the post process.
  60606. * @param camera The camera to dispose the post process on.
  60607. */
  60608. PostProcess.prototype.dispose = function (camera) {
  60609. camera = camera || this._camera;
  60610. this._disposeTextures();
  60611. if (this._scene) {
  60612. var index_1 = this._scene.postProcesses.indexOf(this);
  60613. if (index_1 !== -1) {
  60614. this._scene.postProcesses.splice(index_1, 1);
  60615. }
  60616. }
  60617. else {
  60618. var index_2 = this._engine.postProcesses.indexOf(this);
  60619. if (index_2 !== -1) {
  60620. this._engine.postProcesses.splice(index_2, 1);
  60621. }
  60622. }
  60623. if (!camera) {
  60624. return;
  60625. }
  60626. camera.detachPostProcess(this);
  60627. var index = camera._postProcesses.indexOf(this);
  60628. if (index === 0 && camera._postProcesses.length > 0) {
  60629. var firstPostProcess = this._camera._getFirstPostProcess();
  60630. if (firstPostProcess) {
  60631. firstPostProcess.markTextureDirty();
  60632. }
  60633. }
  60634. this.onActivateObservable.clear();
  60635. this.onAfterRenderObservable.clear();
  60636. this.onApplyObservable.clear();
  60637. this.onBeforeRenderObservable.clear();
  60638. this.onSizeChangedObservable.clear();
  60639. };
  60640. return PostProcess;
  60641. }());
  60642. BABYLON.PostProcess = PostProcess;
  60643. })(BABYLON || (BABYLON = {}));
  60644. //# sourceMappingURL=babylon.postProcess.js.map
  60645. var BABYLON;
  60646. (function (BABYLON) {
  60647. var PassPostProcess = /** @class */ (function (_super) {
  60648. __extends(PassPostProcess, _super);
  60649. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60650. if (camera === void 0) { camera = null; }
  60651. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60652. if (blockCompilation === void 0) { blockCompilation = false; }
  60653. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60654. }
  60655. return PassPostProcess;
  60656. }(BABYLON.PostProcess));
  60657. BABYLON.PassPostProcess = PassPostProcess;
  60658. })(BABYLON || (BABYLON = {}));
  60659. //# sourceMappingURL=babylon.passPostProcess.js.map
  60660. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60661. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60662. s = arguments[i];
  60663. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60664. t[p] = s[p];
  60665. }
  60666. return t;
  60667. };
  60668. var BABYLON;
  60669. (function (BABYLON) {
  60670. /**
  60671. * Default implementation of @see IShadowGenerator.
  60672. * This is the main object responsible of generating shadows in the framework.
  60673. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60674. */
  60675. var ShadowGenerator = /** @class */ (function () {
  60676. /**
  60677. * Creates a ShadowGenerator object.
  60678. * A ShadowGenerator is the required tool to use the shadows.
  60679. * Each light casting shadows needs to use its own ShadowGenerator.
  60680. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60681. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60682. * @param light The light object generating the shadows.
  60683. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  60684. */
  60685. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60686. this._bias = 0.00005;
  60687. this._normalBias = 0;
  60688. this._blurBoxOffset = 1;
  60689. this._blurScale = 2;
  60690. this._blurKernel = 1;
  60691. this._useKernelBlur = false;
  60692. this._filter = ShadowGenerator.FILTER_NONE;
  60693. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  60694. this._contactHardeningLightSizeUVRatio = 0.1;
  60695. this._darkness = 0;
  60696. this._transparencyShadow = false;
  60697. /**
  60698. * Controls the extent to which the shadows fade out at the edge of the frustum
  60699. * Used only by directionals and spots
  60700. */
  60701. this.frustumEdgeFalloff = 0;
  60702. /**
  60703. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60704. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60705. * It might on the other hand introduce peter panning.
  60706. */
  60707. this.forceBackFacesOnly = false;
  60708. this._lightDirection = BABYLON.Vector3.Zero();
  60709. this._viewMatrix = BABYLON.Matrix.Zero();
  60710. this._projectionMatrix = BABYLON.Matrix.Zero();
  60711. this._transformMatrix = BABYLON.Matrix.Zero();
  60712. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60713. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60714. this._currentFaceIndex = 0;
  60715. this._currentFaceIndexCache = 0;
  60716. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60717. this._mapSize = mapSize;
  60718. this._light = light;
  60719. this._scene = light.getScene();
  60720. light._shadowGenerator = this;
  60721. // Texture type fallback from float to int if not supported.
  60722. var caps = this._scene.getEngine().getCaps();
  60723. if (!useFullFloatFirst) {
  60724. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60725. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60726. }
  60727. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60728. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60729. }
  60730. else {
  60731. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60732. }
  60733. }
  60734. else {
  60735. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60736. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60737. }
  60738. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60739. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60740. }
  60741. else {
  60742. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60743. }
  60744. }
  60745. this._initializeGenerator();
  60746. this._applyFilterValues();
  60747. }
  60748. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60749. /**
  60750. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  60751. */
  60752. get: function () {
  60753. return this._bias;
  60754. },
  60755. /**
  60756. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  60757. */
  60758. set: function (bias) {
  60759. this._bias = bias;
  60760. },
  60761. enumerable: true,
  60762. configurable: true
  60763. });
  60764. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  60765. /**
  60766. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60767. */
  60768. get: function () {
  60769. return this._normalBias;
  60770. },
  60771. /**
  60772. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60773. */
  60774. set: function (normalBias) {
  60775. this._normalBias = normalBias;
  60776. },
  60777. enumerable: true,
  60778. configurable: true
  60779. });
  60780. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60781. /**
  60782. * Gets the blur box offset: offset applied during the blur pass.
  60783. * Only usefull if useKernelBlur = false
  60784. */
  60785. get: function () {
  60786. return this._blurBoxOffset;
  60787. },
  60788. /**
  60789. * Sets the blur box offset: offset applied during the blur pass.
  60790. * Only usefull if useKernelBlur = false
  60791. */
  60792. set: function (value) {
  60793. if (this._blurBoxOffset === value) {
  60794. return;
  60795. }
  60796. this._blurBoxOffset = value;
  60797. this._disposeBlurPostProcesses();
  60798. },
  60799. enumerable: true,
  60800. configurable: true
  60801. });
  60802. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60803. /**
  60804. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60805. * 2 means half of the size.
  60806. */
  60807. get: function () {
  60808. return this._blurScale;
  60809. },
  60810. /**
  60811. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60812. * 2 means half of the size.
  60813. */
  60814. set: function (value) {
  60815. if (this._blurScale === value) {
  60816. return;
  60817. }
  60818. this._blurScale = value;
  60819. this._disposeBlurPostProcesses();
  60820. },
  60821. enumerable: true,
  60822. configurable: true
  60823. });
  60824. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60825. /**
  60826. * Gets the blur kernel: kernel size of the blur pass.
  60827. * Only usefull if useKernelBlur = true
  60828. */
  60829. get: function () {
  60830. return this._blurKernel;
  60831. },
  60832. /**
  60833. * Sets the blur kernel: kernel size of the blur pass.
  60834. * Only usefull if useKernelBlur = true
  60835. */
  60836. set: function (value) {
  60837. if (this._blurKernel === value) {
  60838. return;
  60839. }
  60840. this._blurKernel = value;
  60841. this._disposeBlurPostProcesses();
  60842. },
  60843. enumerable: true,
  60844. configurable: true
  60845. });
  60846. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60847. /**
  60848. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60849. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60850. */
  60851. get: function () {
  60852. return this._useKernelBlur;
  60853. },
  60854. /**
  60855. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60856. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60857. */
  60858. set: function (value) {
  60859. if (this._useKernelBlur === value) {
  60860. return;
  60861. }
  60862. this._useKernelBlur = value;
  60863. this._disposeBlurPostProcesses();
  60864. },
  60865. enumerable: true,
  60866. configurable: true
  60867. });
  60868. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60869. /**
  60870. * Gets the depth scale used in ESM mode.
  60871. */
  60872. get: function () {
  60873. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60874. },
  60875. /**
  60876. * Sets the depth scale used in ESM mode.
  60877. * This can override the scale stored on the light.
  60878. */
  60879. set: function (value) {
  60880. this._depthScale = value;
  60881. },
  60882. enumerable: true,
  60883. configurable: true
  60884. });
  60885. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60886. /**
  60887. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60888. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60889. */
  60890. get: function () {
  60891. return this._filter;
  60892. },
  60893. /**
  60894. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60895. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60896. */
  60897. set: function (value) {
  60898. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60899. if (this._light.needCube()) {
  60900. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60901. this.useExponentialShadowMap = true;
  60902. return;
  60903. }
  60904. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60905. this.useCloseExponentialShadowMap = true;
  60906. return;
  60907. }
  60908. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60909. this.usePoissonSampling = true;
  60910. return;
  60911. }
  60912. }
  60913. // Weblg1 fallback for PCF.
  60914. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60915. if (this._scene.getEngine().webGLVersion === 1) {
  60916. this.usePoissonSampling = true;
  60917. return;
  60918. }
  60919. }
  60920. if (this._filter === value) {
  60921. return;
  60922. }
  60923. this._filter = value;
  60924. this._disposeBlurPostProcesses();
  60925. this._applyFilterValues();
  60926. this._light._markMeshesAsLightDirty();
  60927. },
  60928. enumerable: true,
  60929. configurable: true
  60930. });
  60931. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60932. /**
  60933. * Gets if the current filter is set to Poisson Sampling.
  60934. */
  60935. get: function () {
  60936. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60937. },
  60938. /**
  60939. * Sets the current filter to Poisson Sampling.
  60940. */
  60941. set: function (value) {
  60942. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60943. return;
  60944. }
  60945. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60946. },
  60947. enumerable: true,
  60948. configurable: true
  60949. });
  60950. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60951. /**
  60952. * Gets if the current filter is set to VSM.
  60953. * DEPRECATED. Should use useExponentialShadowMap instead.
  60954. */
  60955. get: function () {
  60956. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60957. return this.useExponentialShadowMap;
  60958. },
  60959. /**
  60960. * Sets the current filter is to VSM.
  60961. * DEPRECATED. Should use useExponentialShadowMap instead.
  60962. */
  60963. set: function (value) {
  60964. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60965. this.useExponentialShadowMap = value;
  60966. },
  60967. enumerable: true,
  60968. configurable: true
  60969. });
  60970. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60971. /**
  60972. * Gets if the current filter is set to blurred VSM.
  60973. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60974. */
  60975. get: function () {
  60976. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60977. return this.useBlurExponentialShadowMap;
  60978. },
  60979. /**
  60980. * Sets the current filter is to blurred VSM.
  60981. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60982. */
  60983. set: function (value) {
  60984. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60985. this.useBlurExponentialShadowMap = value;
  60986. },
  60987. enumerable: true,
  60988. configurable: true
  60989. });
  60990. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60991. /**
  60992. * Gets if the current filter is set to ESM.
  60993. */
  60994. get: function () {
  60995. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60996. },
  60997. /**
  60998. * Sets the current filter is to ESM.
  60999. */
  61000. set: function (value) {
  61001. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61002. return;
  61003. }
  61004. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61005. },
  61006. enumerable: true,
  61007. configurable: true
  61008. });
  61009. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61010. /**
  61011. * Gets if the current filter is set to filtered ESM.
  61012. */
  61013. get: function () {
  61014. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61015. },
  61016. /**
  61017. * Gets if the current filter is set to filtered ESM.
  61018. */
  61019. set: function (value) {
  61020. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61021. return;
  61022. }
  61023. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61024. },
  61025. enumerable: true,
  61026. configurable: true
  61027. });
  61028. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61029. /**
  61030. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61031. * exponential to prevent steep falloff artifacts).
  61032. */
  61033. get: function () {
  61034. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61035. },
  61036. /**
  61037. * Sets the current filter to "close ESM" (using the inverse of the
  61038. * exponential to prevent steep falloff artifacts).
  61039. */
  61040. set: function (value) {
  61041. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61042. return;
  61043. }
  61044. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61045. },
  61046. enumerable: true,
  61047. configurable: true
  61048. });
  61049. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61050. /**
  61051. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61052. * exponential to prevent steep falloff artifacts).
  61053. */
  61054. get: function () {
  61055. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61056. },
  61057. /**
  61058. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61059. * exponential to prevent steep falloff artifacts).
  61060. */
  61061. set: function (value) {
  61062. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61063. return;
  61064. }
  61065. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61066. },
  61067. enumerable: true,
  61068. configurable: true
  61069. });
  61070. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61071. /**
  61072. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61073. */
  61074. get: function () {
  61075. return this.filter === ShadowGenerator.FILTER_PCF;
  61076. },
  61077. /**
  61078. * Sets the current filter to "PCF" (percentage closer filtering).
  61079. */
  61080. set: function (value) {
  61081. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61082. return;
  61083. }
  61084. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61085. },
  61086. enumerable: true,
  61087. configurable: true
  61088. });
  61089. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61090. /**
  61091. * Gets the PCF or PCSS Quality.
  61092. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61093. */
  61094. get: function () {
  61095. return this._filteringQuality;
  61096. },
  61097. /**
  61098. * Sets the PCF or PCSS Quality.
  61099. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61100. */
  61101. set: function (filteringQuality) {
  61102. this._filteringQuality = filteringQuality;
  61103. },
  61104. enumerable: true,
  61105. configurable: true
  61106. });
  61107. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61108. /**
  61109. * Gets if the current filter is set to "PCSS" (contact hardening).
  61110. */
  61111. get: function () {
  61112. return this.filter === ShadowGenerator.FILTER_PCSS;
  61113. },
  61114. /**
  61115. * Sets the current filter to "PCSS" (contact hardening).
  61116. */
  61117. set: function (value) {
  61118. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61119. return;
  61120. }
  61121. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61122. },
  61123. enumerable: true,
  61124. configurable: true
  61125. });
  61126. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61127. /**
  61128. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61129. * Using a ratio helps keeping shape stability independently of the map size.
  61130. *
  61131. * It does not account for the light projection as it was having too much
  61132. * instability during the light setup or during light position changes.
  61133. *
  61134. * Only valid if useContactHardeningShadow is true.
  61135. */
  61136. get: function () {
  61137. return this._contactHardeningLightSizeUVRatio;
  61138. },
  61139. /**
  61140. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61141. * Using a ratio helps keeping shape stability independently of the map size.
  61142. *
  61143. * It does not account for the light projection as it was having too much
  61144. * instability during the light setup or during light position changes.
  61145. *
  61146. * Only valid if useContactHardeningShadow is true.
  61147. */
  61148. set: function (contactHardeningLightSizeUVRatio) {
  61149. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61150. },
  61151. enumerable: true,
  61152. configurable: true
  61153. });
  61154. /**
  61155. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61156. * 0 means strongest and 1 would means no shadow.
  61157. * @returns the darkness.
  61158. */
  61159. ShadowGenerator.prototype.getDarkness = function () {
  61160. return this._darkness;
  61161. };
  61162. /**
  61163. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61164. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61165. * @returns the shadow generator allowing fluent coding.
  61166. */
  61167. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61168. if (darkness >= 1.0)
  61169. this._darkness = 1.0;
  61170. else if (darkness <= 0.0)
  61171. this._darkness = 0.0;
  61172. else
  61173. this._darkness = darkness;
  61174. return this;
  61175. };
  61176. /**
  61177. * Sets the ability to have transparent shadow (boolean).
  61178. * @param transparent True if transparent else False
  61179. * @returns the shadow generator allowing fluent coding
  61180. */
  61181. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61182. this._transparencyShadow = transparent;
  61183. return this;
  61184. };
  61185. /**
  61186. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61187. * @returns The render target texture if present otherwise, null
  61188. */
  61189. ShadowGenerator.prototype.getShadowMap = function () {
  61190. return this._shadowMap;
  61191. };
  61192. /**
  61193. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61194. * @returns The render target texture if the shadow map is present otherwise, null
  61195. */
  61196. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61197. if (this._shadowMap2) {
  61198. return this._shadowMap2;
  61199. }
  61200. return this._shadowMap;
  61201. };
  61202. /**
  61203. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61204. * @param mesh Mesh to add
  61205. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61206. * @returns the Shadow Generator itself
  61207. */
  61208. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61209. if (includeDescendants === void 0) { includeDescendants = true; }
  61210. if (!this._shadowMap) {
  61211. return this;
  61212. }
  61213. if (!this._shadowMap.renderList) {
  61214. this._shadowMap.renderList = [];
  61215. }
  61216. this._shadowMap.renderList.push(mesh);
  61217. if (includeDescendants) {
  61218. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61219. }
  61220. return this;
  61221. var _a;
  61222. };
  61223. /**
  61224. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61225. * @param mesh Mesh to remove
  61226. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61227. * @returns the Shadow Generator itself
  61228. */
  61229. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61230. if (includeDescendants === void 0) { includeDescendants = true; }
  61231. if (!this._shadowMap || !this._shadowMap.renderList) {
  61232. return this;
  61233. }
  61234. var index = this._shadowMap.renderList.indexOf(mesh);
  61235. if (index !== -1) {
  61236. this._shadowMap.renderList.splice(index, 1);
  61237. }
  61238. if (includeDescendants) {
  61239. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61240. var child = _a[_i];
  61241. this.removeShadowCaster(child);
  61242. }
  61243. }
  61244. return this;
  61245. };
  61246. /**
  61247. * Returns the associated light object.
  61248. * @returns the light generating the shadow
  61249. */
  61250. ShadowGenerator.prototype.getLight = function () {
  61251. return this._light;
  61252. };
  61253. ShadowGenerator.prototype._initializeGenerator = function () {
  61254. this._light._markMeshesAsLightDirty();
  61255. this._initializeShadowMap();
  61256. };
  61257. ShadowGenerator.prototype._initializeShadowMap = function () {
  61258. var _this = this;
  61259. // Render target
  61260. var engine = this._scene.getEngine();
  61261. if (engine.webGLVersion > 1) {
  61262. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61263. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61264. }
  61265. else {
  61266. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61267. }
  61268. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61269. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61270. this._shadowMap.anisotropicFilteringLevel = 1;
  61271. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61272. this._shadowMap.renderParticles = false;
  61273. this._shadowMap.ignoreCameraViewport = true;
  61274. // Record Face Index before render.
  61275. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61276. _this._currentFaceIndex = faceIndex;
  61277. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61278. engine.setColorWrite(false);
  61279. }
  61280. });
  61281. // Custom render function.
  61282. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61283. // Blur if required afer render.
  61284. this._shadowMap.onAfterUnbindObservable.add(function () {
  61285. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61286. engine.setColorWrite(true);
  61287. }
  61288. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61289. return;
  61290. }
  61291. var shadowMap = _this.getShadowMapForRendering();
  61292. if (shadowMap) {
  61293. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61294. }
  61295. });
  61296. // Clear according to the chosen filter.
  61297. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61298. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61299. this._shadowMap.onClearObservable.add(function (engine) {
  61300. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61301. engine.clear(clearOne, false, true, false);
  61302. }
  61303. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61304. engine.clear(clearZero, true, true, false);
  61305. }
  61306. else {
  61307. engine.clear(clearOne, true, true, false);
  61308. }
  61309. });
  61310. };
  61311. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61312. var _this = this;
  61313. var engine = this._scene.getEngine();
  61314. var targetSize = this._mapSize / this.blurScale;
  61315. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61316. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61317. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61318. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61319. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61320. }
  61321. if (this.useKernelBlur) {
  61322. 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);
  61323. this._kernelBlurXPostprocess.width = targetSize;
  61324. this._kernelBlurXPostprocess.height = targetSize;
  61325. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61326. effect.setTexture("textureSampler", _this._shadowMap);
  61327. });
  61328. 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);
  61329. this._kernelBlurXPostprocess.autoClear = false;
  61330. this._kernelBlurYPostprocess.autoClear = false;
  61331. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61332. this._kernelBlurXPostprocess.packedFloat = true;
  61333. this._kernelBlurYPostprocess.packedFloat = true;
  61334. }
  61335. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61336. }
  61337. else {
  61338. 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);
  61339. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61340. effect.setFloat2("screenSize", targetSize, targetSize);
  61341. effect.setTexture("textureSampler", _this._shadowMap);
  61342. });
  61343. this._boxBlurPostprocess.autoClear = false;
  61344. this._blurPostProcesses = [this._boxBlurPostprocess];
  61345. }
  61346. };
  61347. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61348. var index;
  61349. var engine = this._scene.getEngine();
  61350. if (depthOnlySubMeshes.length) {
  61351. engine.setColorWrite(false);
  61352. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61353. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61354. }
  61355. engine.setColorWrite(true);
  61356. }
  61357. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61358. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61359. }
  61360. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61361. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61362. }
  61363. if (this._transparencyShadow) {
  61364. for (index = 0; index < transparentSubMeshes.length; index++) {
  61365. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61366. }
  61367. }
  61368. };
  61369. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61370. var _this = this;
  61371. var mesh = subMesh.getRenderingMesh();
  61372. var scene = this._scene;
  61373. var engine = scene.getEngine();
  61374. var material = subMesh.getMaterial();
  61375. if (!material) {
  61376. return;
  61377. }
  61378. // Culling
  61379. engine.setState(material.backFaceCulling);
  61380. // Managing instances
  61381. var batch = mesh._getInstancesRenderList(subMesh._id);
  61382. if (batch.mustReturn) {
  61383. return;
  61384. }
  61385. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61386. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61387. engine.enableEffect(this._effect);
  61388. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61389. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61390. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61391. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61392. this._effect.setVector3("lightData", this._cachedDirection);
  61393. }
  61394. else {
  61395. this._effect.setVector3("lightData", this._cachedPosition);
  61396. }
  61397. if (scene.activeCamera) {
  61398. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61399. }
  61400. // Alpha test
  61401. if (material && material.needAlphaTesting()) {
  61402. var alphaTexture = material.getAlphaTestTexture();
  61403. if (alphaTexture) {
  61404. this._effect.setTexture("diffuseSampler", alphaTexture);
  61405. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61406. }
  61407. }
  61408. // Bones
  61409. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61410. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61411. }
  61412. if (this.forceBackFacesOnly) {
  61413. engine.setState(true, 0, false, true);
  61414. }
  61415. // Draw
  61416. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61417. if (this.forceBackFacesOnly) {
  61418. engine.setState(true, 0, false, false);
  61419. }
  61420. }
  61421. else {
  61422. // Need to reset refresh rate of the shadowMap
  61423. if (this._shadowMap) {
  61424. this._shadowMap.resetRefreshCounter();
  61425. }
  61426. }
  61427. };
  61428. ShadowGenerator.prototype._applyFilterValues = function () {
  61429. if (!this._shadowMap) {
  61430. return;
  61431. }
  61432. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61433. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61434. }
  61435. else {
  61436. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61437. }
  61438. };
  61439. /**
  61440. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61441. * @param onCompiled Callback triggered at the and of the effects compilation
  61442. * @param options Sets of optional options forcing the compilation with different modes
  61443. */
  61444. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61445. var _this = this;
  61446. var localOptions = __assign({ useInstances: false }, options);
  61447. var shadowMap = this.getShadowMap();
  61448. if (!shadowMap) {
  61449. if (onCompiled) {
  61450. onCompiled(this);
  61451. }
  61452. return;
  61453. }
  61454. var renderList = shadowMap.renderList;
  61455. if (!renderList) {
  61456. if (onCompiled) {
  61457. onCompiled(this);
  61458. }
  61459. return;
  61460. }
  61461. var subMeshes = new Array();
  61462. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61463. var mesh = renderList_1[_i];
  61464. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61465. }
  61466. if (subMeshes.length === 0) {
  61467. if (onCompiled) {
  61468. onCompiled(this);
  61469. }
  61470. return;
  61471. }
  61472. var currentIndex = 0;
  61473. var checkReady = function () {
  61474. if (!_this._scene || !_this._scene.getEngine()) {
  61475. return;
  61476. }
  61477. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61478. currentIndex++;
  61479. if (currentIndex >= subMeshes.length) {
  61480. if (onCompiled) {
  61481. onCompiled(_this);
  61482. }
  61483. return;
  61484. }
  61485. }
  61486. setTimeout(checkReady, 16);
  61487. };
  61488. checkReady();
  61489. };
  61490. /**
  61491. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61492. * @param options Sets of optional options forcing the compilation with different modes
  61493. * @returns A promise that resolves when the compilation completes
  61494. */
  61495. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61496. var _this = this;
  61497. return new Promise(function (resolve) {
  61498. _this.forceCompilation(function () {
  61499. resolve();
  61500. }, options);
  61501. });
  61502. };
  61503. /**
  61504. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61505. * @param subMesh The submesh we want to render in the shadow map
  61506. * @param useInstances Defines wether will draw in the map using instances
  61507. * @returns true if ready otherwise, false
  61508. */
  61509. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61510. var defines = [];
  61511. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61512. defines.push("#define FLOAT");
  61513. }
  61514. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61515. defines.push("#define ESM");
  61516. }
  61517. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61518. defines.push("#define DEPTHTEXTURE");
  61519. }
  61520. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61521. var mesh = subMesh.getMesh();
  61522. var material = subMesh.getMaterial();
  61523. // Normal bias.
  61524. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61525. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61526. defines.push("#define NORMAL");
  61527. if (mesh.nonUniformScaling) {
  61528. defines.push("#define NONUNIFORMSCALING");
  61529. }
  61530. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61531. defines.push("#define DIRECTIONINLIGHTDATA");
  61532. }
  61533. }
  61534. // Alpha test
  61535. if (material && material.needAlphaTesting()) {
  61536. var alphaTexture = material.getAlphaTestTexture();
  61537. if (alphaTexture) {
  61538. defines.push("#define ALPHATEST");
  61539. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61540. attribs.push(BABYLON.VertexBuffer.UVKind);
  61541. defines.push("#define UV1");
  61542. }
  61543. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61544. if (alphaTexture.coordinatesIndex === 1) {
  61545. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61546. defines.push("#define UV2");
  61547. }
  61548. }
  61549. }
  61550. }
  61551. // Bones
  61552. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61553. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61554. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61555. if (mesh.numBoneInfluencers > 4) {
  61556. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61557. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61558. }
  61559. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61560. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61561. }
  61562. else {
  61563. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61564. }
  61565. // Instances
  61566. if (useInstances) {
  61567. defines.push("#define INSTANCES");
  61568. attribs.push("world0");
  61569. attribs.push("world1");
  61570. attribs.push("world2");
  61571. attribs.push("world3");
  61572. }
  61573. // Get correct effect
  61574. var join = defines.join("\n");
  61575. if (this._cachedDefines !== join) {
  61576. this._cachedDefines = join;
  61577. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61578. }
  61579. if (!this._effect.isReady()) {
  61580. return false;
  61581. }
  61582. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61583. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61584. this._initializeBlurRTTAndPostProcesses();
  61585. }
  61586. }
  61587. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61588. return false;
  61589. }
  61590. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61591. return false;
  61592. }
  61593. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61594. return false;
  61595. }
  61596. return true;
  61597. };
  61598. /**
  61599. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61600. * @param defines Defines of the material we want to update
  61601. * @param lightIndex Index of the light in the enabled light list of the material
  61602. */
  61603. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61604. var scene = this._scene;
  61605. var light = this._light;
  61606. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61607. return;
  61608. }
  61609. defines["SHADOW" + lightIndex] = true;
  61610. if (this.useContactHardeningShadow) {
  61611. defines["SHADOWPCSS" + lightIndex] = true;
  61612. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61613. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61614. }
  61615. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61616. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61617. }
  61618. // else default to high.
  61619. }
  61620. if (this.usePercentageCloserFiltering) {
  61621. defines["SHADOWPCF" + lightIndex] = true;
  61622. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61623. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61624. }
  61625. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61626. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61627. }
  61628. // else default to high.
  61629. }
  61630. else if (this.usePoissonSampling) {
  61631. defines["SHADOWPOISSON" + lightIndex] = true;
  61632. }
  61633. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61634. defines["SHADOWESM" + lightIndex] = true;
  61635. }
  61636. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61637. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61638. }
  61639. if (light.needCube()) {
  61640. defines["SHADOWCUBE" + lightIndex] = true;
  61641. }
  61642. };
  61643. /**
  61644. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61645. * defined in the generator but impacting the effect).
  61646. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61647. * @param effect The effect we are binfing the information for
  61648. */
  61649. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61650. var light = this._light;
  61651. var scene = this._scene;
  61652. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61653. return;
  61654. }
  61655. var camera = scene.activeCamera;
  61656. if (!camera) {
  61657. return;
  61658. }
  61659. var shadowMap = this.getShadowMap();
  61660. if (!shadowMap) {
  61661. return;
  61662. }
  61663. if (!light.needCube()) {
  61664. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61665. }
  61666. // Only PCF uses depth stencil texture.
  61667. if (this._filter === ShadowGenerator.FILTER_PCF) {
  61668. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61669. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61670. }
  61671. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  61672. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61673. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  61674. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61675. }
  61676. else {
  61677. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61678. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61679. }
  61680. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61681. };
  61682. /**
  61683. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61684. * (eq to shadow prjection matrix * light transform matrix)
  61685. * @returns The transform matrix used to create the shadow map
  61686. */
  61687. ShadowGenerator.prototype.getTransformMatrix = function () {
  61688. var scene = this._scene;
  61689. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61690. return this._transformMatrix;
  61691. }
  61692. this._currentRenderID = scene.getRenderId();
  61693. this._currentFaceIndexCache = this._currentFaceIndex;
  61694. var lightPosition = this._light.position;
  61695. if (this._light.computeTransformedInformation()) {
  61696. lightPosition = this._light.transformedPosition;
  61697. }
  61698. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61699. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61700. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61701. }
  61702. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61703. this._cachedPosition.copyFrom(lightPosition);
  61704. this._cachedDirection.copyFrom(this._lightDirection);
  61705. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61706. var shadowMap = this.getShadowMap();
  61707. if (shadowMap) {
  61708. var renderList = shadowMap.renderList;
  61709. if (renderList) {
  61710. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61711. }
  61712. }
  61713. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61714. }
  61715. return this._transformMatrix;
  61716. };
  61717. /**
  61718. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61719. * Cube and 2D textures for instance.
  61720. */
  61721. ShadowGenerator.prototype.recreateShadowMap = function () {
  61722. var shadowMap = this._shadowMap;
  61723. if (!shadowMap) {
  61724. return;
  61725. }
  61726. // Track render list.
  61727. var renderList = shadowMap.renderList;
  61728. // Clean up existing data.
  61729. this._disposeRTTandPostProcesses();
  61730. // Reinitializes.
  61731. this._initializeGenerator();
  61732. // Reaffect the filter to ensure a correct fallback if necessary.
  61733. this.filter = this.filter;
  61734. // Reaffect the filter.
  61735. this._applyFilterValues();
  61736. // Reaffect Render List.
  61737. this._shadowMap.renderList = renderList;
  61738. };
  61739. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61740. if (this._shadowMap2) {
  61741. this._shadowMap2.dispose();
  61742. this._shadowMap2 = null;
  61743. }
  61744. if (this._boxBlurPostprocess) {
  61745. this._boxBlurPostprocess.dispose();
  61746. this._boxBlurPostprocess = null;
  61747. }
  61748. if (this._kernelBlurXPostprocess) {
  61749. this._kernelBlurXPostprocess.dispose();
  61750. this._kernelBlurXPostprocess = null;
  61751. }
  61752. if (this._kernelBlurYPostprocess) {
  61753. this._kernelBlurYPostprocess.dispose();
  61754. this._kernelBlurYPostprocess = null;
  61755. }
  61756. this._blurPostProcesses = [];
  61757. };
  61758. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61759. if (this._shadowMap) {
  61760. this._shadowMap.dispose();
  61761. this._shadowMap = null;
  61762. }
  61763. this._disposeBlurPostProcesses();
  61764. };
  61765. /**
  61766. * Disposes the ShadowGenerator.
  61767. * Returns nothing.
  61768. */
  61769. ShadowGenerator.prototype.dispose = function () {
  61770. this._disposeRTTandPostProcesses();
  61771. if (this._light) {
  61772. this._light._shadowGenerator = null;
  61773. this._light._markMeshesAsLightDirty();
  61774. }
  61775. };
  61776. /**
  61777. * Serializes the shadow generator setup to a json object.
  61778. * @returns The serialized JSON object
  61779. */
  61780. ShadowGenerator.prototype.serialize = function () {
  61781. var serializationObject = {};
  61782. var shadowMap = this.getShadowMap();
  61783. if (!shadowMap) {
  61784. return serializationObject;
  61785. }
  61786. serializationObject.lightId = this._light.id;
  61787. serializationObject.mapSize = shadowMap.getRenderSize();
  61788. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61789. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61790. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61791. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61792. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61793. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61794. serializationObject.depthScale = this.depthScale;
  61795. serializationObject.darkness = this.getDarkness();
  61796. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61797. serializationObject.blurKernel = this.blurKernel;
  61798. serializationObject.blurScale = this.blurScale;
  61799. serializationObject.useKernelBlur = this.useKernelBlur;
  61800. serializationObject.transparencyShadow = this._transparencyShadow;
  61801. serializationObject.bias = this.bias;
  61802. serializationObject.normalBias = this.normalBias;
  61803. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  61804. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  61805. serializationObject.filteringQuality = this.filteringQuality;
  61806. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  61807. serializationObject.renderList = [];
  61808. if (shadowMap.renderList) {
  61809. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61810. var mesh = shadowMap.renderList[meshIndex];
  61811. serializationObject.renderList.push(mesh.id);
  61812. }
  61813. }
  61814. return serializationObject;
  61815. };
  61816. /**
  61817. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61818. * @param parsedShadowGenerator The JSON object to parse
  61819. * @param scene The scene to create the shadow map for
  61820. * @returns The parsed shadow generator
  61821. */
  61822. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61823. //casting to point light, as light is missing the position attr and typescript complains.
  61824. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61825. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61826. var shadowMap = shadowGenerator.getShadowMap();
  61827. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61828. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61829. meshes.forEach(function (mesh) {
  61830. if (!shadowMap) {
  61831. return;
  61832. }
  61833. if (!shadowMap.renderList) {
  61834. shadowMap.renderList = [];
  61835. }
  61836. shadowMap.renderList.push(mesh);
  61837. });
  61838. }
  61839. if (parsedShadowGenerator.usePoissonSampling) {
  61840. shadowGenerator.usePoissonSampling = true;
  61841. }
  61842. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61843. shadowGenerator.useExponentialShadowMap = true;
  61844. }
  61845. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61846. shadowGenerator.useBlurExponentialShadowMap = true;
  61847. }
  61848. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61849. shadowGenerator.useCloseExponentialShadowMap = true;
  61850. }
  61851. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61852. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61853. }
  61854. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  61855. shadowGenerator.usePercentageCloserFiltering = true;
  61856. }
  61857. else if (parsedShadowGenerator.useContactHardeningShadow) {
  61858. shadowGenerator.useContactHardeningShadow = true;
  61859. }
  61860. if (parsedShadowGenerator.filteringQuality) {
  61861. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  61862. }
  61863. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  61864. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  61865. }
  61866. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61867. shadowGenerator.useExponentialShadowMap = true;
  61868. }
  61869. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61870. shadowGenerator.useBlurExponentialShadowMap = true;
  61871. }
  61872. if (parsedShadowGenerator.depthScale) {
  61873. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61874. }
  61875. if (parsedShadowGenerator.blurScale) {
  61876. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61877. }
  61878. if (parsedShadowGenerator.blurBoxOffset) {
  61879. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61880. }
  61881. if (parsedShadowGenerator.useKernelBlur) {
  61882. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61883. }
  61884. if (parsedShadowGenerator.blurKernel) {
  61885. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61886. }
  61887. if (parsedShadowGenerator.bias !== undefined) {
  61888. shadowGenerator.bias = parsedShadowGenerator.bias;
  61889. }
  61890. if (parsedShadowGenerator.normalBias !== undefined) {
  61891. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  61892. }
  61893. if (parsedShadowGenerator.darkness) {
  61894. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61895. }
  61896. if (parsedShadowGenerator.transparencyShadow) {
  61897. shadowGenerator.setTransparencyShadow(true);
  61898. }
  61899. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61900. return shadowGenerator;
  61901. };
  61902. /**
  61903. * Shadow generator mode None: no filtering applied.
  61904. */
  61905. ShadowGenerator.FILTER_NONE = 0;
  61906. /**
  61907. * Shadow generator mode ESM: Exponential Shadow Mapping.
  61908. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61909. */
  61910. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  61911. /**
  61912. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  61913. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  61914. */
  61915. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  61916. /**
  61917. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  61918. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61919. */
  61920. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61921. /**
  61922. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  61923. * edge artifacts on steep falloff.
  61924. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61925. */
  61926. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61927. /**
  61928. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  61929. * edge artifacts on steep falloff.
  61930. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61931. */
  61932. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61933. /**
  61934. * Shadow generator mode PCF: Percentage Closer Filtering
  61935. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61936. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  61937. */
  61938. ShadowGenerator.FILTER_PCF = 6;
  61939. /**
  61940. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  61941. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61942. * Contact Hardening
  61943. */
  61944. ShadowGenerator.FILTER_PCSS = 7;
  61945. /**
  61946. * Reserved for PCF and PCSS
  61947. * Highest Quality.
  61948. *
  61949. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  61950. *
  61951. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  61952. */
  61953. ShadowGenerator.QUALITY_HIGH = 0;
  61954. /**
  61955. * Reserved for PCF and PCSS
  61956. * Good tradeoff for quality/perf cross devices
  61957. *
  61958. * Execute PCF on a 3*3 kernel.
  61959. *
  61960. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  61961. */
  61962. ShadowGenerator.QUALITY_MEDIUM = 1;
  61963. /**
  61964. * Reserved for PCF and PCSS
  61965. * The lowest quality but the fastest.
  61966. *
  61967. * Execute PCF on a 1*1 kernel.
  61968. *
  61969. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  61970. */
  61971. ShadowGenerator.QUALITY_LOW = 2;
  61972. return ShadowGenerator;
  61973. }());
  61974. BABYLON.ShadowGenerator = ShadowGenerator;
  61975. })(BABYLON || (BABYLON = {}));
  61976. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61977. var BABYLON;
  61978. (function (BABYLON) {
  61979. var DefaultLoadingScreen = /** @class */ (function () {
  61980. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61981. if (_loadingText === void 0) { _loadingText = ""; }
  61982. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61983. var _this = this;
  61984. this._renderingCanvas = _renderingCanvas;
  61985. this._loadingText = _loadingText;
  61986. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61987. // Resize
  61988. this._resizeLoadingUI = function () {
  61989. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61990. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61991. if (!_this._loadingDiv) {
  61992. return;
  61993. }
  61994. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61995. _this._loadingDiv.style.left = canvasRect.left + "px";
  61996. _this._loadingDiv.style.top = canvasRect.top + "px";
  61997. _this._loadingDiv.style.width = canvasRect.width + "px";
  61998. _this._loadingDiv.style.height = canvasRect.height + "px";
  61999. };
  62000. }
  62001. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62002. if (this._loadingDiv) {
  62003. // Do not add a loading screen if there is already one
  62004. return;
  62005. }
  62006. this._loadingDiv = document.createElement("div");
  62007. this._loadingDiv.id = "babylonjsLoadingDiv";
  62008. this._loadingDiv.style.opacity = "0";
  62009. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62010. this._loadingDiv.style.pointerEvents = "none";
  62011. // Loading text
  62012. this._loadingTextDiv = document.createElement("div");
  62013. this._loadingTextDiv.style.position = "absolute";
  62014. this._loadingTextDiv.style.left = "0";
  62015. this._loadingTextDiv.style.top = "50%";
  62016. this._loadingTextDiv.style.marginTop = "80px";
  62017. this._loadingTextDiv.style.width = "100%";
  62018. this._loadingTextDiv.style.height = "20px";
  62019. this._loadingTextDiv.style.fontFamily = "Arial";
  62020. this._loadingTextDiv.style.fontSize = "14px";
  62021. this._loadingTextDiv.style.color = "white";
  62022. this._loadingTextDiv.style.textAlign = "center";
  62023. this._loadingTextDiv.innerHTML = "Loading";
  62024. this._loadingDiv.appendChild(this._loadingTextDiv);
  62025. //set the predefined text
  62026. this._loadingTextDiv.innerHTML = this._loadingText;
  62027. // Generating keyframes
  62028. var style = document.createElement('style');
  62029. style.type = 'text/css';
  62030. 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 }";
  62031. style.innerHTML = keyFrames;
  62032. document.getElementsByTagName('head')[0].appendChild(style);
  62033. // Loading img
  62034. var imgBack = new Image();
  62035. 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";
  62036. imgBack.style.position = "absolute";
  62037. imgBack.style.left = "50%";
  62038. imgBack.style.top = "50%";
  62039. imgBack.style.marginLeft = "-60px";
  62040. imgBack.style.marginTop = "-60px";
  62041. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62042. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62043. imgBack.style.transformOrigin = "50% 50%";
  62044. imgBack.style.webkitTransformOrigin = "50% 50%";
  62045. this._loadingDiv.appendChild(imgBack);
  62046. this._resizeLoadingUI();
  62047. window.addEventListener("resize", this._resizeLoadingUI);
  62048. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62049. document.body.appendChild(this._loadingDiv);
  62050. this._loadingDiv.style.opacity = "1";
  62051. };
  62052. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62053. var _this = this;
  62054. if (!this._loadingDiv) {
  62055. return;
  62056. }
  62057. var onTransitionEnd = function () {
  62058. if (!_this._loadingDiv) {
  62059. return;
  62060. }
  62061. document.body.removeChild(_this._loadingDiv);
  62062. window.removeEventListener("resize", _this._resizeLoadingUI);
  62063. _this._loadingDiv = null;
  62064. };
  62065. this._loadingDiv.style.opacity = "0";
  62066. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62067. };
  62068. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62069. set: function (text) {
  62070. this._loadingText = text;
  62071. if (this._loadingTextDiv) {
  62072. this._loadingTextDiv.innerHTML = this._loadingText;
  62073. }
  62074. },
  62075. enumerable: true,
  62076. configurable: true
  62077. });
  62078. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62079. get: function () {
  62080. return this._loadingDivBackgroundColor;
  62081. },
  62082. set: function (color) {
  62083. this._loadingDivBackgroundColor = color;
  62084. if (!this._loadingDiv) {
  62085. return;
  62086. }
  62087. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62088. },
  62089. enumerable: true,
  62090. configurable: true
  62091. });
  62092. return DefaultLoadingScreen;
  62093. }());
  62094. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62095. })(BABYLON || (BABYLON = {}));
  62096. //# sourceMappingURL=babylon.loadingScreen.js.map
  62097. var BABYLON;
  62098. (function (BABYLON) {
  62099. var SceneLoaderProgressEvent = /** @class */ (function () {
  62100. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62101. this.lengthComputable = lengthComputable;
  62102. this.loaded = loaded;
  62103. this.total = total;
  62104. }
  62105. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62106. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62107. };
  62108. return SceneLoaderProgressEvent;
  62109. }());
  62110. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62111. var SceneLoader = /** @class */ (function () {
  62112. function SceneLoader() {
  62113. }
  62114. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62115. get: function () {
  62116. return 0;
  62117. },
  62118. enumerable: true,
  62119. configurable: true
  62120. });
  62121. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62122. get: function () {
  62123. return 1;
  62124. },
  62125. enumerable: true,
  62126. configurable: true
  62127. });
  62128. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62129. get: function () {
  62130. return 2;
  62131. },
  62132. enumerable: true,
  62133. configurable: true
  62134. });
  62135. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62136. get: function () {
  62137. return 3;
  62138. },
  62139. enumerable: true,
  62140. configurable: true
  62141. });
  62142. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62143. get: function () {
  62144. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62145. },
  62146. set: function (value) {
  62147. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62148. },
  62149. enumerable: true,
  62150. configurable: true
  62151. });
  62152. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62153. get: function () {
  62154. return SceneLoader._ShowLoadingScreen;
  62155. },
  62156. set: function (value) {
  62157. SceneLoader._ShowLoadingScreen = value;
  62158. },
  62159. enumerable: true,
  62160. configurable: true
  62161. });
  62162. Object.defineProperty(SceneLoader, "loggingLevel", {
  62163. get: function () {
  62164. return SceneLoader._loggingLevel;
  62165. },
  62166. set: function (value) {
  62167. SceneLoader._loggingLevel = value;
  62168. },
  62169. enumerable: true,
  62170. configurable: true
  62171. });
  62172. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62173. get: function () {
  62174. return SceneLoader._CleanBoneMatrixWeights;
  62175. },
  62176. set: function (value) {
  62177. SceneLoader._CleanBoneMatrixWeights = value;
  62178. },
  62179. enumerable: true,
  62180. configurable: true
  62181. });
  62182. SceneLoader._getDefaultPlugin = function () {
  62183. return SceneLoader._registeredPlugins[".babylon"];
  62184. };
  62185. SceneLoader._getPluginForExtension = function (extension) {
  62186. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62187. if (registeredPlugin) {
  62188. return registeredPlugin;
  62189. }
  62190. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62191. return SceneLoader._getDefaultPlugin();
  62192. };
  62193. SceneLoader._getPluginForDirectLoad = function (data) {
  62194. for (var extension in SceneLoader._registeredPlugins) {
  62195. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62196. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62197. return SceneLoader._registeredPlugins[extension];
  62198. }
  62199. }
  62200. return SceneLoader._getDefaultPlugin();
  62201. };
  62202. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62203. if (sceneFilename.name) {
  62204. sceneFilename = sceneFilename.name;
  62205. }
  62206. var queryStringPosition = sceneFilename.indexOf("?");
  62207. if (queryStringPosition !== -1) {
  62208. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62209. }
  62210. var dotPosition = sceneFilename.lastIndexOf(".");
  62211. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62212. return SceneLoader._getPluginForExtension(extension);
  62213. };
  62214. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62215. SceneLoader._getDirectLoad = function (sceneFilename) {
  62216. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62217. return sceneFilename.substr(5);
  62218. }
  62219. return null;
  62220. };
  62221. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62222. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62223. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62224. var plugin;
  62225. if (registeredPlugin.plugin.createPlugin) {
  62226. plugin = registeredPlugin.plugin.createPlugin();
  62227. }
  62228. else {
  62229. plugin = registeredPlugin.plugin;
  62230. }
  62231. var useArrayBuffer = registeredPlugin.isBinary;
  62232. var database;
  62233. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62234. var dataCallback = function (data, responseURL) {
  62235. if (scene.isDisposed) {
  62236. onError("Scene has been disposed");
  62237. return;
  62238. }
  62239. scene.database = database;
  62240. onSuccess(plugin, data, responseURL);
  62241. };
  62242. var request = null;
  62243. var pluginDisposed = false;
  62244. var onDisposeObservable = plugin.onDisposeObservable;
  62245. if (onDisposeObservable) {
  62246. onDisposeObservable.add(function () {
  62247. pluginDisposed = true;
  62248. if (request) {
  62249. request.abort();
  62250. request = null;
  62251. }
  62252. onDispose();
  62253. });
  62254. }
  62255. var manifestChecked = function () {
  62256. if (pluginDisposed) {
  62257. return;
  62258. }
  62259. var url = rootUrl + sceneFilename;
  62260. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62261. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62262. } : undefined, database, useArrayBuffer, function (request, exception) {
  62263. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62264. });
  62265. };
  62266. if (directLoad) {
  62267. dataCallback(directLoad);
  62268. return plugin;
  62269. }
  62270. if (rootUrl.indexOf("file:") === -1) {
  62271. if (scene.getEngine().enableOfflineSupport) {
  62272. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62273. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62274. }
  62275. else {
  62276. manifestChecked();
  62277. }
  62278. }
  62279. else {
  62280. var fileOrString = sceneFilename;
  62281. if (fileOrString.name) {
  62282. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62283. }
  62284. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62285. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62286. }
  62287. else {
  62288. onError("Unable to find file named " + sceneFilename);
  62289. }
  62290. }
  62291. return plugin;
  62292. };
  62293. // Public functions
  62294. SceneLoader.GetPluginForExtension = function (extension) {
  62295. return SceneLoader._getPluginForExtension(extension).plugin;
  62296. };
  62297. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62298. return !!SceneLoader._registeredPlugins[extension];
  62299. };
  62300. SceneLoader.RegisterPlugin = function (plugin) {
  62301. if (typeof plugin.extensions === "string") {
  62302. var extension = plugin.extensions;
  62303. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62304. plugin: plugin,
  62305. isBinary: false
  62306. };
  62307. }
  62308. else {
  62309. var extensions = plugin.extensions;
  62310. Object.keys(extensions).forEach(function (extension) {
  62311. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62312. plugin: plugin,
  62313. isBinary: extensions[extension].isBinary
  62314. };
  62315. });
  62316. }
  62317. };
  62318. /**
  62319. * Import meshes into a scene
  62320. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62321. * @param rootUrl a string that defines the root url for scene and resources
  62322. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62323. * @param scene the instance of BABYLON.Scene to append to
  62324. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62325. * @param onProgress a callback with a progress event for each file being loaded
  62326. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62327. * @param pluginExtension the extension used to determine the plugin
  62328. * @returns The loaded plugin
  62329. */
  62330. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62331. if (onSuccess === void 0) { onSuccess = null; }
  62332. if (onProgress === void 0) { onProgress = null; }
  62333. if (onError === void 0) { onError = null; }
  62334. if (pluginExtension === void 0) { pluginExtension = null; }
  62335. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62336. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62337. return null;
  62338. }
  62339. var loadingToken = {};
  62340. scene._addPendingData(loadingToken);
  62341. var disposeHandler = function () {
  62342. scene._removePendingData(loadingToken);
  62343. };
  62344. var errorHandler = function (message, exception) {
  62345. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62346. if (onError) {
  62347. onError(scene, errorMessage, exception);
  62348. }
  62349. else {
  62350. BABYLON.Tools.Error(errorMessage);
  62351. // should the exception be thrown?
  62352. }
  62353. disposeHandler();
  62354. };
  62355. var progressHandler = onProgress ? function (event) {
  62356. try {
  62357. onProgress(event);
  62358. }
  62359. catch (e) {
  62360. errorHandler("Error in onProgress callback", e);
  62361. }
  62362. } : undefined;
  62363. var successHandler = function (meshes, particleSystems, skeletons) {
  62364. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62365. if (onSuccess) {
  62366. try {
  62367. onSuccess(meshes, particleSystems, skeletons);
  62368. }
  62369. catch (e) {
  62370. errorHandler("Error in onSuccess callback", e);
  62371. }
  62372. }
  62373. scene._removePendingData(loadingToken);
  62374. };
  62375. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62376. if (plugin.rewriteRootURL) {
  62377. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62378. }
  62379. if (sceneFilename === "") {
  62380. if (sceneFilename === "") {
  62381. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62382. }
  62383. }
  62384. if (plugin.importMesh) {
  62385. var syncedPlugin = plugin;
  62386. var meshes = new Array();
  62387. var particleSystems = new Array();
  62388. var skeletons = new Array();
  62389. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62390. return;
  62391. }
  62392. scene.loadingPluginName = plugin.name;
  62393. successHandler(meshes, particleSystems, skeletons);
  62394. }
  62395. else {
  62396. var asyncedPlugin = plugin;
  62397. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62398. scene.loadingPluginName = plugin.name;
  62399. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62400. }).catch(function (error) {
  62401. errorHandler(error.message, error);
  62402. });
  62403. }
  62404. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62405. };
  62406. /**
  62407. * Import meshes into a scene
  62408. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62409. * @param rootUrl a string that defines the root url for scene and resources
  62410. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62411. * @param scene the instance of BABYLON.Scene to append to
  62412. * @param onProgress a callback with a progress event for each file being loaded
  62413. * @param pluginExtension the extension used to determine the plugin
  62414. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62415. */
  62416. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62417. if (onProgress === void 0) { onProgress = null; }
  62418. if (pluginExtension === void 0) { pluginExtension = null; }
  62419. return new Promise(function (resolve, reject) {
  62420. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62421. resolve({
  62422. meshes: meshes,
  62423. particleSystems: particleSystems,
  62424. skeletons: skeletons
  62425. });
  62426. }, onProgress, function (scene, message, exception) {
  62427. reject(exception || new Error(message));
  62428. });
  62429. });
  62430. };
  62431. /**
  62432. * Load a scene
  62433. * @param rootUrl a string that defines the root url for scene and resources
  62434. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62435. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62436. * @param onSuccess a callback with the scene when import succeeds
  62437. * @param onProgress a callback with a progress event for each file being loaded
  62438. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62439. * @param pluginExtension the extension used to determine the plugin
  62440. * @returns The loaded plugin
  62441. */
  62442. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62443. if (onSuccess === void 0) { onSuccess = null; }
  62444. if (onProgress === void 0) { onProgress = null; }
  62445. if (onError === void 0) { onError = null; }
  62446. if (pluginExtension === void 0) { pluginExtension = null; }
  62447. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62448. };
  62449. /**
  62450. * Load a scene
  62451. * @param rootUrl a string that defines the root url for scene and resources
  62452. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62453. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62454. * @param onProgress a callback with a progress event for each file being loaded
  62455. * @param pluginExtension the extension used to determine the plugin
  62456. * @returns The loaded scene
  62457. */
  62458. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62459. if (onProgress === void 0) { onProgress = null; }
  62460. if (pluginExtension === void 0) { pluginExtension = null; }
  62461. return new Promise(function (resolve, reject) {
  62462. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62463. resolve(scene);
  62464. }, onProgress, function (scene, message, exception) {
  62465. reject(exception || new Error(message));
  62466. }, pluginExtension);
  62467. });
  62468. };
  62469. /**
  62470. * Append a scene
  62471. * @param rootUrl a string that defines the root url for scene and resources
  62472. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62473. * @param scene is the instance of BABYLON.Scene to append to
  62474. * @param onSuccess a callback with the scene when import succeeds
  62475. * @param onProgress a callback with a progress event for each file being loaded
  62476. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62477. * @param pluginExtension the extension used to determine the plugin
  62478. * @returns The loaded plugin
  62479. */
  62480. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62481. if (onSuccess === void 0) { onSuccess = null; }
  62482. if (onProgress === void 0) { onProgress = null; }
  62483. if (onError === void 0) { onError = null; }
  62484. if (pluginExtension === void 0) { pluginExtension = null; }
  62485. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62486. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62487. return null;
  62488. }
  62489. if (SceneLoader.ShowLoadingScreen) {
  62490. scene.getEngine().displayLoadingUI();
  62491. }
  62492. var loadingToken = {};
  62493. scene._addPendingData(loadingToken);
  62494. var disposeHandler = function () {
  62495. scene._removePendingData(loadingToken);
  62496. scene.getEngine().hideLoadingUI();
  62497. };
  62498. var errorHandler = function (message, exception) {
  62499. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62500. if (onError) {
  62501. onError(scene, errorMessage, exception);
  62502. }
  62503. else {
  62504. BABYLON.Tools.Error(errorMessage);
  62505. // should the exception be thrown?
  62506. }
  62507. disposeHandler();
  62508. };
  62509. var progressHandler = onProgress ? function (event) {
  62510. try {
  62511. onProgress(event);
  62512. }
  62513. catch (e) {
  62514. errorHandler("Error in onProgress callback", e);
  62515. }
  62516. } : undefined;
  62517. var successHandler = function () {
  62518. if (onSuccess) {
  62519. try {
  62520. onSuccess(scene);
  62521. }
  62522. catch (e) {
  62523. errorHandler("Error in onSuccess callback", e);
  62524. }
  62525. }
  62526. scene._removePendingData(loadingToken);
  62527. };
  62528. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62529. if (sceneFilename === "") {
  62530. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62531. }
  62532. if (plugin.load) {
  62533. var syncedPlugin = plugin;
  62534. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62535. return;
  62536. }
  62537. scene.loadingPluginName = plugin.name;
  62538. successHandler();
  62539. }
  62540. else {
  62541. var asyncedPlugin = plugin;
  62542. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  62543. scene.loadingPluginName = plugin.name;
  62544. successHandler();
  62545. }).catch(function (error) {
  62546. errorHandler(error.message, error);
  62547. });
  62548. }
  62549. if (SceneLoader.ShowLoadingScreen) {
  62550. scene.executeWhenReady(function () {
  62551. scene.getEngine().hideLoadingUI();
  62552. });
  62553. }
  62554. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62555. };
  62556. /**
  62557. * Append a scene
  62558. * @param rootUrl a string that defines the root url for scene and resources
  62559. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62560. * @param scene is the instance of BABYLON.Scene to append to
  62561. * @param onProgress a callback with a progress event for each file being loaded
  62562. * @param pluginExtension the extension used to determine the plugin
  62563. * @returns The given scene
  62564. */
  62565. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62566. if (onProgress === void 0) { onProgress = null; }
  62567. if (pluginExtension === void 0) { pluginExtension = null; }
  62568. return new Promise(function (resolve, reject) {
  62569. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62570. resolve(scene);
  62571. }, onProgress, function (scene, message, exception) {
  62572. reject(exception || new Error(message));
  62573. }, pluginExtension);
  62574. });
  62575. };
  62576. /**
  62577. * Load a scene into an asset container
  62578. * @param rootUrl a string that defines the root url for scene and resources
  62579. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62580. * @param scene is the instance of BABYLON.Scene to append to
  62581. * @param onSuccess a callback with the scene when import succeeds
  62582. * @param onProgress a callback with a progress event for each file being loaded
  62583. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62584. * @param pluginExtension the extension used to determine the plugin
  62585. * @returns The loaded plugin
  62586. */
  62587. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62588. if (onSuccess === void 0) { onSuccess = null; }
  62589. if (onProgress === void 0) { onProgress = null; }
  62590. if (onError === void 0) { onError = null; }
  62591. if (pluginExtension === void 0) { pluginExtension = null; }
  62592. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62593. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62594. return null;
  62595. }
  62596. var loadingToken = {};
  62597. scene._addPendingData(loadingToken);
  62598. var disposeHandler = function () {
  62599. scene._removePendingData(loadingToken);
  62600. };
  62601. var errorHandler = function (message, exception) {
  62602. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62603. if (onError) {
  62604. onError(scene, errorMessage, exception);
  62605. }
  62606. else {
  62607. BABYLON.Tools.Error(errorMessage);
  62608. // should the exception be thrown?
  62609. }
  62610. disposeHandler();
  62611. };
  62612. var progressHandler = onProgress ? function (event) {
  62613. try {
  62614. onProgress(event);
  62615. }
  62616. catch (e) {
  62617. errorHandler("Error in onProgress callback", e);
  62618. }
  62619. } : undefined;
  62620. var successHandler = function (assets) {
  62621. if (onSuccess) {
  62622. try {
  62623. onSuccess(assets);
  62624. }
  62625. catch (e) {
  62626. errorHandler("Error in onSuccess callback", e);
  62627. }
  62628. }
  62629. scene._removePendingData(loadingToken);
  62630. };
  62631. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62632. if (plugin.loadAssetContainer) {
  62633. var syncedPlugin = plugin;
  62634. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62635. if (!assetContainer) {
  62636. return;
  62637. }
  62638. scene.loadingPluginName = plugin.name;
  62639. successHandler(assetContainer);
  62640. }
  62641. else if (plugin.loadAssetContainerAsync) {
  62642. var asyncedPlugin = plugin;
  62643. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62644. scene.loadingPluginName = plugin.name;
  62645. successHandler(assetContainer);
  62646. }).catch(function (error) {
  62647. errorHandler(error.message, error);
  62648. });
  62649. }
  62650. else {
  62651. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62652. }
  62653. if (SceneLoader.ShowLoadingScreen) {
  62654. scene.executeWhenReady(function () {
  62655. scene.getEngine().hideLoadingUI();
  62656. });
  62657. }
  62658. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62659. };
  62660. /**
  62661. * Load a scene into an asset container
  62662. * @param rootUrl a string that defines the root url for scene and resources
  62663. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62664. * @param scene is the instance of BABYLON.Scene to append to
  62665. * @param onProgress a callback with a progress event for each file being loaded
  62666. * @param pluginExtension the extension used to determine the plugin
  62667. * @returns The loaded asset container
  62668. */
  62669. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62670. if (onProgress === void 0) { onProgress = null; }
  62671. if (pluginExtension === void 0) { pluginExtension = null; }
  62672. return new Promise(function (resolve, reject) {
  62673. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62674. resolve(assetContainer);
  62675. }, onProgress, function (scene, message, exception) {
  62676. reject(exception || new Error(message));
  62677. }, pluginExtension);
  62678. });
  62679. };
  62680. // Flags
  62681. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62682. SceneLoader._ShowLoadingScreen = true;
  62683. SceneLoader._CleanBoneMatrixWeights = false;
  62684. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62685. // Members
  62686. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62687. SceneLoader._registeredPlugins = {};
  62688. return SceneLoader;
  62689. }());
  62690. BABYLON.SceneLoader = SceneLoader;
  62691. ;
  62692. })(BABYLON || (BABYLON = {}));
  62693. //# sourceMappingURL=babylon.sceneLoader.js.map
  62694. var BABYLON;
  62695. (function (BABYLON) {
  62696. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62697. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62698. var parsedMaterial = parsedData.materials[index];
  62699. if (parsedMaterial.id === id) {
  62700. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62701. }
  62702. }
  62703. return null;
  62704. };
  62705. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62706. for (var i in names) {
  62707. if (mesh.name === names[i]) {
  62708. hierarchyIds.push(mesh.id);
  62709. return true;
  62710. }
  62711. }
  62712. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62713. hierarchyIds.push(mesh.id);
  62714. return true;
  62715. }
  62716. return false;
  62717. };
  62718. var logOperation = function (operation, producer) {
  62719. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62720. };
  62721. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62722. if (addToScene === void 0) { addToScene = false; }
  62723. var container = new BABYLON.AssetContainer(scene);
  62724. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62725. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62726. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62727. // and avoid problems with multiple concurrent .babylon loads.
  62728. var log = "importScene has failed JSON parse";
  62729. try {
  62730. var parsedData = JSON.parse(data);
  62731. log = "";
  62732. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62733. var index;
  62734. var cache;
  62735. // Lights
  62736. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62737. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62738. var parsedLight = parsedData.lights[index];
  62739. var light = BABYLON.Light.Parse(parsedLight, scene);
  62740. if (light) {
  62741. container.lights.push(light);
  62742. log += (index === 0 ? "\n\tLights:" : "");
  62743. log += "\n\t\t" + light.toString(fullDetails);
  62744. }
  62745. }
  62746. }
  62747. // Animations
  62748. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62749. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62750. var parsedAnimation = parsedData.animations[index];
  62751. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62752. scene.animations.push(animation);
  62753. container.animations.push(animation);
  62754. log += (index === 0 ? "\n\tAnimations:" : "");
  62755. log += "\n\t\t" + animation.toString(fullDetails);
  62756. }
  62757. }
  62758. // Materials
  62759. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62760. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62761. var parsedMaterial = parsedData.materials[index];
  62762. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62763. container.materials.push(mat);
  62764. log += (index === 0 ? "\n\tMaterials:" : "");
  62765. log += "\n\t\t" + mat.toString(fullDetails);
  62766. }
  62767. }
  62768. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62769. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62770. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62771. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62772. container.multiMaterials.push(mmat);
  62773. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62774. log += "\n\t\t" + mmat.toString(fullDetails);
  62775. }
  62776. }
  62777. // Morph targets
  62778. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62779. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62780. var managerData = _a[_i];
  62781. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62782. }
  62783. }
  62784. // Skeletons
  62785. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62786. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62787. var parsedSkeleton = parsedData.skeletons[index];
  62788. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62789. container.skeletons.push(skeleton);
  62790. log += (index === 0 ? "\n\tSkeletons:" : "");
  62791. log += "\n\t\t" + skeleton.toString(fullDetails);
  62792. }
  62793. }
  62794. // Geometries
  62795. var geometries = parsedData.geometries;
  62796. if (geometries !== undefined && geometries !== null) {
  62797. var addedGeometry = new Array();
  62798. // Boxes
  62799. var boxes = geometries.boxes;
  62800. if (boxes !== undefined && boxes !== null) {
  62801. for (index = 0, cache = boxes.length; index < cache; index++) {
  62802. var parsedBox = boxes[index];
  62803. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62804. }
  62805. }
  62806. // Spheres
  62807. var spheres = geometries.spheres;
  62808. if (spheres !== undefined && spheres !== null) {
  62809. for (index = 0, cache = spheres.length; index < cache; index++) {
  62810. var parsedSphere = spheres[index];
  62811. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62812. }
  62813. }
  62814. // Cylinders
  62815. var cylinders = geometries.cylinders;
  62816. if (cylinders !== undefined && cylinders !== null) {
  62817. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62818. var parsedCylinder = cylinders[index];
  62819. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62820. }
  62821. }
  62822. // Toruses
  62823. var toruses = geometries.toruses;
  62824. if (toruses !== undefined && toruses !== null) {
  62825. for (index = 0, cache = toruses.length; index < cache; index++) {
  62826. var parsedTorus = toruses[index];
  62827. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62828. }
  62829. }
  62830. // Grounds
  62831. var grounds = geometries.grounds;
  62832. if (grounds !== undefined && grounds !== null) {
  62833. for (index = 0, cache = grounds.length; index < cache; index++) {
  62834. var parsedGround = grounds[index];
  62835. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62836. }
  62837. }
  62838. // Planes
  62839. var planes = geometries.planes;
  62840. if (planes !== undefined && planes !== null) {
  62841. for (index = 0, cache = planes.length; index < cache; index++) {
  62842. var parsedPlane = planes[index];
  62843. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62844. }
  62845. }
  62846. // TorusKnots
  62847. var torusKnots = geometries.torusKnots;
  62848. if (torusKnots !== undefined && torusKnots !== null) {
  62849. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62850. var parsedTorusKnot = torusKnots[index];
  62851. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62852. }
  62853. }
  62854. // VertexData
  62855. var vertexData = geometries.vertexData;
  62856. if (vertexData !== undefined && vertexData !== null) {
  62857. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62858. var parsedVertexData = vertexData[index];
  62859. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62860. }
  62861. }
  62862. addedGeometry.forEach(function (g) {
  62863. if (g) {
  62864. container.geometries.push(g);
  62865. }
  62866. });
  62867. }
  62868. // Transform nodes
  62869. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62870. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62871. var parsedTransformNode = parsedData.transformNodes[index];
  62872. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62873. container.transformNodes.push(node);
  62874. }
  62875. }
  62876. // Meshes
  62877. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62878. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62879. var parsedMesh = parsedData.meshes[index];
  62880. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62881. container.meshes.push(mesh);
  62882. log += (index === 0 ? "\n\tMeshes:" : "");
  62883. log += "\n\t\t" + mesh.toString(fullDetails);
  62884. }
  62885. }
  62886. // Cameras
  62887. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62888. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62889. var parsedCamera = parsedData.cameras[index];
  62890. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62891. container.cameras.push(camera);
  62892. log += (index === 0 ? "\n\tCameras:" : "");
  62893. log += "\n\t\t" + camera.toString(fullDetails);
  62894. }
  62895. }
  62896. // Browsing all the graph to connect the dots
  62897. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62898. var camera = scene.cameras[index];
  62899. if (camera._waitingParentId) {
  62900. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62901. camera._waitingParentId = null;
  62902. }
  62903. }
  62904. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62905. var light_1 = scene.lights[index];
  62906. if (light_1 && light_1._waitingParentId) {
  62907. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62908. light_1._waitingParentId = null;
  62909. }
  62910. }
  62911. // Sounds
  62912. // TODO: add sound
  62913. var loadedSounds = [];
  62914. var loadedSound;
  62915. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62916. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62917. var parsedSound = parsedData.sounds[index];
  62918. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62919. if (!parsedSound.url)
  62920. parsedSound.url = parsedSound.name;
  62921. if (!loadedSounds[parsedSound.url]) {
  62922. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62923. loadedSounds[parsedSound.url] = loadedSound;
  62924. container.sounds.push(loadedSound);
  62925. }
  62926. else {
  62927. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62928. }
  62929. }
  62930. else {
  62931. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62932. }
  62933. }
  62934. }
  62935. loadedSounds = [];
  62936. // Connect parents & children and parse actions
  62937. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62938. var transformNode = scene.transformNodes[index];
  62939. if (transformNode._waitingParentId) {
  62940. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62941. transformNode._waitingParentId = null;
  62942. }
  62943. }
  62944. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62945. var mesh = scene.meshes[index];
  62946. if (mesh._waitingParentId) {
  62947. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62948. mesh._waitingParentId = null;
  62949. }
  62950. if (mesh._waitingActions) {
  62951. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62952. mesh._waitingActions = null;
  62953. }
  62954. }
  62955. // freeze world matrix application
  62956. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62957. var currentMesh = scene.meshes[index];
  62958. if (currentMesh._waitingFreezeWorldMatrix) {
  62959. currentMesh.freezeWorldMatrix();
  62960. currentMesh._waitingFreezeWorldMatrix = null;
  62961. }
  62962. else {
  62963. currentMesh.computeWorldMatrix(true);
  62964. }
  62965. }
  62966. // Particles Systems
  62967. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62968. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62969. var parsedParticleSystem = parsedData.particleSystems[index];
  62970. if (parsedParticleSystem.activeParticleCount) {
  62971. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62972. container.particleSystems.push(ps);
  62973. }
  62974. else {
  62975. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62976. container.particleSystems.push(ps);
  62977. }
  62978. }
  62979. }
  62980. // Lens flares
  62981. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62982. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62983. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62984. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62985. container.lensFlareSystems.push(lf);
  62986. }
  62987. }
  62988. // Shadows
  62989. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62990. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62991. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62992. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62993. container.shadowGenerators.push(sg);
  62994. }
  62995. }
  62996. // Lights exclusions / inclusions
  62997. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62998. var light_2 = scene.lights[index];
  62999. // Excluded check
  63000. if (light_2._excludedMeshesIds.length > 0) {
  63001. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63002. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63003. if (excludedMesh) {
  63004. light_2.excludedMeshes.push(excludedMesh);
  63005. }
  63006. }
  63007. light_2._excludedMeshesIds = [];
  63008. }
  63009. // Included check
  63010. if (light_2._includedOnlyMeshesIds.length > 0) {
  63011. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63012. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63013. if (includedOnlyMesh) {
  63014. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63015. }
  63016. }
  63017. light_2._includedOnlyMeshesIds = [];
  63018. }
  63019. }
  63020. // Actions (scene)
  63021. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63022. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63023. }
  63024. if (!addToScene) {
  63025. container.removeAllFromScene();
  63026. }
  63027. }
  63028. catch (err) {
  63029. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63030. if (onError) {
  63031. onError(msg, err);
  63032. }
  63033. else {
  63034. BABYLON.Tools.Log(msg);
  63035. throw err;
  63036. }
  63037. }
  63038. finally {
  63039. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63040. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63041. }
  63042. }
  63043. return container;
  63044. };
  63045. BABYLON.SceneLoader.RegisterPlugin({
  63046. name: "babylon.js",
  63047. extensions: ".babylon",
  63048. canDirectLoad: function (data) {
  63049. if (data.indexOf("babylon") !== -1) {
  63050. return true;
  63051. }
  63052. return false;
  63053. },
  63054. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63055. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63056. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63057. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63058. // and avoid problems with multiple concurrent .babylon loads.
  63059. var log = "importMesh has failed JSON parse";
  63060. try {
  63061. var parsedData = JSON.parse(data);
  63062. log = "";
  63063. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63064. if (!meshesNames) {
  63065. meshesNames = null;
  63066. }
  63067. else if (!Array.isArray(meshesNames)) {
  63068. meshesNames = [meshesNames];
  63069. }
  63070. var hierarchyIds = new Array();
  63071. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63072. var loadedSkeletonsIds = [];
  63073. var loadedMaterialsIds = [];
  63074. var index;
  63075. var cache;
  63076. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63077. var parsedMesh = parsedData.meshes[index];
  63078. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63079. if (meshesNames !== null) {
  63080. // Remove found mesh name from list.
  63081. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63082. }
  63083. //Geometry?
  63084. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63085. //does the file contain geometries?
  63086. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63087. //find the correct geometry and add it to the scene
  63088. var found = false;
  63089. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63090. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63091. return;
  63092. }
  63093. else {
  63094. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63095. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63096. switch (geometryType) {
  63097. case "boxes":
  63098. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63099. break;
  63100. case "spheres":
  63101. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63102. break;
  63103. case "cylinders":
  63104. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63105. break;
  63106. case "toruses":
  63107. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63108. break;
  63109. case "grounds":
  63110. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63111. break;
  63112. case "planes":
  63113. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63114. break;
  63115. case "torusKnots":
  63116. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63117. break;
  63118. case "vertexData":
  63119. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63120. break;
  63121. }
  63122. found = true;
  63123. }
  63124. });
  63125. }
  63126. });
  63127. if (found === false) {
  63128. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63129. }
  63130. }
  63131. }
  63132. // Material ?
  63133. if (parsedMesh.materialId) {
  63134. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63135. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63136. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63137. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63138. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63139. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63140. var subMatId = parsedMultiMaterial.materials[matIndex];
  63141. loadedMaterialsIds.push(subMatId);
  63142. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63143. if (mat) {
  63144. log += "\n\tMaterial " + mat.toString(fullDetails);
  63145. }
  63146. }
  63147. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63148. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63149. if (mmat) {
  63150. materialFound = true;
  63151. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63152. }
  63153. break;
  63154. }
  63155. }
  63156. }
  63157. if (materialFound === false) {
  63158. loadedMaterialsIds.push(parsedMesh.materialId);
  63159. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63160. if (!mat) {
  63161. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63162. }
  63163. else {
  63164. log += "\n\tMaterial " + mat.toString(fullDetails);
  63165. }
  63166. }
  63167. }
  63168. // Skeleton ?
  63169. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63170. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63171. if (skeletonAlreadyLoaded === false) {
  63172. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63173. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63174. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63175. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63176. skeletons.push(skeleton);
  63177. loadedSkeletonsIds.push(parsedSkeleton.id);
  63178. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63179. }
  63180. }
  63181. }
  63182. }
  63183. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63184. meshes.push(mesh);
  63185. log += "\n\tMesh " + mesh.toString(fullDetails);
  63186. }
  63187. }
  63188. // Connecting parents
  63189. var currentMesh;
  63190. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63191. currentMesh = scene.meshes[index];
  63192. if (currentMesh._waitingParentId) {
  63193. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63194. currentMesh._waitingParentId = null;
  63195. }
  63196. }
  63197. // freeze and compute world matrix application
  63198. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63199. currentMesh = scene.meshes[index];
  63200. if (currentMesh._waitingFreezeWorldMatrix) {
  63201. currentMesh.freezeWorldMatrix();
  63202. currentMesh._waitingFreezeWorldMatrix = null;
  63203. }
  63204. else {
  63205. currentMesh.computeWorldMatrix(true);
  63206. }
  63207. }
  63208. }
  63209. // Particles
  63210. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63211. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63212. var parsedParticleSystem = parsedData.particleSystems[index];
  63213. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63214. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63215. }
  63216. }
  63217. }
  63218. return true;
  63219. }
  63220. catch (err) {
  63221. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63222. if (onError) {
  63223. onError(msg, err);
  63224. }
  63225. else {
  63226. BABYLON.Tools.Log(msg);
  63227. throw err;
  63228. }
  63229. }
  63230. finally {
  63231. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63232. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63233. }
  63234. }
  63235. return false;
  63236. },
  63237. load: function (scene, data, rootUrl, onError) {
  63238. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63239. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63240. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63241. // and avoid problems with multiple concurrent .babylon loads.
  63242. var log = "importScene has failed JSON parse";
  63243. try {
  63244. var parsedData = JSON.parse(data);
  63245. log = "";
  63246. // Scene
  63247. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63248. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63249. }
  63250. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63251. scene.autoClear = parsedData.autoClear;
  63252. }
  63253. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63254. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63255. }
  63256. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63257. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63258. }
  63259. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63260. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63261. }
  63262. // Fog
  63263. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63264. scene.fogMode = parsedData.fogMode;
  63265. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63266. scene.fogStart = parsedData.fogStart;
  63267. scene.fogEnd = parsedData.fogEnd;
  63268. scene.fogDensity = parsedData.fogDensity;
  63269. log += "\tFog mode for scene: ";
  63270. switch (scene.fogMode) {
  63271. // getters not compiling, so using hardcoded
  63272. case 1:
  63273. log += "exp\n";
  63274. break;
  63275. case 2:
  63276. log += "exp2\n";
  63277. break;
  63278. case 3:
  63279. log += "linear\n";
  63280. break;
  63281. }
  63282. }
  63283. //Physics
  63284. if (parsedData.physicsEnabled) {
  63285. var physicsPlugin;
  63286. if (parsedData.physicsEngine === "cannon") {
  63287. physicsPlugin = new BABYLON.CannonJSPlugin();
  63288. }
  63289. else if (parsedData.physicsEngine === "oimo") {
  63290. physicsPlugin = new BABYLON.OimoJSPlugin();
  63291. }
  63292. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63293. //else - default engine, which is currently oimo
  63294. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63295. scene.enablePhysics(physicsGravity, physicsPlugin);
  63296. }
  63297. // Metadata
  63298. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63299. scene.metadata = parsedData.metadata;
  63300. }
  63301. //collisions, if defined. otherwise, default is true
  63302. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63303. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63304. }
  63305. scene.workerCollisions = !!parsedData.workerCollisions;
  63306. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63307. if (!container) {
  63308. return false;
  63309. }
  63310. if (parsedData.autoAnimate) {
  63311. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63312. }
  63313. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63314. scene.setActiveCameraByID(parsedData.activeCameraID);
  63315. }
  63316. // Environment texture
  63317. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63318. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63319. if (parsedData.createDefaultSkybox === true) {
  63320. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63321. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63322. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63323. }
  63324. }
  63325. // Finish
  63326. return true;
  63327. }
  63328. catch (err) {
  63329. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63330. if (onError) {
  63331. onError(msg, err);
  63332. }
  63333. else {
  63334. BABYLON.Tools.Log(msg);
  63335. throw err;
  63336. }
  63337. }
  63338. finally {
  63339. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63340. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63341. }
  63342. }
  63343. return false;
  63344. },
  63345. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63346. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63347. return container;
  63348. }
  63349. });
  63350. })(BABYLON || (BABYLON = {}));
  63351. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63352. var BABYLON;
  63353. (function (BABYLON) {
  63354. var FilesInput = /** @class */ (function () {
  63355. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63356. this.onProcessFileCallback = function () { return true; };
  63357. this._engine = engine;
  63358. this._currentScene = scene;
  63359. this._sceneLoadedCallback = sceneLoadedCallback;
  63360. this._progressCallback = progressCallback;
  63361. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63362. this._textureLoadingCallback = textureLoadingCallback;
  63363. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63364. this._onReloadCallback = onReloadCallback;
  63365. this._errorCallback = errorCallback;
  63366. }
  63367. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63368. var _this = this;
  63369. if (elementToMonitor) {
  63370. this._elementToMonitor = elementToMonitor;
  63371. this._dragEnterHandler = function (e) { _this.drag(e); };
  63372. this._dragOverHandler = function (e) { _this.drag(e); };
  63373. this._dropHandler = function (e) { _this.drop(e); };
  63374. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63375. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63376. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63377. }
  63378. };
  63379. FilesInput.prototype.dispose = function () {
  63380. if (!this._elementToMonitor) {
  63381. return;
  63382. }
  63383. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63384. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63385. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63386. };
  63387. FilesInput.prototype.renderFunction = function () {
  63388. if (this._additionalRenderLoopLogicCallback) {
  63389. this._additionalRenderLoopLogicCallback();
  63390. }
  63391. if (this._currentScene) {
  63392. if (this._textureLoadingCallback) {
  63393. var remaining = this._currentScene.getWaitingItemsCount();
  63394. if (remaining > 0) {
  63395. this._textureLoadingCallback(remaining);
  63396. }
  63397. }
  63398. this._currentScene.render();
  63399. }
  63400. };
  63401. FilesInput.prototype.drag = function (e) {
  63402. e.stopPropagation();
  63403. e.preventDefault();
  63404. };
  63405. FilesInput.prototype.drop = function (eventDrop) {
  63406. eventDrop.stopPropagation();
  63407. eventDrop.preventDefault();
  63408. this.loadFiles(eventDrop);
  63409. };
  63410. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63411. var _this = this;
  63412. var reader = folder.createReader();
  63413. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63414. reader.readEntries(function (entries) {
  63415. remaining.count += entries.length;
  63416. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63417. var entry = entries_1[_i];
  63418. if (entry.isFile) {
  63419. entry.file(function (file) {
  63420. file.correctName = relativePath + file.name;
  63421. files.push(file);
  63422. if (--remaining.count === 0) {
  63423. callback();
  63424. }
  63425. });
  63426. }
  63427. else if (entry.isDirectory) {
  63428. _this._traverseFolder(entry, files, remaining, callback);
  63429. }
  63430. }
  63431. if (--remaining.count) {
  63432. callback();
  63433. }
  63434. });
  63435. };
  63436. FilesInput.prototype._processFiles = function (files) {
  63437. for (var i = 0; i < files.length; i++) {
  63438. var name = files[i].correctName.toLowerCase();
  63439. var extension = name.split('.').pop();
  63440. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63441. continue;
  63442. }
  63443. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63444. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63445. this._sceneFileToLoad = files[i];
  63446. }
  63447. else {
  63448. FilesInput.FilesToLoad[name] = files[i];
  63449. }
  63450. }
  63451. };
  63452. FilesInput.prototype.loadFiles = function (event) {
  63453. var _this = this;
  63454. if (this._startingProcessingFilesCallback)
  63455. this._startingProcessingFilesCallback();
  63456. // Handling data transfer via drag'n'drop
  63457. if (event && event.dataTransfer && event.dataTransfer.files) {
  63458. this._filesToLoad = event.dataTransfer.files;
  63459. }
  63460. // Handling files from input files
  63461. if (event && event.target && event.target.files) {
  63462. this._filesToLoad = event.target.files;
  63463. }
  63464. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63465. var files_1 = new Array();
  63466. var folders = [];
  63467. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63468. for (var i = 0; i < this._filesToLoad.length; i++) {
  63469. var fileToLoad = this._filesToLoad[i];
  63470. var name_1 = fileToLoad.name.toLowerCase();
  63471. var entry = void 0;
  63472. fileToLoad.correctName = name_1;
  63473. if (items) {
  63474. var item = items[i];
  63475. if (item.getAsEntry) {
  63476. entry = item.getAsEntry();
  63477. }
  63478. else if (item.webkitGetAsEntry) {
  63479. entry = item.webkitGetAsEntry();
  63480. }
  63481. }
  63482. if (!entry) {
  63483. files_1.push(fileToLoad);
  63484. }
  63485. else {
  63486. if (entry.isDirectory) {
  63487. folders.push(entry);
  63488. }
  63489. else {
  63490. files_1.push(fileToLoad);
  63491. }
  63492. }
  63493. }
  63494. if (folders.length === 0) {
  63495. this._processFiles(files_1);
  63496. this._processReload();
  63497. }
  63498. else {
  63499. var remaining = { count: folders.length };
  63500. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63501. var folder = folders_1[_i];
  63502. this._traverseFolder(folder, files_1, remaining, function () {
  63503. _this._processFiles(files_1);
  63504. if (remaining.count === 0) {
  63505. _this._processReload();
  63506. }
  63507. });
  63508. }
  63509. }
  63510. }
  63511. };
  63512. FilesInput.prototype._processReload = function () {
  63513. if (this._onReloadCallback) {
  63514. this._onReloadCallback(this._sceneFileToLoad);
  63515. }
  63516. else {
  63517. this.reload();
  63518. }
  63519. };
  63520. FilesInput.prototype.reload = function () {
  63521. var _this = this;
  63522. // If a scene file has been provided
  63523. if (this._sceneFileToLoad) {
  63524. if (this._currentScene) {
  63525. if (BABYLON.Tools.errorsCount > 0) {
  63526. BABYLON.Tools.ClearLogCache();
  63527. }
  63528. this._engine.stopRenderLoop();
  63529. this._currentScene.dispose();
  63530. }
  63531. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63532. if (_this._progressCallback) {
  63533. _this._progressCallback(progress);
  63534. }
  63535. }).then(function (scene) {
  63536. _this._currentScene = scene;
  63537. if (_this._sceneLoadedCallback) {
  63538. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  63539. }
  63540. // Wait for textures and shaders to be ready
  63541. _this._currentScene.executeWhenReady(function () {
  63542. _this._engine.runRenderLoop(function () {
  63543. _this.renderFunction();
  63544. });
  63545. });
  63546. }).catch(function (error) {
  63547. if (_this._errorCallback) {
  63548. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  63549. }
  63550. });
  63551. }
  63552. else {
  63553. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63554. }
  63555. };
  63556. FilesInput.FilesToLoad = {};
  63557. return FilesInput;
  63558. }());
  63559. BABYLON.FilesInput = FilesInput;
  63560. })(BABYLON || (BABYLON = {}));
  63561. //# sourceMappingURL=babylon.filesInput.js.map
  63562. var BABYLON;
  63563. (function (BABYLON) {
  63564. /**
  63565. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63566. * The underlying implementation relies on an associative array to ensure the best performances.
  63567. * The value can be anything including 'null' but except 'undefined'
  63568. */
  63569. var StringDictionary = /** @class */ (function () {
  63570. function StringDictionary() {
  63571. this._count = 0;
  63572. this._data = {};
  63573. }
  63574. /**
  63575. * This will clear this dictionary and copy the content from the 'source' one.
  63576. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63577. * @param source the dictionary to take the content from and copy to this dictionary
  63578. */
  63579. StringDictionary.prototype.copyFrom = function (source) {
  63580. var _this = this;
  63581. this.clear();
  63582. source.forEach(function (t, v) { return _this.add(t, v); });
  63583. };
  63584. /**
  63585. * Get a value based from its key
  63586. * @param key the given key to get the matching value from
  63587. * @return the value if found, otherwise undefined is returned
  63588. */
  63589. StringDictionary.prototype.get = function (key) {
  63590. var val = this._data[key];
  63591. if (val !== undefined) {
  63592. return val;
  63593. }
  63594. return undefined;
  63595. };
  63596. /**
  63597. * Get a value from its key or add it if it doesn't exist.
  63598. * This method will ensure you that a given key/data will be present in the dictionary.
  63599. * @param key the given key to get the matching value from
  63600. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63601. * The factory will only be invoked if there's no data for the given key.
  63602. * @return the value corresponding to the key.
  63603. */
  63604. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63605. var val = this.get(key);
  63606. if (val !== undefined) {
  63607. return val;
  63608. }
  63609. val = factory(key);
  63610. if (val) {
  63611. this.add(key, val);
  63612. }
  63613. return val;
  63614. };
  63615. /**
  63616. * Get a value from its key if present in the dictionary otherwise add it
  63617. * @param key the key to get the value from
  63618. * @param val if there's no such key/value pair in the dictionary add it with this value
  63619. * @return the value corresponding to the key
  63620. */
  63621. StringDictionary.prototype.getOrAdd = function (key, val) {
  63622. var curVal = this.get(key);
  63623. if (curVal !== undefined) {
  63624. return curVal;
  63625. }
  63626. this.add(key, val);
  63627. return val;
  63628. };
  63629. /**
  63630. * Check if there's a given key in the dictionary
  63631. * @param key the key to check for
  63632. * @return true if the key is present, false otherwise
  63633. */
  63634. StringDictionary.prototype.contains = function (key) {
  63635. return this._data[key] !== undefined;
  63636. };
  63637. /**
  63638. * Add a new key and its corresponding value
  63639. * @param key the key to add
  63640. * @param value the value corresponding to the key
  63641. * @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
  63642. */
  63643. StringDictionary.prototype.add = function (key, value) {
  63644. if (this._data[key] !== undefined) {
  63645. return false;
  63646. }
  63647. this._data[key] = value;
  63648. ++this._count;
  63649. return true;
  63650. };
  63651. StringDictionary.prototype.set = function (key, value) {
  63652. if (this._data[key] === undefined) {
  63653. return false;
  63654. }
  63655. this._data[key] = value;
  63656. return true;
  63657. };
  63658. /**
  63659. * Get the element of the given key and remove it from the dictionary
  63660. * @param key
  63661. */
  63662. StringDictionary.prototype.getAndRemove = function (key) {
  63663. var val = this.get(key);
  63664. if (val !== undefined) {
  63665. delete this._data[key];
  63666. --this._count;
  63667. return val;
  63668. }
  63669. return null;
  63670. };
  63671. /**
  63672. * Remove a key/value from the dictionary.
  63673. * @param key the key to remove
  63674. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63675. */
  63676. StringDictionary.prototype.remove = function (key) {
  63677. if (this.contains(key)) {
  63678. delete this._data[key];
  63679. --this._count;
  63680. return true;
  63681. }
  63682. return false;
  63683. };
  63684. /**
  63685. * Clear the whole content of the dictionary
  63686. */
  63687. StringDictionary.prototype.clear = function () {
  63688. this._data = {};
  63689. this._count = 0;
  63690. };
  63691. Object.defineProperty(StringDictionary.prototype, "count", {
  63692. get: function () {
  63693. return this._count;
  63694. },
  63695. enumerable: true,
  63696. configurable: true
  63697. });
  63698. /**
  63699. * Execute a callback on each key/val of the dictionary.
  63700. * Note that you can remove any element in this dictionary in the callback implementation
  63701. * @param callback the callback to execute on a given key/value pair
  63702. */
  63703. StringDictionary.prototype.forEach = function (callback) {
  63704. for (var cur in this._data) {
  63705. var val = this._data[cur];
  63706. callback(cur, val);
  63707. }
  63708. };
  63709. /**
  63710. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63711. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63712. * Note that you can remove any element in this dictionary in the callback implementation
  63713. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63714. */
  63715. StringDictionary.prototype.first = function (callback) {
  63716. for (var cur in this._data) {
  63717. var val = this._data[cur];
  63718. var res = callback(cur, val);
  63719. if (res) {
  63720. return res;
  63721. }
  63722. }
  63723. return null;
  63724. };
  63725. return StringDictionary;
  63726. }());
  63727. BABYLON.StringDictionary = StringDictionary;
  63728. })(BABYLON || (BABYLON = {}));
  63729. //# sourceMappingURL=babylon.stringDictionary.js.map
  63730. var BABYLON;
  63731. (function (BABYLON) {
  63732. var Tags = /** @class */ (function () {
  63733. function Tags() {
  63734. }
  63735. Tags.EnableFor = function (obj) {
  63736. obj._tags = obj._tags || {};
  63737. obj.hasTags = function () {
  63738. return Tags.HasTags(obj);
  63739. };
  63740. obj.addTags = function (tagsString) {
  63741. return Tags.AddTagsTo(obj, tagsString);
  63742. };
  63743. obj.removeTags = function (tagsString) {
  63744. return Tags.RemoveTagsFrom(obj, tagsString);
  63745. };
  63746. obj.matchesTagsQuery = function (tagsQuery) {
  63747. return Tags.MatchesQuery(obj, tagsQuery);
  63748. };
  63749. };
  63750. Tags.DisableFor = function (obj) {
  63751. delete obj._tags;
  63752. delete obj.hasTags;
  63753. delete obj.addTags;
  63754. delete obj.removeTags;
  63755. delete obj.matchesTagsQuery;
  63756. };
  63757. Tags.HasTags = function (obj) {
  63758. if (!obj._tags) {
  63759. return false;
  63760. }
  63761. return !BABYLON.Tools.IsEmpty(obj._tags);
  63762. };
  63763. Tags.GetTags = function (obj, asString) {
  63764. if (asString === void 0) { asString = true; }
  63765. if (!obj._tags) {
  63766. return null;
  63767. }
  63768. if (asString) {
  63769. var tagsArray = [];
  63770. for (var tag in obj._tags) {
  63771. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63772. tagsArray.push(tag);
  63773. }
  63774. }
  63775. return tagsArray.join(" ");
  63776. }
  63777. else {
  63778. return obj._tags;
  63779. }
  63780. };
  63781. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63782. // a tag cannot start with '||', '&&', and '!'
  63783. // it cannot contain whitespaces
  63784. Tags.AddTagsTo = function (obj, tagsString) {
  63785. if (!tagsString) {
  63786. return;
  63787. }
  63788. if (typeof tagsString !== "string") {
  63789. return;
  63790. }
  63791. var tags = tagsString.split(" ");
  63792. tags.forEach(function (tag, index, array) {
  63793. Tags._AddTagTo(obj, tag);
  63794. });
  63795. };
  63796. Tags._AddTagTo = function (obj, tag) {
  63797. tag = tag.trim();
  63798. if (tag === "" || tag === "true" || tag === "false") {
  63799. return;
  63800. }
  63801. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63802. return;
  63803. }
  63804. Tags.EnableFor(obj);
  63805. obj._tags[tag] = true;
  63806. };
  63807. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63808. if (!Tags.HasTags(obj)) {
  63809. return;
  63810. }
  63811. var tags = tagsString.split(" ");
  63812. for (var t in tags) {
  63813. Tags._RemoveTagFrom(obj, tags[t]);
  63814. }
  63815. };
  63816. Tags._RemoveTagFrom = function (obj, tag) {
  63817. delete obj._tags[tag];
  63818. };
  63819. Tags.MatchesQuery = function (obj, tagsQuery) {
  63820. if (tagsQuery === undefined) {
  63821. return true;
  63822. }
  63823. if (tagsQuery === "") {
  63824. return Tags.HasTags(obj);
  63825. }
  63826. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63827. };
  63828. return Tags;
  63829. }());
  63830. BABYLON.Tags = Tags;
  63831. })(BABYLON || (BABYLON = {}));
  63832. //# sourceMappingURL=babylon.tags.js.map
  63833. var BABYLON;
  63834. (function (BABYLON) {
  63835. var AndOrNotEvaluator = /** @class */ (function () {
  63836. function AndOrNotEvaluator() {
  63837. }
  63838. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63839. if (!query.match(/\([^\(\)]*\)/g)) {
  63840. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63841. }
  63842. else {
  63843. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63844. // remove parenthesis
  63845. r = r.slice(1, r.length - 1);
  63846. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63847. });
  63848. }
  63849. if (query === "true") {
  63850. return true;
  63851. }
  63852. if (query === "false") {
  63853. return false;
  63854. }
  63855. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63856. };
  63857. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63858. evaluateCallback = evaluateCallback || (function (r) {
  63859. return r === "true" ? true : false;
  63860. });
  63861. var result;
  63862. var or = parenthesisContent.split("||");
  63863. for (var i in or) {
  63864. if (or.hasOwnProperty(i)) {
  63865. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63866. var and = ori.split("&&");
  63867. if (and.length > 1) {
  63868. for (var j = 0; j < and.length; ++j) {
  63869. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63870. if (andj !== "true" && andj !== "false") {
  63871. if (andj[0] === "!") {
  63872. result = !evaluateCallback(andj.substring(1));
  63873. }
  63874. else {
  63875. result = evaluateCallback(andj);
  63876. }
  63877. }
  63878. else {
  63879. result = andj === "true" ? true : false;
  63880. }
  63881. if (!result) {
  63882. ori = "false";
  63883. break;
  63884. }
  63885. }
  63886. }
  63887. if (result || ori === "true") {
  63888. result = true;
  63889. break;
  63890. }
  63891. // result equals false (or undefined)
  63892. if (ori !== "true" && ori !== "false") {
  63893. if (ori[0] === "!") {
  63894. result = !evaluateCallback(ori.substring(1));
  63895. }
  63896. else {
  63897. result = evaluateCallback(ori);
  63898. }
  63899. }
  63900. else {
  63901. result = ori === "true" ? true : false;
  63902. }
  63903. }
  63904. }
  63905. // the whole parenthesis scope is replaced by 'true' or 'false'
  63906. return result ? "true" : "false";
  63907. };
  63908. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63909. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63910. // remove whitespaces
  63911. r = r.replace(/[\s]/g, function () { return ""; });
  63912. return r.length % 2 ? "!" : "";
  63913. });
  63914. booleanString = booleanString.trim();
  63915. if (booleanString === "!true") {
  63916. booleanString = "false";
  63917. }
  63918. else if (booleanString === "!false") {
  63919. booleanString = "true";
  63920. }
  63921. return booleanString;
  63922. };
  63923. return AndOrNotEvaluator;
  63924. }());
  63925. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63926. })(BABYLON || (BABYLON = {}));
  63927. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63928. var BABYLON;
  63929. (function (BABYLON) {
  63930. var Database = /** @class */ (function () {
  63931. function Database(urlToScene, callbackManifestChecked) {
  63932. // Handling various flavors of prefixed version of IndexedDB
  63933. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63934. this.callbackManifestChecked = callbackManifestChecked;
  63935. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63936. this.db = null;
  63937. this._enableSceneOffline = false;
  63938. this._enableTexturesOffline = false;
  63939. this.manifestVersionFound = 0;
  63940. this.mustUpdateRessources = false;
  63941. this.hasReachedQuota = false;
  63942. if (!Database.IDBStorageEnabled) {
  63943. this.callbackManifestChecked(true);
  63944. }
  63945. else {
  63946. this.checkManifestFile();
  63947. }
  63948. }
  63949. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63950. get: function () {
  63951. return this._enableSceneOffline;
  63952. },
  63953. enumerable: true,
  63954. configurable: true
  63955. });
  63956. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63957. get: function () {
  63958. return this._enableTexturesOffline;
  63959. },
  63960. enumerable: true,
  63961. configurable: true
  63962. });
  63963. Database.prototype.checkManifestFile = function () {
  63964. var _this = this;
  63965. var noManifestFile = function () {
  63966. _this._enableSceneOffline = false;
  63967. _this._enableTexturesOffline = false;
  63968. _this.callbackManifestChecked(false);
  63969. };
  63970. var timeStampUsed = false;
  63971. var manifestURL = this.currentSceneUrl + ".manifest";
  63972. var xhr = new XMLHttpRequest();
  63973. if (navigator.onLine) {
  63974. // Adding a timestamp to by-pass browsers' cache
  63975. timeStampUsed = true;
  63976. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63977. }
  63978. xhr.open("GET", manifestURL, true);
  63979. xhr.addEventListener("load", function () {
  63980. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63981. try {
  63982. var manifestFile = JSON.parse(xhr.response);
  63983. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63984. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63985. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63986. _this.manifestVersionFound = manifestFile.version;
  63987. }
  63988. if (_this.callbackManifestChecked) {
  63989. _this.callbackManifestChecked(true);
  63990. }
  63991. }
  63992. catch (ex) {
  63993. noManifestFile();
  63994. }
  63995. }
  63996. else {
  63997. noManifestFile();
  63998. }
  63999. }, false);
  64000. xhr.addEventListener("error", function (event) {
  64001. if (timeStampUsed) {
  64002. timeStampUsed = false;
  64003. // Let's retry without the timeStamp
  64004. // It could fail when coupled with HTML5 Offline API
  64005. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64006. xhr.open("GET", retryManifestURL, true);
  64007. xhr.send();
  64008. }
  64009. else {
  64010. noManifestFile();
  64011. }
  64012. }, false);
  64013. try {
  64014. xhr.send();
  64015. }
  64016. catch (ex) {
  64017. BABYLON.Tools.Error("Error on XHR send request.");
  64018. this.callbackManifestChecked(false);
  64019. }
  64020. };
  64021. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64022. var _this = this;
  64023. var handleError = function () {
  64024. _this.isSupported = false;
  64025. if (errorCallback)
  64026. errorCallback();
  64027. };
  64028. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64029. // Your browser doesn't support IndexedDB
  64030. this.isSupported = false;
  64031. if (errorCallback)
  64032. errorCallback();
  64033. }
  64034. else {
  64035. // If the DB hasn't been opened or created yet
  64036. if (!this.db) {
  64037. this.hasReachedQuota = false;
  64038. this.isSupported = true;
  64039. var request = this.idbFactory.open("babylonjs", 1);
  64040. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64041. request.onerror = function (event) {
  64042. handleError();
  64043. };
  64044. // executes when a version change transaction cannot complete due to other active transactions
  64045. request.onblocked = function (event) {
  64046. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64047. handleError();
  64048. };
  64049. // DB has been opened successfully
  64050. request.onsuccess = function (event) {
  64051. _this.db = request.result;
  64052. successCallback();
  64053. };
  64054. // Initialization of the DB. Creating Scenes & Textures stores
  64055. request.onupgradeneeded = function (event) {
  64056. _this.db = (event.target).result;
  64057. if (_this.db) {
  64058. try {
  64059. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64060. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64061. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64062. }
  64063. catch (ex) {
  64064. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64065. handleError();
  64066. }
  64067. }
  64068. };
  64069. }
  64070. else {
  64071. if (successCallback)
  64072. successCallback();
  64073. }
  64074. }
  64075. };
  64076. Database.prototype.loadImageFromDB = function (url, image) {
  64077. var _this = this;
  64078. var completeURL = Database.ReturnFullUrlLocation(url);
  64079. var saveAndLoadImage = function () {
  64080. if (!_this.hasReachedQuota && _this.db !== null) {
  64081. // the texture is not yet in the DB, let's try to save it
  64082. _this._saveImageIntoDBAsync(completeURL, image);
  64083. }
  64084. else {
  64085. image.src = url;
  64086. }
  64087. };
  64088. if (!this.mustUpdateRessources) {
  64089. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64090. }
  64091. else {
  64092. saveAndLoadImage();
  64093. }
  64094. };
  64095. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64096. if (this.isSupported && this.db !== null) {
  64097. var texture;
  64098. var transaction = this.db.transaction(["textures"]);
  64099. transaction.onabort = function (event) {
  64100. image.src = url;
  64101. };
  64102. transaction.oncomplete = function (event) {
  64103. var blobTextureURL;
  64104. if (texture) {
  64105. var URL = window.URL || window.webkitURL;
  64106. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64107. image.onerror = function () {
  64108. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64109. image.src = url;
  64110. };
  64111. image.src = blobTextureURL;
  64112. }
  64113. else {
  64114. notInDBCallback();
  64115. }
  64116. };
  64117. var getRequest = transaction.objectStore("textures").get(url);
  64118. getRequest.onsuccess = function (event) {
  64119. texture = (event.target).result;
  64120. };
  64121. getRequest.onerror = function (event) {
  64122. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64123. image.src = url;
  64124. };
  64125. }
  64126. else {
  64127. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64128. image.src = url;
  64129. }
  64130. };
  64131. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64132. var _this = this;
  64133. if (this.isSupported) {
  64134. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64135. var generateBlobUrl = function () {
  64136. var blobTextureURL;
  64137. if (blob) {
  64138. var URL = window.URL || window.webkitURL;
  64139. try {
  64140. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64141. }
  64142. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64143. catch (ex) {
  64144. blobTextureURL = URL.createObjectURL(blob);
  64145. }
  64146. }
  64147. if (blobTextureURL) {
  64148. image.src = blobTextureURL;
  64149. }
  64150. };
  64151. if (Database.IsUASupportingBlobStorage) {
  64152. var xhr = new XMLHttpRequest(), blob;
  64153. xhr.open("GET", url, true);
  64154. xhr.responseType = "blob";
  64155. xhr.addEventListener("load", function () {
  64156. if (xhr.status === 200 && _this.db) {
  64157. // Blob as response (XHR2)
  64158. blob = xhr.response;
  64159. var transaction = _this.db.transaction(["textures"], "readwrite");
  64160. // the transaction could abort because of a QuotaExceededError error
  64161. transaction.onabort = function (event) {
  64162. try {
  64163. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64164. var srcElement = (event.srcElement || event.target);
  64165. var error = srcElement.error;
  64166. if (error && error.name === "QuotaExceededError") {
  64167. _this.hasReachedQuota = true;
  64168. }
  64169. }
  64170. catch (ex) { }
  64171. generateBlobUrl();
  64172. };
  64173. transaction.oncomplete = function (event) {
  64174. generateBlobUrl();
  64175. };
  64176. var newTexture = { textureUrl: url, data: blob };
  64177. try {
  64178. // Put the blob into the dabase
  64179. var addRequest = transaction.objectStore("textures").put(newTexture);
  64180. addRequest.onsuccess = function (event) {
  64181. };
  64182. addRequest.onerror = function (event) {
  64183. generateBlobUrl();
  64184. };
  64185. }
  64186. catch (ex) {
  64187. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64188. if (ex.code === 25) {
  64189. Database.IsUASupportingBlobStorage = false;
  64190. }
  64191. image.src = url;
  64192. }
  64193. }
  64194. else {
  64195. image.src = url;
  64196. }
  64197. }, false);
  64198. xhr.addEventListener("error", function (event) {
  64199. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64200. image.src = url;
  64201. }, false);
  64202. xhr.send();
  64203. }
  64204. else {
  64205. image.src = url;
  64206. }
  64207. }
  64208. else {
  64209. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64210. image.src = url;
  64211. }
  64212. };
  64213. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64214. var _this = this;
  64215. var updateVersion = function () {
  64216. // the version is not yet in the DB or we need to update it
  64217. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64218. };
  64219. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64220. };
  64221. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64222. var _this = this;
  64223. if (this.isSupported && this.db) {
  64224. var version;
  64225. try {
  64226. var transaction = this.db.transaction(["versions"]);
  64227. transaction.oncomplete = function (event) {
  64228. if (version) {
  64229. // If the version in the JSON file is > than the version in DB
  64230. if (_this.manifestVersionFound > version.data) {
  64231. _this.mustUpdateRessources = true;
  64232. updateInDBCallback();
  64233. }
  64234. else {
  64235. callback(version.data);
  64236. }
  64237. }
  64238. else {
  64239. _this.mustUpdateRessources = true;
  64240. updateInDBCallback();
  64241. }
  64242. };
  64243. transaction.onabort = function (event) {
  64244. callback(-1);
  64245. };
  64246. var getRequest = transaction.objectStore("versions").get(url);
  64247. getRequest.onsuccess = function (event) {
  64248. version = (event.target).result;
  64249. };
  64250. getRequest.onerror = function (event) {
  64251. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64252. callback(-1);
  64253. };
  64254. }
  64255. catch (ex) {
  64256. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64257. callback(-1);
  64258. }
  64259. }
  64260. else {
  64261. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64262. callback(-1);
  64263. }
  64264. };
  64265. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64266. var _this = this;
  64267. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64268. try {
  64269. // Open a transaction to the database
  64270. var transaction = this.db.transaction(["versions"], "readwrite");
  64271. // the transaction could abort because of a QuotaExceededError error
  64272. transaction.onabort = function (event) {
  64273. try {
  64274. var error = event.srcElement['error'];
  64275. if (error && error.name === "QuotaExceededError") {
  64276. _this.hasReachedQuota = true;
  64277. }
  64278. }
  64279. catch (ex) { }
  64280. callback(-1);
  64281. };
  64282. transaction.oncomplete = function (event) {
  64283. callback(_this.manifestVersionFound);
  64284. };
  64285. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64286. // Put the scene into the database
  64287. var addRequest = transaction.objectStore("versions").put(newVersion);
  64288. addRequest.onsuccess = function (event) {
  64289. };
  64290. addRequest.onerror = function (event) {
  64291. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64292. };
  64293. }
  64294. catch (ex) {
  64295. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64296. callback(-1);
  64297. }
  64298. }
  64299. else {
  64300. callback(-1);
  64301. }
  64302. };
  64303. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64304. var _this = this;
  64305. var completeUrl = Database.ReturnFullUrlLocation(url);
  64306. var saveAndLoadFile = function () {
  64307. // the scene is not yet in the DB, let's try to save it
  64308. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64309. };
  64310. this._checkVersionFromDB(completeUrl, function (version) {
  64311. if (version !== -1) {
  64312. if (!_this.mustUpdateRessources) {
  64313. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64314. }
  64315. else {
  64316. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64317. }
  64318. }
  64319. else {
  64320. if (errorCallback) {
  64321. errorCallback();
  64322. }
  64323. }
  64324. });
  64325. };
  64326. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64327. if (this.isSupported && this.db) {
  64328. var targetStore;
  64329. if (url.indexOf(".babylon") !== -1) {
  64330. targetStore = "scenes";
  64331. }
  64332. else {
  64333. targetStore = "textures";
  64334. }
  64335. var file;
  64336. var transaction = this.db.transaction([targetStore]);
  64337. transaction.oncomplete = function (event) {
  64338. if (file) {
  64339. callback(file.data);
  64340. }
  64341. else {
  64342. notInDBCallback();
  64343. }
  64344. };
  64345. transaction.onabort = function (event) {
  64346. notInDBCallback();
  64347. };
  64348. var getRequest = transaction.objectStore(targetStore).get(url);
  64349. getRequest.onsuccess = function (event) {
  64350. file = (event.target).result;
  64351. };
  64352. getRequest.onerror = function (event) {
  64353. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64354. notInDBCallback();
  64355. };
  64356. }
  64357. else {
  64358. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64359. callback();
  64360. }
  64361. };
  64362. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64363. var _this = this;
  64364. if (this.isSupported) {
  64365. var targetStore;
  64366. if (url.indexOf(".babylon") !== -1) {
  64367. targetStore = "scenes";
  64368. }
  64369. else {
  64370. targetStore = "textures";
  64371. }
  64372. // Create XHR
  64373. var xhr = new XMLHttpRequest();
  64374. var fileData;
  64375. xhr.open("GET", url, true);
  64376. if (useArrayBuffer) {
  64377. xhr.responseType = "arraybuffer";
  64378. }
  64379. if (progressCallback) {
  64380. xhr.onprogress = progressCallback;
  64381. }
  64382. xhr.addEventListener("load", function () {
  64383. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64384. // Blob as response (XHR2)
  64385. //fileData = xhr.responseText;
  64386. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64387. if (!_this.hasReachedQuota && _this.db) {
  64388. // Open a transaction to the database
  64389. var transaction = _this.db.transaction([targetStore], "readwrite");
  64390. // the transaction could abort because of a QuotaExceededError error
  64391. transaction.onabort = function (event) {
  64392. try {
  64393. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64394. var error = event.srcElement['error'];
  64395. if (error && error.name === "QuotaExceededError") {
  64396. _this.hasReachedQuota = true;
  64397. }
  64398. }
  64399. catch (ex) { }
  64400. callback(fileData);
  64401. };
  64402. transaction.oncomplete = function (event) {
  64403. callback(fileData);
  64404. };
  64405. var newFile;
  64406. if (targetStore === "scenes") {
  64407. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64408. }
  64409. else {
  64410. newFile = { textureUrl: url, data: fileData };
  64411. }
  64412. try {
  64413. // Put the scene into the database
  64414. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64415. addRequest.onsuccess = function (event) {
  64416. };
  64417. addRequest.onerror = function (event) {
  64418. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64419. };
  64420. }
  64421. catch (ex) {
  64422. callback(fileData);
  64423. }
  64424. }
  64425. else {
  64426. callback(fileData);
  64427. }
  64428. }
  64429. else {
  64430. callback();
  64431. }
  64432. }, false);
  64433. xhr.addEventListener("error", function (event) {
  64434. BABYLON.Tools.Error("error on XHR request.");
  64435. callback();
  64436. }, false);
  64437. xhr.send();
  64438. }
  64439. else {
  64440. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64441. callback();
  64442. }
  64443. };
  64444. Database.IsUASupportingBlobStorage = true;
  64445. Database.IDBStorageEnabled = true;
  64446. Database.parseURL = function (url) {
  64447. var a = document.createElement('a');
  64448. a.href = url;
  64449. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64450. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64451. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64452. return absLocation;
  64453. };
  64454. Database.ReturnFullUrlLocation = function (url) {
  64455. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64456. return (Database.parseURL(window.location.href) + url);
  64457. }
  64458. else {
  64459. return url;
  64460. }
  64461. };
  64462. return Database;
  64463. }());
  64464. BABYLON.Database = Database;
  64465. })(BABYLON || (BABYLON = {}));
  64466. //# sourceMappingURL=babylon.database.js.map
  64467. var BABYLON;
  64468. (function (BABYLON) {
  64469. var FresnelParameters = /** @class */ (function () {
  64470. function FresnelParameters() {
  64471. this._isEnabled = true;
  64472. this.leftColor = BABYLON.Color3.White();
  64473. this.rightColor = BABYLON.Color3.Black();
  64474. this.bias = 0;
  64475. this.power = 1;
  64476. }
  64477. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64478. get: function () {
  64479. return this._isEnabled;
  64480. },
  64481. set: function (value) {
  64482. if (this._isEnabled === value) {
  64483. return;
  64484. }
  64485. this._isEnabled = value;
  64486. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64487. },
  64488. enumerable: true,
  64489. configurable: true
  64490. });
  64491. FresnelParameters.prototype.clone = function () {
  64492. var newFresnelParameters = new FresnelParameters();
  64493. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64494. return newFresnelParameters;
  64495. };
  64496. FresnelParameters.prototype.serialize = function () {
  64497. var serializationObject = {};
  64498. serializationObject.isEnabled = this.isEnabled;
  64499. serializationObject.leftColor = this.leftColor;
  64500. serializationObject.rightColor = this.rightColor;
  64501. serializationObject.bias = this.bias;
  64502. serializationObject.power = this.power;
  64503. return serializationObject;
  64504. };
  64505. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64506. var fresnelParameters = new FresnelParameters();
  64507. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64508. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64509. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64510. fresnelParameters.bias = parsedFresnelParameters.bias;
  64511. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64512. return fresnelParameters;
  64513. };
  64514. return FresnelParameters;
  64515. }());
  64516. BABYLON.FresnelParameters = FresnelParameters;
  64517. })(BABYLON || (BABYLON = {}));
  64518. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64519. var BABYLON;
  64520. (function (BABYLON) {
  64521. var MultiMaterial = /** @class */ (function (_super) {
  64522. __extends(MultiMaterial, _super);
  64523. function MultiMaterial(name, scene) {
  64524. var _this = _super.call(this, name, scene, true) || this;
  64525. scene.multiMaterials.push(_this);
  64526. _this.subMaterials = new Array();
  64527. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64528. return _this;
  64529. }
  64530. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  64531. get: function () {
  64532. return this._subMaterials;
  64533. },
  64534. set: function (value) {
  64535. this._subMaterials = value;
  64536. this._hookArray(value);
  64537. },
  64538. enumerable: true,
  64539. configurable: true
  64540. });
  64541. MultiMaterial.prototype._hookArray = function (array) {
  64542. var _this = this;
  64543. var oldPush = array.push;
  64544. array.push = function () {
  64545. var items = [];
  64546. for (var _i = 0; _i < arguments.length; _i++) {
  64547. items[_i] = arguments[_i];
  64548. }
  64549. var result = oldPush.apply(array, items);
  64550. _this._markAllSubMeshesAsTexturesDirty();
  64551. return result;
  64552. };
  64553. var oldSplice = array.splice;
  64554. array.splice = function (index, deleteCount) {
  64555. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64556. _this._markAllSubMeshesAsTexturesDirty();
  64557. return deleted;
  64558. };
  64559. };
  64560. // Properties
  64561. MultiMaterial.prototype.getSubMaterial = function (index) {
  64562. if (index < 0 || index >= this.subMaterials.length) {
  64563. return this.getScene().defaultMaterial;
  64564. }
  64565. return this.subMaterials[index];
  64566. };
  64567. MultiMaterial.prototype.getActiveTextures = function () {
  64568. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64569. if (subMaterial) {
  64570. return subMaterial.getActiveTextures();
  64571. }
  64572. else {
  64573. return [];
  64574. }
  64575. }));
  64576. var _a;
  64577. };
  64578. // Methods
  64579. MultiMaterial.prototype.getClassName = function () {
  64580. return "MultiMaterial";
  64581. };
  64582. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64583. for (var index = 0; index < this.subMaterials.length; index++) {
  64584. var subMaterial = this.subMaterials[index];
  64585. if (subMaterial) {
  64586. if (subMaterial.storeEffectOnSubMeshes) {
  64587. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64588. return false;
  64589. }
  64590. continue;
  64591. }
  64592. if (!subMaterial.isReady(mesh)) {
  64593. return false;
  64594. }
  64595. }
  64596. }
  64597. return true;
  64598. };
  64599. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64600. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64601. for (var index = 0; index < this.subMaterials.length; index++) {
  64602. var subMaterial = null;
  64603. var current = this.subMaterials[index];
  64604. if (cloneChildren && current) {
  64605. subMaterial = current.clone(name + "-" + current.name);
  64606. }
  64607. else {
  64608. subMaterial = this.subMaterials[index];
  64609. }
  64610. newMultiMaterial.subMaterials.push(subMaterial);
  64611. }
  64612. return newMultiMaterial;
  64613. };
  64614. MultiMaterial.prototype.serialize = function () {
  64615. var serializationObject = {};
  64616. serializationObject.name = this.name;
  64617. serializationObject.id = this.id;
  64618. if (BABYLON.Tags) {
  64619. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64620. }
  64621. serializationObject.materials = [];
  64622. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64623. var subMat = this.subMaterials[matIndex];
  64624. if (subMat) {
  64625. serializationObject.materials.push(subMat.id);
  64626. }
  64627. else {
  64628. serializationObject.materials.push(null);
  64629. }
  64630. }
  64631. return serializationObject;
  64632. };
  64633. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64634. var scene = this.getScene();
  64635. if (!scene) {
  64636. return;
  64637. }
  64638. var index = scene.multiMaterials.indexOf(this);
  64639. if (index >= 0) {
  64640. scene.multiMaterials.splice(index, 1);
  64641. }
  64642. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64643. };
  64644. return MultiMaterial;
  64645. }(BABYLON.Material));
  64646. BABYLON.MultiMaterial = MultiMaterial;
  64647. })(BABYLON || (BABYLON = {}));
  64648. //# sourceMappingURL=babylon.multiMaterial.js.map
  64649. var BABYLON;
  64650. (function (BABYLON) {
  64651. var FreeCameraTouchInput = /** @class */ (function () {
  64652. function FreeCameraTouchInput() {
  64653. this._offsetX = null;
  64654. this._offsetY = null;
  64655. this._pointerPressed = new Array();
  64656. this.touchAngularSensibility = 200000.0;
  64657. this.touchMoveSensibility = 250.0;
  64658. }
  64659. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64660. var _this = this;
  64661. var previousPosition = null;
  64662. if (this._pointerInput === undefined) {
  64663. this._onLostFocus = function (evt) {
  64664. _this._offsetX = null;
  64665. _this._offsetY = null;
  64666. };
  64667. this._pointerInput = function (p, s) {
  64668. var evt = p.event;
  64669. if (evt.pointerType === "mouse") {
  64670. return;
  64671. }
  64672. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64673. if (!noPreventDefault) {
  64674. evt.preventDefault();
  64675. }
  64676. _this._pointerPressed.push(evt.pointerId);
  64677. if (_this._pointerPressed.length !== 1) {
  64678. return;
  64679. }
  64680. previousPosition = {
  64681. x: evt.clientX,
  64682. y: evt.clientY
  64683. };
  64684. }
  64685. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64686. if (!noPreventDefault) {
  64687. evt.preventDefault();
  64688. }
  64689. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64690. if (index === -1) {
  64691. return;
  64692. }
  64693. _this._pointerPressed.splice(index, 1);
  64694. if (index != 0) {
  64695. return;
  64696. }
  64697. previousPosition = null;
  64698. _this._offsetX = null;
  64699. _this._offsetY = null;
  64700. }
  64701. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64702. if (!noPreventDefault) {
  64703. evt.preventDefault();
  64704. }
  64705. if (!previousPosition) {
  64706. return;
  64707. }
  64708. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64709. if (index != 0) {
  64710. return;
  64711. }
  64712. _this._offsetX = evt.clientX - previousPosition.x;
  64713. _this._offsetY = -(evt.clientY - previousPosition.y);
  64714. }
  64715. };
  64716. }
  64717. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64718. if (this._onLostFocus) {
  64719. element.addEventListener("blur", this._onLostFocus);
  64720. }
  64721. };
  64722. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64723. if (this._pointerInput && element) {
  64724. if (this._observer) {
  64725. this.camera.getScene().onPointerObservable.remove(this._observer);
  64726. this._observer = null;
  64727. }
  64728. if (this._onLostFocus) {
  64729. element.removeEventListener("blur", this._onLostFocus);
  64730. this._onLostFocus = null;
  64731. }
  64732. this._pointerPressed = [];
  64733. this._offsetX = null;
  64734. this._offsetY = null;
  64735. }
  64736. };
  64737. FreeCameraTouchInput.prototype.checkInputs = function () {
  64738. if (this._offsetX && this._offsetY) {
  64739. var camera = this.camera;
  64740. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64741. if (this._pointerPressed.length > 1) {
  64742. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64743. }
  64744. else {
  64745. var speed = camera._computeLocalCameraSpeed();
  64746. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64747. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64748. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64749. }
  64750. }
  64751. };
  64752. FreeCameraTouchInput.prototype.getClassName = function () {
  64753. return "FreeCameraTouchInput";
  64754. };
  64755. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64756. return "touch";
  64757. };
  64758. __decorate([
  64759. BABYLON.serialize()
  64760. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64761. __decorate([
  64762. BABYLON.serialize()
  64763. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64764. return FreeCameraTouchInput;
  64765. }());
  64766. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64767. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64768. })(BABYLON || (BABYLON = {}));
  64769. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64770. var BABYLON;
  64771. (function (BABYLON) {
  64772. // We're mainly based on the logic defined into the FreeCamera code
  64773. var TouchCamera = /** @class */ (function (_super) {
  64774. __extends(TouchCamera, _super);
  64775. //-- end properties for backward compatibility for inputs
  64776. function TouchCamera(name, position, scene) {
  64777. var _this = _super.call(this, name, position, scene) || this;
  64778. _this.inputs.addTouch();
  64779. _this._setupInputs();
  64780. return _this;
  64781. }
  64782. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64783. //-- Begin properties for backward compatibility for inputs
  64784. get: function () {
  64785. var touch = this.inputs.attached["touch"];
  64786. if (touch)
  64787. return touch.touchAngularSensibility;
  64788. return 0;
  64789. },
  64790. set: function (value) {
  64791. var touch = this.inputs.attached["touch"];
  64792. if (touch)
  64793. touch.touchAngularSensibility = value;
  64794. },
  64795. enumerable: true,
  64796. configurable: true
  64797. });
  64798. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64799. get: function () {
  64800. var touch = this.inputs.attached["touch"];
  64801. if (touch)
  64802. return touch.touchMoveSensibility;
  64803. return 0;
  64804. },
  64805. set: function (value) {
  64806. var touch = this.inputs.attached["touch"];
  64807. if (touch)
  64808. touch.touchMoveSensibility = value;
  64809. },
  64810. enumerable: true,
  64811. configurable: true
  64812. });
  64813. TouchCamera.prototype.getClassName = function () {
  64814. return "TouchCamera";
  64815. };
  64816. TouchCamera.prototype._setupInputs = function () {
  64817. var mouse = this.inputs.attached["mouse"];
  64818. if (mouse) {
  64819. mouse.touchEnabled = false;
  64820. }
  64821. };
  64822. return TouchCamera;
  64823. }(BABYLON.FreeCamera));
  64824. BABYLON.TouchCamera = TouchCamera;
  64825. })(BABYLON || (BABYLON = {}));
  64826. //# sourceMappingURL=babylon.touchCamera.js.map
  64827. var BABYLON;
  64828. (function (BABYLON) {
  64829. var ProceduralTexture = /** @class */ (function (_super) {
  64830. __extends(ProceduralTexture, _super);
  64831. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64832. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64833. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64834. if (isCube === void 0) { isCube = false; }
  64835. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64836. _this.isCube = isCube;
  64837. _this.isEnabled = true;
  64838. _this._currentRefreshId = -1;
  64839. _this._refreshRate = 1;
  64840. _this._vertexBuffers = {};
  64841. _this._uniforms = new Array();
  64842. _this._samplers = new Array();
  64843. _this._textures = {};
  64844. _this._floats = {};
  64845. _this._floatsArrays = {};
  64846. _this._colors3 = {};
  64847. _this._colors4 = {};
  64848. _this._vectors2 = {};
  64849. _this._vectors3 = {};
  64850. _this._matrices = {};
  64851. _this._fallbackTextureUsed = false;
  64852. scene._proceduralTextures.push(_this);
  64853. _this._engine = scene.getEngine();
  64854. _this.name = name;
  64855. _this.isRenderTarget = true;
  64856. _this._size = size;
  64857. _this._generateMipMaps = generateMipMaps;
  64858. _this.setFragment(fragment);
  64859. _this._fallbackTexture = fallbackTexture;
  64860. if (isCube) {
  64861. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64862. _this.setFloat("face", 0);
  64863. }
  64864. else {
  64865. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64866. }
  64867. // VBO
  64868. var vertices = [];
  64869. vertices.push(1, 1);
  64870. vertices.push(-1, 1);
  64871. vertices.push(-1, -1);
  64872. vertices.push(1, -1);
  64873. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64874. _this._createIndexBuffer();
  64875. return _this;
  64876. }
  64877. ProceduralTexture.prototype._createIndexBuffer = function () {
  64878. var engine = this._engine;
  64879. // Indices
  64880. var indices = [];
  64881. indices.push(0);
  64882. indices.push(1);
  64883. indices.push(2);
  64884. indices.push(0);
  64885. indices.push(2);
  64886. indices.push(3);
  64887. this._indexBuffer = engine.createIndexBuffer(indices);
  64888. };
  64889. ProceduralTexture.prototype._rebuild = function () {
  64890. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64891. if (vb) {
  64892. vb._rebuild();
  64893. }
  64894. this._createIndexBuffer();
  64895. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64896. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64897. }
  64898. };
  64899. ProceduralTexture.prototype.reset = function () {
  64900. if (this._effect === undefined) {
  64901. return;
  64902. }
  64903. var engine = this._engine;
  64904. engine._releaseEffect(this._effect);
  64905. };
  64906. ProceduralTexture.prototype.isReady = function () {
  64907. var _this = this;
  64908. var engine = this._engine;
  64909. var shaders;
  64910. if (!this._fragment) {
  64911. return false;
  64912. }
  64913. if (this._fallbackTextureUsed) {
  64914. return true;
  64915. }
  64916. if (this._fragment.fragmentElement !== undefined) {
  64917. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64918. }
  64919. else {
  64920. shaders = { vertex: "procedural", fragment: this._fragment };
  64921. }
  64922. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64923. _this.releaseInternalTexture();
  64924. if (_this._fallbackTexture) {
  64925. _this._texture = _this._fallbackTexture._texture;
  64926. if (_this._texture) {
  64927. _this._texture.incrementReferences();
  64928. }
  64929. }
  64930. _this._fallbackTextureUsed = true;
  64931. });
  64932. return this._effect.isReady();
  64933. };
  64934. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64935. this._currentRefreshId = -1;
  64936. };
  64937. ProceduralTexture.prototype.setFragment = function (fragment) {
  64938. this._fragment = fragment;
  64939. };
  64940. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64941. get: function () {
  64942. return this._refreshRate;
  64943. },
  64944. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64945. set: function (value) {
  64946. this._refreshRate = value;
  64947. this.resetRefreshCounter();
  64948. },
  64949. enumerable: true,
  64950. configurable: true
  64951. });
  64952. ProceduralTexture.prototype._shouldRender = function () {
  64953. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64954. return false;
  64955. }
  64956. if (this._fallbackTextureUsed) {
  64957. return false;
  64958. }
  64959. if (this._currentRefreshId === -1) {
  64960. this._currentRefreshId = 1;
  64961. return true;
  64962. }
  64963. if (this.refreshRate === this._currentRefreshId) {
  64964. this._currentRefreshId = 1;
  64965. return true;
  64966. }
  64967. this._currentRefreshId++;
  64968. return false;
  64969. };
  64970. ProceduralTexture.prototype.getRenderSize = function () {
  64971. return this._size;
  64972. };
  64973. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64974. if (this._fallbackTextureUsed) {
  64975. return;
  64976. }
  64977. this.releaseInternalTexture();
  64978. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64979. };
  64980. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64981. if (this._uniforms.indexOf(uniformName) === -1) {
  64982. this._uniforms.push(uniformName);
  64983. }
  64984. };
  64985. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64986. if (this._samplers.indexOf(name) === -1) {
  64987. this._samplers.push(name);
  64988. }
  64989. this._textures[name] = texture;
  64990. return this;
  64991. };
  64992. ProceduralTexture.prototype.setFloat = function (name, value) {
  64993. this._checkUniform(name);
  64994. this._floats[name] = value;
  64995. return this;
  64996. };
  64997. ProceduralTexture.prototype.setFloats = function (name, value) {
  64998. this._checkUniform(name);
  64999. this._floatsArrays[name] = value;
  65000. return this;
  65001. };
  65002. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65003. this._checkUniform(name);
  65004. this._colors3[name] = value;
  65005. return this;
  65006. };
  65007. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65008. this._checkUniform(name);
  65009. this._colors4[name] = value;
  65010. return this;
  65011. };
  65012. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65013. this._checkUniform(name);
  65014. this._vectors2[name] = value;
  65015. return this;
  65016. };
  65017. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65018. this._checkUniform(name);
  65019. this._vectors3[name] = value;
  65020. return this;
  65021. };
  65022. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65023. this._checkUniform(name);
  65024. this._matrices[name] = value;
  65025. return this;
  65026. };
  65027. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65028. var scene = this.getScene();
  65029. if (!scene) {
  65030. return;
  65031. }
  65032. var engine = this._engine;
  65033. // Render
  65034. engine.enableEffect(this._effect);
  65035. engine.setState(false);
  65036. // Texture
  65037. for (var name in this._textures) {
  65038. this._effect.setTexture(name, this._textures[name]);
  65039. }
  65040. // Float
  65041. for (name in this._floats) {
  65042. this._effect.setFloat(name, this._floats[name]);
  65043. }
  65044. // Floats
  65045. for (name in this._floatsArrays) {
  65046. this._effect.setArray(name, this._floatsArrays[name]);
  65047. }
  65048. // Color3
  65049. for (name in this._colors3) {
  65050. this._effect.setColor3(name, this._colors3[name]);
  65051. }
  65052. // Color4
  65053. for (name in this._colors4) {
  65054. var color = this._colors4[name];
  65055. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65056. }
  65057. // Vector2
  65058. for (name in this._vectors2) {
  65059. this._effect.setVector2(name, this._vectors2[name]);
  65060. }
  65061. // Vector3
  65062. for (name in this._vectors3) {
  65063. this._effect.setVector3(name, this._vectors3[name]);
  65064. }
  65065. // Matrix
  65066. for (name in this._matrices) {
  65067. this._effect.setMatrix(name, this._matrices[name]);
  65068. }
  65069. if (!this._texture) {
  65070. return;
  65071. }
  65072. if (this.isCube) {
  65073. for (var face = 0; face < 6; face++) {
  65074. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65075. // VBOs
  65076. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65077. this._effect.setFloat("face", face);
  65078. // Clear
  65079. engine.clear(scene.clearColor, true, true, true);
  65080. // Draw order
  65081. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65082. // Mipmaps
  65083. if (face === 5) {
  65084. engine.generateMipMapsForCubemap(this._texture);
  65085. }
  65086. }
  65087. }
  65088. else {
  65089. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65090. // VBOs
  65091. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65092. // Clear
  65093. engine.clear(scene.clearColor, true, true, true);
  65094. // Draw order
  65095. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65096. }
  65097. // Unbind
  65098. engine.unBindFramebuffer(this._texture, this.isCube);
  65099. if (this.onGenerated) {
  65100. this.onGenerated();
  65101. }
  65102. };
  65103. ProceduralTexture.prototype.clone = function () {
  65104. var textureSize = this.getSize();
  65105. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65106. // Base texture
  65107. newTexture.hasAlpha = this.hasAlpha;
  65108. newTexture.level = this.level;
  65109. // RenderTarget Texture
  65110. newTexture.coordinatesMode = this.coordinatesMode;
  65111. return newTexture;
  65112. };
  65113. ProceduralTexture.prototype.dispose = function () {
  65114. var scene = this.getScene();
  65115. if (!scene) {
  65116. return;
  65117. }
  65118. var index = scene._proceduralTextures.indexOf(this);
  65119. if (index >= 0) {
  65120. scene._proceduralTextures.splice(index, 1);
  65121. }
  65122. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65123. if (vertexBuffer) {
  65124. vertexBuffer.dispose();
  65125. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65126. }
  65127. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65128. this._indexBuffer = null;
  65129. }
  65130. _super.prototype.dispose.call(this);
  65131. };
  65132. return ProceduralTexture;
  65133. }(BABYLON.Texture));
  65134. BABYLON.ProceduralTexture = ProceduralTexture;
  65135. })(BABYLON || (BABYLON = {}));
  65136. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65137. var BABYLON;
  65138. (function (BABYLON) {
  65139. var CustomProceduralTexture = /** @class */ (function (_super) {
  65140. __extends(CustomProceduralTexture, _super);
  65141. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65142. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65143. _this._animate = true;
  65144. _this._time = 0;
  65145. _this._texturePath = texturePath;
  65146. //Try to load json
  65147. _this.loadJson(texturePath);
  65148. _this.refreshRate = 1;
  65149. return _this;
  65150. }
  65151. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65152. var _this = this;
  65153. var noConfigFile = function () {
  65154. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65155. try {
  65156. _this.setFragment(_this._texturePath);
  65157. }
  65158. catch (ex) {
  65159. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65160. }
  65161. };
  65162. var configFileUrl = jsonUrl + "/config.json";
  65163. var xhr = new XMLHttpRequest();
  65164. xhr.open("GET", configFileUrl, true);
  65165. xhr.addEventListener("load", function () {
  65166. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65167. try {
  65168. _this._config = JSON.parse(xhr.response);
  65169. _this.updateShaderUniforms();
  65170. _this.updateTextures();
  65171. _this.setFragment(_this._texturePath + "/custom");
  65172. _this._animate = _this._config.animate;
  65173. _this.refreshRate = _this._config.refreshrate;
  65174. }
  65175. catch (ex) {
  65176. noConfigFile();
  65177. }
  65178. }
  65179. else {
  65180. noConfigFile();
  65181. }
  65182. }, false);
  65183. xhr.addEventListener("error", function () {
  65184. noConfigFile();
  65185. }, false);
  65186. try {
  65187. xhr.send();
  65188. }
  65189. catch (ex) {
  65190. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65191. }
  65192. };
  65193. CustomProceduralTexture.prototype.isReady = function () {
  65194. if (!_super.prototype.isReady.call(this)) {
  65195. return false;
  65196. }
  65197. for (var name in this._textures) {
  65198. var texture = this._textures[name];
  65199. if (!texture.isReady()) {
  65200. return false;
  65201. }
  65202. }
  65203. return true;
  65204. };
  65205. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65206. var scene = this.getScene();
  65207. if (this._animate && scene) {
  65208. this._time += scene.getAnimationRatio() * 0.03;
  65209. this.updateShaderUniforms();
  65210. }
  65211. _super.prototype.render.call(this, useCameraPostProcess);
  65212. };
  65213. CustomProceduralTexture.prototype.updateTextures = function () {
  65214. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65215. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65216. }
  65217. };
  65218. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65219. if (this._config) {
  65220. for (var j = 0; j < this._config.uniforms.length; j++) {
  65221. var uniform = this._config.uniforms[j];
  65222. switch (uniform.type) {
  65223. case "float":
  65224. this.setFloat(uniform.name, uniform.value);
  65225. break;
  65226. case "color3":
  65227. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65228. break;
  65229. case "color4":
  65230. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65231. break;
  65232. case "vector2":
  65233. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65234. break;
  65235. case "vector3":
  65236. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65237. break;
  65238. }
  65239. }
  65240. }
  65241. this.setFloat("time", this._time);
  65242. };
  65243. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65244. get: function () {
  65245. return this._animate;
  65246. },
  65247. set: function (value) {
  65248. this._animate = value;
  65249. },
  65250. enumerable: true,
  65251. configurable: true
  65252. });
  65253. return CustomProceduralTexture;
  65254. }(BABYLON.ProceduralTexture));
  65255. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65256. })(BABYLON || (BABYLON = {}));
  65257. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65258. var BABYLON;
  65259. (function (BABYLON) {
  65260. var FreeCameraGamepadInput = /** @class */ (function () {
  65261. function FreeCameraGamepadInput() {
  65262. this.gamepadAngularSensibility = 200;
  65263. this.gamepadMoveSensibility = 40;
  65264. // private members
  65265. this._cameraTransform = BABYLON.Matrix.Identity();
  65266. this._deltaTransform = BABYLON.Vector3.Zero();
  65267. this._vector3 = BABYLON.Vector3.Zero();
  65268. this._vector2 = BABYLON.Vector2.Zero();
  65269. }
  65270. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65271. var _this = this;
  65272. var manager = this.camera.getScene().gamepadManager;
  65273. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65274. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65275. // prioritize XBOX gamepads.
  65276. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65277. _this.gamepad = gamepad;
  65278. }
  65279. }
  65280. });
  65281. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65282. if (_this.gamepad === gamepad) {
  65283. _this.gamepad = null;
  65284. }
  65285. });
  65286. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65287. };
  65288. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65289. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65290. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65291. this.gamepad = null;
  65292. };
  65293. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65294. if (this.gamepad && this.gamepad.leftStick) {
  65295. var camera = this.camera;
  65296. var LSValues = this.gamepad.leftStick;
  65297. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65298. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65299. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65300. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65301. var RSValues = this.gamepad.rightStick;
  65302. if (RSValues) {
  65303. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65304. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65305. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65306. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65307. }
  65308. else {
  65309. RSValues = { x: 0, y: 0 };
  65310. }
  65311. if (!camera.rotationQuaternion) {
  65312. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65313. }
  65314. else {
  65315. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65316. }
  65317. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65318. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65319. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65320. camera.cameraDirection.addInPlace(this._deltaTransform);
  65321. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65322. camera.cameraRotation.addInPlace(this._vector2);
  65323. }
  65324. };
  65325. FreeCameraGamepadInput.prototype.getClassName = function () {
  65326. return "FreeCameraGamepadInput";
  65327. };
  65328. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65329. return "gamepad";
  65330. };
  65331. __decorate([
  65332. BABYLON.serialize()
  65333. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65334. __decorate([
  65335. BABYLON.serialize()
  65336. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65337. return FreeCameraGamepadInput;
  65338. }());
  65339. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65340. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65341. })(BABYLON || (BABYLON = {}));
  65342. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65343. var BABYLON;
  65344. (function (BABYLON) {
  65345. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65346. function ArcRotateCameraGamepadInput() {
  65347. this.gamepadRotationSensibility = 80;
  65348. this.gamepadMoveSensibility = 40;
  65349. }
  65350. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65351. var _this = this;
  65352. var manager = this.camera.getScene().gamepadManager;
  65353. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65354. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65355. // prioritize XBOX gamepads.
  65356. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65357. _this.gamepad = gamepad;
  65358. }
  65359. }
  65360. });
  65361. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65362. if (_this.gamepad === gamepad) {
  65363. _this.gamepad = null;
  65364. }
  65365. });
  65366. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65367. };
  65368. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65369. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65370. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65371. this.gamepad = null;
  65372. };
  65373. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65374. if (this.gamepad) {
  65375. var camera = this.camera;
  65376. var RSValues = this.gamepad.rightStick;
  65377. if (RSValues) {
  65378. if (RSValues.x != 0) {
  65379. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65380. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65381. camera.inertialAlphaOffset += normalizedRX;
  65382. }
  65383. }
  65384. if (RSValues.y != 0) {
  65385. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65386. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65387. camera.inertialBetaOffset += normalizedRY;
  65388. }
  65389. }
  65390. }
  65391. var LSValues = this.gamepad.leftStick;
  65392. if (LSValues && LSValues.y != 0) {
  65393. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65394. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65395. this.camera.inertialRadiusOffset -= normalizedLY;
  65396. }
  65397. }
  65398. }
  65399. };
  65400. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65401. return "ArcRotateCameraGamepadInput";
  65402. };
  65403. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65404. return "gamepad";
  65405. };
  65406. __decorate([
  65407. BABYLON.serialize()
  65408. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65409. __decorate([
  65410. BABYLON.serialize()
  65411. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65412. return ArcRotateCameraGamepadInput;
  65413. }());
  65414. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65415. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65416. })(BABYLON || (BABYLON = {}));
  65417. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65418. var BABYLON;
  65419. (function (BABYLON) {
  65420. var GamepadManager = /** @class */ (function () {
  65421. function GamepadManager(_scene) {
  65422. var _this = this;
  65423. this._scene = _scene;
  65424. this._babylonGamepads = [];
  65425. this._oneGamepadConnected = false;
  65426. this._isMonitoring = false;
  65427. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65428. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65429. this._gamepadEventSupported = false;
  65430. }
  65431. else {
  65432. this._gamepadEventSupported = 'GamepadEvent' in window;
  65433. this._gamepadSupport = (navigator.getGamepads ||
  65434. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65435. }
  65436. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65437. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65438. for (var i in _this._babylonGamepads) {
  65439. var gamepad = _this._babylonGamepads[i];
  65440. if (gamepad && gamepad._isConnected) {
  65441. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65442. }
  65443. }
  65444. });
  65445. this._onGamepadConnectedEvent = function (evt) {
  65446. var gamepad = evt.gamepad;
  65447. if (gamepad.index in _this._babylonGamepads) {
  65448. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65449. return;
  65450. }
  65451. }
  65452. var newGamepad;
  65453. if (_this._babylonGamepads[gamepad.index]) {
  65454. newGamepad = _this._babylonGamepads[gamepad.index];
  65455. newGamepad.browserGamepad = gamepad;
  65456. newGamepad._isConnected = true;
  65457. }
  65458. else {
  65459. newGamepad = _this._addNewGamepad(gamepad);
  65460. }
  65461. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65462. _this._startMonitoringGamepads();
  65463. };
  65464. this._onGamepadDisconnectedEvent = function (evt) {
  65465. var gamepad = evt.gamepad;
  65466. // Remove the gamepad from the list of gamepads to monitor.
  65467. for (var i in _this._babylonGamepads) {
  65468. if (_this._babylonGamepads[i].index === gamepad.index) {
  65469. var disconnectedGamepad = _this._babylonGamepads[i];
  65470. disconnectedGamepad._isConnected = false;
  65471. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65472. break;
  65473. }
  65474. }
  65475. };
  65476. if (this._gamepadSupport) {
  65477. //first add already-connected gamepads
  65478. this._updateGamepadObjects();
  65479. if (this._babylonGamepads.length) {
  65480. this._startMonitoringGamepads();
  65481. }
  65482. // Checking if the gamepad connected event is supported (like in Firefox)
  65483. if (this._gamepadEventSupported) {
  65484. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65485. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65486. }
  65487. else {
  65488. this._startMonitoringGamepads();
  65489. }
  65490. }
  65491. }
  65492. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65493. get: function () {
  65494. return this._babylonGamepads;
  65495. },
  65496. enumerable: true,
  65497. configurable: true
  65498. });
  65499. GamepadManager.prototype.getGamepadByType = function (type) {
  65500. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65501. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65502. var gamepad = _a[_i];
  65503. if (gamepad && gamepad.type === type) {
  65504. return gamepad;
  65505. }
  65506. }
  65507. return null;
  65508. };
  65509. GamepadManager.prototype.dispose = function () {
  65510. if (this._gamepadEventSupported) {
  65511. if (this._onGamepadConnectedEvent) {
  65512. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65513. }
  65514. if (this._onGamepadDisconnectedEvent) {
  65515. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65516. }
  65517. this._onGamepadConnectedEvent = null;
  65518. this._onGamepadDisconnectedEvent = null;
  65519. }
  65520. this._babylonGamepads.forEach(function (gamepad) {
  65521. gamepad.dispose();
  65522. });
  65523. this.onGamepadConnectedObservable.clear();
  65524. this.onGamepadDisconnectedObservable.clear();
  65525. this._oneGamepadConnected = false;
  65526. this._stopMonitoringGamepads();
  65527. this._babylonGamepads = [];
  65528. };
  65529. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  65530. if (!this._oneGamepadConnected) {
  65531. this._oneGamepadConnected = true;
  65532. }
  65533. var newGamepad;
  65534. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  65535. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  65536. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65537. }
  65538. else if (gamepad.pose) {
  65539. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65540. }
  65541. else {
  65542. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65543. }
  65544. this._babylonGamepads[newGamepad.index] = newGamepad;
  65545. return newGamepad;
  65546. };
  65547. GamepadManager.prototype._startMonitoringGamepads = function () {
  65548. if (!this._isMonitoring) {
  65549. this._isMonitoring = true;
  65550. //back-comp
  65551. if (!this._scene) {
  65552. this._checkGamepadsStatus();
  65553. }
  65554. }
  65555. };
  65556. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65557. this._isMonitoring = false;
  65558. };
  65559. GamepadManager.prototype._checkGamepadsStatus = function () {
  65560. var _this = this;
  65561. // Hack to be compatible Chrome
  65562. this._updateGamepadObjects();
  65563. for (var i in this._babylonGamepads) {
  65564. var gamepad = this._babylonGamepads[i];
  65565. if (!gamepad || !gamepad.isConnected) {
  65566. continue;
  65567. }
  65568. gamepad.update();
  65569. }
  65570. if (this._isMonitoring && !this._scene) {
  65571. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65572. }
  65573. };
  65574. // This function is called only on Chrome, which does not properly support
  65575. // connection/disconnection events and forces you to recopy again the gamepad object
  65576. GamepadManager.prototype._updateGamepadObjects = function () {
  65577. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65578. for (var i = 0; i < gamepads.length; i++) {
  65579. if (gamepads[i]) {
  65580. if (!this._babylonGamepads[gamepads[i].index]) {
  65581. var newGamepad = this._addNewGamepad(gamepads[i]);
  65582. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65583. }
  65584. else {
  65585. // Forced to copy again this object for Chrome for unknown reason
  65586. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65587. if (!this._babylonGamepads[i].isConnected) {
  65588. this._babylonGamepads[i]._isConnected = true;
  65589. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65590. }
  65591. }
  65592. }
  65593. }
  65594. };
  65595. return GamepadManager;
  65596. }());
  65597. BABYLON.GamepadManager = GamepadManager;
  65598. })(BABYLON || (BABYLON = {}));
  65599. //# sourceMappingURL=babylon.gamepadManager.js.map
  65600. var BABYLON;
  65601. (function (BABYLON) {
  65602. var StickValues = /** @class */ (function () {
  65603. function StickValues(x, y) {
  65604. this.x = x;
  65605. this.y = y;
  65606. }
  65607. return StickValues;
  65608. }());
  65609. BABYLON.StickValues = StickValues;
  65610. var Gamepad = /** @class */ (function () {
  65611. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65612. if (leftStickX === void 0) { leftStickX = 0; }
  65613. if (leftStickY === void 0) { leftStickY = 1; }
  65614. if (rightStickX === void 0) { rightStickX = 2; }
  65615. if (rightStickY === void 0) { rightStickY = 3; }
  65616. this.id = id;
  65617. this.index = index;
  65618. this.browserGamepad = browserGamepad;
  65619. this._isConnected = true;
  65620. this._invertLeftStickY = false;
  65621. this.type = Gamepad.GAMEPAD;
  65622. this._leftStickAxisX = leftStickX;
  65623. this._leftStickAxisY = leftStickY;
  65624. this._rightStickAxisX = rightStickX;
  65625. this._rightStickAxisY = rightStickY;
  65626. if (this.browserGamepad.axes.length >= 2) {
  65627. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65628. }
  65629. if (this.browserGamepad.axes.length >= 4) {
  65630. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65631. }
  65632. }
  65633. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65634. get: function () {
  65635. return this._isConnected;
  65636. },
  65637. enumerable: true,
  65638. configurable: true
  65639. });
  65640. Gamepad.prototype.onleftstickchanged = function (callback) {
  65641. this._onleftstickchanged = callback;
  65642. };
  65643. Gamepad.prototype.onrightstickchanged = function (callback) {
  65644. this._onrightstickchanged = callback;
  65645. };
  65646. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65647. get: function () {
  65648. return this._leftStick;
  65649. },
  65650. set: function (newValues) {
  65651. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65652. this._onleftstickchanged(newValues);
  65653. }
  65654. this._leftStick = newValues;
  65655. },
  65656. enumerable: true,
  65657. configurable: true
  65658. });
  65659. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65660. get: function () {
  65661. return this._rightStick;
  65662. },
  65663. set: function (newValues) {
  65664. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65665. this._onrightstickchanged(newValues);
  65666. }
  65667. this._rightStick = newValues;
  65668. },
  65669. enumerable: true,
  65670. configurable: true
  65671. });
  65672. Gamepad.prototype.update = function () {
  65673. if (this._leftStick) {
  65674. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65675. if (this._invertLeftStickY) {
  65676. this.leftStick.y *= -1;
  65677. }
  65678. }
  65679. if (this._rightStick) {
  65680. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65681. }
  65682. };
  65683. Gamepad.prototype.dispose = function () {
  65684. };
  65685. Gamepad.GAMEPAD = 0;
  65686. Gamepad.GENERIC = 1;
  65687. Gamepad.XBOX = 2;
  65688. Gamepad.POSE_ENABLED = 3;
  65689. return Gamepad;
  65690. }());
  65691. BABYLON.Gamepad = Gamepad;
  65692. var GenericPad = /** @class */ (function (_super) {
  65693. __extends(GenericPad, _super);
  65694. function GenericPad(id, index, browserGamepad) {
  65695. var _this = _super.call(this, id, index, browserGamepad) || this;
  65696. _this.onButtonDownObservable = new BABYLON.Observable();
  65697. _this.onButtonUpObservable = new BABYLON.Observable();
  65698. _this.type = Gamepad.GENERIC;
  65699. _this._buttons = new Array(browserGamepad.buttons.length);
  65700. return _this;
  65701. }
  65702. GenericPad.prototype.onbuttondown = function (callback) {
  65703. this._onbuttondown = callback;
  65704. };
  65705. GenericPad.prototype.onbuttonup = function (callback) {
  65706. this._onbuttonup = callback;
  65707. };
  65708. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65709. if (newValue !== currentValue) {
  65710. if (newValue === 1) {
  65711. if (this._onbuttondown) {
  65712. this._onbuttondown(buttonIndex);
  65713. }
  65714. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65715. }
  65716. if (newValue === 0) {
  65717. if (this._onbuttonup) {
  65718. this._onbuttonup(buttonIndex);
  65719. }
  65720. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65721. }
  65722. }
  65723. return newValue;
  65724. };
  65725. GenericPad.prototype.update = function () {
  65726. _super.prototype.update.call(this);
  65727. for (var index = 0; index < this._buttons.length; index++) {
  65728. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65729. }
  65730. };
  65731. GenericPad.prototype.dispose = function () {
  65732. _super.prototype.dispose.call(this);
  65733. this.onButtonDownObservable.clear();
  65734. this.onButtonUpObservable.clear();
  65735. };
  65736. return GenericPad;
  65737. }(Gamepad));
  65738. BABYLON.GenericPad = GenericPad;
  65739. })(BABYLON || (BABYLON = {}));
  65740. //# sourceMappingURL=babylon.gamepad.js.map
  65741. var BABYLON;
  65742. (function (BABYLON) {
  65743. var Xbox360Button;
  65744. (function (Xbox360Button) {
  65745. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65746. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65747. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65748. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65749. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65750. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65751. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65752. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65753. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65754. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65755. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65756. var Xbox360Dpad;
  65757. (function (Xbox360Dpad) {
  65758. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65759. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65760. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65761. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65762. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65763. var Xbox360Pad = /** @class */ (function (_super) {
  65764. __extends(Xbox360Pad, _super);
  65765. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65766. if (xboxOne === void 0) { xboxOne = false; }
  65767. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65768. _this._leftTrigger = 0;
  65769. _this._rightTrigger = 0;
  65770. _this.onButtonDownObservable = new BABYLON.Observable();
  65771. _this.onButtonUpObservable = new BABYLON.Observable();
  65772. _this.onPadDownObservable = new BABYLON.Observable();
  65773. _this.onPadUpObservable = new BABYLON.Observable();
  65774. _this._buttonA = 0;
  65775. _this._buttonB = 0;
  65776. _this._buttonX = 0;
  65777. _this._buttonY = 0;
  65778. _this._buttonBack = 0;
  65779. _this._buttonStart = 0;
  65780. _this._buttonLB = 0;
  65781. _this._buttonRB = 0;
  65782. _this._buttonLeftStick = 0;
  65783. _this._buttonRightStick = 0;
  65784. _this._dPadUp = 0;
  65785. _this._dPadDown = 0;
  65786. _this._dPadLeft = 0;
  65787. _this._dPadRight = 0;
  65788. _this._isXboxOnePad = false;
  65789. _this.type = BABYLON.Gamepad.XBOX;
  65790. _this._isXboxOnePad = xboxOne;
  65791. return _this;
  65792. }
  65793. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65794. this._onlefttriggerchanged = callback;
  65795. };
  65796. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65797. this._onrighttriggerchanged = callback;
  65798. };
  65799. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65800. get: function () {
  65801. return this._leftTrigger;
  65802. },
  65803. set: function (newValue) {
  65804. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65805. this._onlefttriggerchanged(newValue);
  65806. }
  65807. this._leftTrigger = newValue;
  65808. },
  65809. enumerable: true,
  65810. configurable: true
  65811. });
  65812. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65813. get: function () {
  65814. return this._rightTrigger;
  65815. },
  65816. set: function (newValue) {
  65817. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65818. this._onrighttriggerchanged(newValue);
  65819. }
  65820. this._rightTrigger = newValue;
  65821. },
  65822. enumerable: true,
  65823. configurable: true
  65824. });
  65825. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65826. this._onbuttondown = callback;
  65827. };
  65828. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65829. this._onbuttonup = callback;
  65830. };
  65831. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65832. this._ondpaddown = callback;
  65833. };
  65834. Xbox360Pad.prototype.ondpadup = function (callback) {
  65835. this._ondpadup = callback;
  65836. };
  65837. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65838. if (newValue !== currentValue) {
  65839. if (newValue === 1) {
  65840. if (this._onbuttondown) {
  65841. this._onbuttondown(buttonType);
  65842. }
  65843. this.onButtonDownObservable.notifyObservers(buttonType);
  65844. }
  65845. if (newValue === 0) {
  65846. if (this._onbuttonup) {
  65847. this._onbuttonup(buttonType);
  65848. }
  65849. this.onButtonUpObservable.notifyObservers(buttonType);
  65850. }
  65851. }
  65852. return newValue;
  65853. };
  65854. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65855. if (newValue !== currentValue) {
  65856. if (newValue === 1) {
  65857. if (this._ondpaddown) {
  65858. this._ondpaddown(buttonType);
  65859. }
  65860. this.onPadDownObservable.notifyObservers(buttonType);
  65861. }
  65862. if (newValue === 0) {
  65863. if (this._ondpadup) {
  65864. this._ondpadup(buttonType);
  65865. }
  65866. this.onPadUpObservable.notifyObservers(buttonType);
  65867. }
  65868. }
  65869. return newValue;
  65870. };
  65871. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65872. get: function () {
  65873. return this._buttonA;
  65874. },
  65875. set: function (value) {
  65876. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65877. },
  65878. enumerable: true,
  65879. configurable: true
  65880. });
  65881. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65882. get: function () {
  65883. return this._buttonB;
  65884. },
  65885. set: function (value) {
  65886. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65887. },
  65888. enumerable: true,
  65889. configurable: true
  65890. });
  65891. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65892. get: function () {
  65893. return this._buttonX;
  65894. },
  65895. set: function (value) {
  65896. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65897. },
  65898. enumerable: true,
  65899. configurable: true
  65900. });
  65901. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65902. get: function () {
  65903. return this._buttonY;
  65904. },
  65905. set: function (value) {
  65906. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65907. },
  65908. enumerable: true,
  65909. configurable: true
  65910. });
  65911. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65912. get: function () {
  65913. return this._buttonStart;
  65914. },
  65915. set: function (value) {
  65916. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65917. },
  65918. enumerable: true,
  65919. configurable: true
  65920. });
  65921. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65922. get: function () {
  65923. return this._buttonBack;
  65924. },
  65925. set: function (value) {
  65926. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65927. },
  65928. enumerable: true,
  65929. configurable: true
  65930. });
  65931. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65932. get: function () {
  65933. return this._buttonLB;
  65934. },
  65935. set: function (value) {
  65936. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65937. },
  65938. enumerable: true,
  65939. configurable: true
  65940. });
  65941. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65942. get: function () {
  65943. return this._buttonRB;
  65944. },
  65945. set: function (value) {
  65946. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65947. },
  65948. enumerable: true,
  65949. configurable: true
  65950. });
  65951. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65952. get: function () {
  65953. return this._buttonLeftStick;
  65954. },
  65955. set: function (value) {
  65956. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65957. },
  65958. enumerable: true,
  65959. configurable: true
  65960. });
  65961. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65962. get: function () {
  65963. return this._buttonRightStick;
  65964. },
  65965. set: function (value) {
  65966. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65967. },
  65968. enumerable: true,
  65969. configurable: true
  65970. });
  65971. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65972. get: function () {
  65973. return this._dPadUp;
  65974. },
  65975. set: function (value) {
  65976. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65977. },
  65978. enumerable: true,
  65979. configurable: true
  65980. });
  65981. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65982. get: function () {
  65983. return this._dPadDown;
  65984. },
  65985. set: function (value) {
  65986. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65987. },
  65988. enumerable: true,
  65989. configurable: true
  65990. });
  65991. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65992. get: function () {
  65993. return this._dPadLeft;
  65994. },
  65995. set: function (value) {
  65996. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65997. },
  65998. enumerable: true,
  65999. configurable: true
  66000. });
  66001. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66002. get: function () {
  66003. return this._dPadRight;
  66004. },
  66005. set: function (value) {
  66006. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66007. },
  66008. enumerable: true,
  66009. configurable: true
  66010. });
  66011. Xbox360Pad.prototype.update = function () {
  66012. _super.prototype.update.call(this);
  66013. if (this._isXboxOnePad) {
  66014. this.buttonA = this.browserGamepad.buttons[0].value;
  66015. this.buttonB = this.browserGamepad.buttons[1].value;
  66016. this.buttonX = this.browserGamepad.buttons[2].value;
  66017. this.buttonY = this.browserGamepad.buttons[3].value;
  66018. this.buttonLB = this.browserGamepad.buttons[4].value;
  66019. this.buttonRB = this.browserGamepad.buttons[5].value;
  66020. this.leftTrigger = this.browserGamepad.axes[2];
  66021. this.rightTrigger = this.browserGamepad.axes[5];
  66022. this.buttonBack = this.browserGamepad.buttons[9].value;
  66023. this.buttonStart = this.browserGamepad.buttons[8].value;
  66024. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66025. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66026. this.dPadUp = this.browserGamepad.buttons[11].value;
  66027. this.dPadDown = this.browserGamepad.buttons[12].value;
  66028. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66029. this.dPadRight = this.browserGamepad.buttons[14].value;
  66030. }
  66031. else {
  66032. this.buttonA = this.browserGamepad.buttons[0].value;
  66033. this.buttonB = this.browserGamepad.buttons[1].value;
  66034. this.buttonX = this.browserGamepad.buttons[2].value;
  66035. this.buttonY = this.browserGamepad.buttons[3].value;
  66036. this.buttonLB = this.browserGamepad.buttons[4].value;
  66037. this.buttonRB = this.browserGamepad.buttons[5].value;
  66038. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66039. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66040. this.buttonBack = this.browserGamepad.buttons[8].value;
  66041. this.buttonStart = this.browserGamepad.buttons[9].value;
  66042. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66043. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66044. this.dPadUp = this.browserGamepad.buttons[12].value;
  66045. this.dPadDown = this.browserGamepad.buttons[13].value;
  66046. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66047. this.dPadRight = this.browserGamepad.buttons[15].value;
  66048. }
  66049. };
  66050. Xbox360Pad.prototype.dispose = function () {
  66051. _super.prototype.dispose.call(this);
  66052. this.onButtonDownObservable.clear();
  66053. this.onButtonUpObservable.clear();
  66054. this.onPadDownObservable.clear();
  66055. this.onPadUpObservable.clear();
  66056. };
  66057. return Xbox360Pad;
  66058. }(BABYLON.Gamepad));
  66059. BABYLON.Xbox360Pad = Xbox360Pad;
  66060. })(BABYLON || (BABYLON = {}));
  66061. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66062. var BABYLON;
  66063. (function (BABYLON) {
  66064. var PoseEnabledControllerType;
  66065. (function (PoseEnabledControllerType) {
  66066. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66067. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66068. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66069. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66070. /**
  66071. * Google Daydream
  66072. */
  66073. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66074. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66075. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66076. var PoseEnabledControllerHelper = /** @class */ (function () {
  66077. function PoseEnabledControllerHelper() {
  66078. }
  66079. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66080. // Oculus Touch
  66081. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66082. return new BABYLON.OculusTouchController(vrGamepad);
  66083. }
  66084. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66085. return new BABYLON.WindowsMotionController(vrGamepad);
  66086. }
  66087. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66088. return new BABYLON.ViveController(vrGamepad);
  66089. }
  66090. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66091. return new BABYLON.GearVRController(vrGamepad);
  66092. }
  66093. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66094. return new BABYLON.DaydreamController(vrGamepad);
  66095. }
  66096. else {
  66097. return new BABYLON.GenericController(vrGamepad);
  66098. }
  66099. };
  66100. return PoseEnabledControllerHelper;
  66101. }());
  66102. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66103. var PoseEnabledController = /** @class */ (function (_super) {
  66104. __extends(PoseEnabledController, _super);
  66105. function PoseEnabledController(browserGamepad) {
  66106. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66107. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66108. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66109. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66110. // Represents device position and rotation in babylon space
  66111. _this.devicePosition = BABYLON.Vector3.Zero();
  66112. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66113. _this.deviceScaleFactor = 1;
  66114. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66115. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66116. /**
  66117. * Node to be used when casting a ray from the controller
  66118. */
  66119. _this._pointingPoseNode = null;
  66120. _this._workingMatrix = BABYLON.Matrix.Identity();
  66121. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66122. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66123. _this.position = BABYLON.Vector3.Zero();
  66124. _this.rotationQuaternion = new BABYLON.Quaternion();
  66125. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66126. _this._calculatedRotation = new BABYLON.Quaternion();
  66127. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66128. return _this;
  66129. }
  66130. PoseEnabledController.prototype.update = function () {
  66131. _super.prototype.update.call(this);
  66132. var pose = this.browserGamepad.pose;
  66133. this.updateFromDevice(pose);
  66134. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66135. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66136. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66137. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66138. if (this._mesh) {
  66139. this._mesh.position.copyFrom(this.devicePosition);
  66140. if (this._mesh.rotationQuaternion) {
  66141. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66142. }
  66143. }
  66144. };
  66145. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66146. if (poseData) {
  66147. this.rawPose = poseData;
  66148. if (poseData.position) {
  66149. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66150. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66151. this._deviceRoomPosition.z *= -1;
  66152. }
  66153. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66154. this._calculatedPosition.addInPlace(this.position);
  66155. }
  66156. var pose = this.rawPose;
  66157. if (poseData.orientation && pose.orientation) {
  66158. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66159. if (this._mesh) {
  66160. if (this._mesh.getScene().useRightHandedSystem) {
  66161. this._deviceRoomRotationQuaternion.z *= -1;
  66162. this._deviceRoomRotationQuaternion.w *= -1;
  66163. }
  66164. else {
  66165. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66166. }
  66167. }
  66168. // if the camera is set, rotate to the camera's rotation
  66169. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66170. }
  66171. }
  66172. };
  66173. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66174. if (this._mesh) {
  66175. this._mesh.parent = null;
  66176. }
  66177. this._mesh = mesh;
  66178. if (this._poseControlledCamera) {
  66179. this._mesh.parent = this._poseControlledCamera;
  66180. }
  66181. if (!this._mesh.rotationQuaternion) {
  66182. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66183. }
  66184. };
  66185. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66186. this._poseControlledCamera = camera;
  66187. if (this._mesh) {
  66188. this._mesh.parent = this._poseControlledCamera;
  66189. }
  66190. };
  66191. PoseEnabledController.prototype.dispose = function () {
  66192. if (this._mesh) {
  66193. this._mesh.dispose();
  66194. }
  66195. this._mesh = null;
  66196. _super.prototype.dispose.call(this);
  66197. };
  66198. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66199. get: function () {
  66200. return this._mesh;
  66201. },
  66202. enumerable: true,
  66203. configurable: true
  66204. });
  66205. PoseEnabledController.prototype.getForwardRay = function (length) {
  66206. if (length === void 0) { length = 100; }
  66207. if (!this.mesh) {
  66208. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66209. }
  66210. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66211. var origin = m.getTranslation();
  66212. var forward = new BABYLON.Vector3(0, 0, -1);
  66213. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66214. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66215. return new BABYLON.Ray(origin, direction, length);
  66216. };
  66217. /**
  66218. * Name of the child mesh that can be used to cast a ray from the controller
  66219. */
  66220. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66221. return PoseEnabledController;
  66222. }(BABYLON.Gamepad));
  66223. BABYLON.PoseEnabledController = PoseEnabledController;
  66224. })(BABYLON || (BABYLON = {}));
  66225. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66226. var BABYLON;
  66227. (function (BABYLON) {
  66228. var WebVRController = /** @class */ (function (_super) {
  66229. __extends(WebVRController, _super);
  66230. function WebVRController(vrGamepad) {
  66231. var _this = _super.call(this, vrGamepad) || this;
  66232. // Observables
  66233. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66234. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66235. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66236. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66237. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66238. _this.pad = { x: 0, y: 0 };
  66239. // avoid GC, store state in a tmp object
  66240. _this._changes = {
  66241. pressChanged: false,
  66242. touchChanged: false,
  66243. valueChanged: false,
  66244. changed: false
  66245. };
  66246. _this._buttons = new Array(vrGamepad.buttons.length);
  66247. _this.hand = vrGamepad.hand;
  66248. return _this;
  66249. }
  66250. WebVRController.prototype.onButtonStateChange = function (callback) {
  66251. this._onButtonStateChange = callback;
  66252. };
  66253. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66254. get: function () {
  66255. return this._defaultModel;
  66256. },
  66257. enumerable: true,
  66258. configurable: true
  66259. });
  66260. WebVRController.prototype.update = function () {
  66261. _super.prototype.update.call(this);
  66262. for (var index = 0; index < this._buttons.length; index++) {
  66263. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66264. }
  66265. ;
  66266. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66267. this.pad.x = this.leftStick.x;
  66268. this.pad.y = this.leftStick.y;
  66269. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66270. }
  66271. };
  66272. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66273. if (!newState) {
  66274. newState = {
  66275. pressed: false,
  66276. touched: false,
  66277. value: 0
  66278. };
  66279. }
  66280. if (!currentState) {
  66281. this._buttons[buttonIndex] = {
  66282. pressed: newState.pressed,
  66283. touched: newState.touched,
  66284. value: newState.value
  66285. };
  66286. return;
  66287. }
  66288. this._checkChanges(newState, currentState);
  66289. if (this._changes.changed) {
  66290. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66291. this._handleButtonChange(buttonIndex, newState, this._changes);
  66292. }
  66293. this._buttons[buttonIndex].pressed = newState.pressed;
  66294. this._buttons[buttonIndex].touched = newState.touched;
  66295. // oculus triggers are never 0, thou not touched.
  66296. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66297. };
  66298. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66299. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66300. this._changes.touchChanged = newState.touched !== currentState.touched;
  66301. this._changes.valueChanged = newState.value !== currentState.value;
  66302. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66303. return this._changes;
  66304. };
  66305. WebVRController.prototype.dispose = function () {
  66306. _super.prototype.dispose.call(this);
  66307. this.onTriggerStateChangedObservable.clear();
  66308. this.onMainButtonStateChangedObservable.clear();
  66309. this.onSecondaryButtonStateChangedObservable.clear();
  66310. this.onPadStateChangedObservable.clear();
  66311. this.onPadValuesChangedObservable.clear();
  66312. };
  66313. return WebVRController;
  66314. }(BABYLON.PoseEnabledController));
  66315. BABYLON.WebVRController = WebVRController;
  66316. })(BABYLON || (BABYLON = {}));
  66317. //# sourceMappingURL=babylon.webVRController.js.map
  66318. var BABYLON;
  66319. (function (BABYLON) {
  66320. var OculusTouchController = /** @class */ (function (_super) {
  66321. __extends(OculusTouchController, _super);
  66322. function OculusTouchController(vrGamepad) {
  66323. var _this = _super.call(this, vrGamepad) || this;
  66324. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66325. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66326. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66327. return _this;
  66328. }
  66329. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66330. var _this = this;
  66331. var meshName;
  66332. // Hand
  66333. if (this.hand === 'left') {
  66334. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66335. }
  66336. else {
  66337. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66338. }
  66339. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66340. /*
  66341. Parent Mesh name: oculus_touch_left
  66342. - body
  66343. - trigger
  66344. - thumbstick
  66345. - grip
  66346. - button_y
  66347. - button_x
  66348. - button_enter
  66349. */
  66350. _this._defaultModel = newMeshes[1];
  66351. _this.attachToMesh(_this._defaultModel);
  66352. if (meshLoaded) {
  66353. meshLoaded(_this._defaultModel);
  66354. }
  66355. });
  66356. };
  66357. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66358. // helper getters for left and right hand.
  66359. get: function () {
  66360. if (this.hand === 'right') {
  66361. return this.onMainButtonStateChangedObservable;
  66362. }
  66363. else {
  66364. throw new Error('No A button on left hand');
  66365. }
  66366. },
  66367. enumerable: true,
  66368. configurable: true
  66369. });
  66370. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66371. get: function () {
  66372. if (this.hand === 'right') {
  66373. return this.onSecondaryButtonStateChangedObservable;
  66374. }
  66375. else {
  66376. throw new Error('No B button on left hand');
  66377. }
  66378. },
  66379. enumerable: true,
  66380. configurable: true
  66381. });
  66382. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66383. get: function () {
  66384. if (this.hand === 'left') {
  66385. return this.onMainButtonStateChangedObservable;
  66386. }
  66387. else {
  66388. throw new Error('No X button on right hand');
  66389. }
  66390. },
  66391. enumerable: true,
  66392. configurable: true
  66393. });
  66394. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66395. get: function () {
  66396. if (this.hand === 'left') {
  66397. return this.onSecondaryButtonStateChangedObservable;
  66398. }
  66399. else {
  66400. throw new Error('No Y button on right hand');
  66401. }
  66402. },
  66403. enumerable: true,
  66404. configurable: true
  66405. });
  66406. /*
  66407. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66408. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66409. 2) secondary trigger (same)
  66410. 3) A (right) X (left), touch, pressed = value
  66411. 4) B / Y
  66412. 5) thumb rest
  66413. */
  66414. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66415. var notifyObject = state; //{ state: state, changes: changes };
  66416. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66417. switch (buttonIdx) {
  66418. case 0:
  66419. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66420. return;
  66421. case 1:// index trigger
  66422. if (this._defaultModel) {
  66423. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66424. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66425. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66426. }
  66427. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66428. return;
  66429. case 2:// secondary trigger
  66430. if (this._defaultModel) {
  66431. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66432. }
  66433. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66434. return;
  66435. case 3:
  66436. if (this._defaultModel) {
  66437. if (notifyObject.pressed) {
  66438. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66439. }
  66440. else {
  66441. (this._defaultModel.getChildren()[1]).position.y = 0;
  66442. }
  66443. }
  66444. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66445. return;
  66446. case 4:
  66447. if (this._defaultModel) {
  66448. if (notifyObject.pressed) {
  66449. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66450. }
  66451. else {
  66452. (this._defaultModel.getChildren()[2]).position.y = 0;
  66453. }
  66454. }
  66455. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66456. return;
  66457. case 5:
  66458. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66459. return;
  66460. }
  66461. };
  66462. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66463. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66464. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66465. return OculusTouchController;
  66466. }(BABYLON.WebVRController));
  66467. BABYLON.OculusTouchController = OculusTouchController;
  66468. })(BABYLON || (BABYLON = {}));
  66469. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66470. var BABYLON;
  66471. (function (BABYLON) {
  66472. var ViveController = /** @class */ (function (_super) {
  66473. __extends(ViveController, _super);
  66474. function ViveController(vrGamepad) {
  66475. var _this = _super.call(this, vrGamepad) || this;
  66476. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66477. _this._invertLeftStickY = true;
  66478. return _this;
  66479. }
  66480. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66481. var _this = this;
  66482. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66483. /*
  66484. Parent Mesh name: ViveWand
  66485. - body
  66486. - r_gripper
  66487. - l_gripper
  66488. - menu_button
  66489. - system_button
  66490. - trackpad
  66491. - trigger
  66492. - LED
  66493. */
  66494. _this._defaultModel = newMeshes[1];
  66495. _this.attachToMesh(_this._defaultModel);
  66496. if (meshLoaded) {
  66497. meshLoaded(_this._defaultModel);
  66498. }
  66499. });
  66500. };
  66501. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66502. get: function () {
  66503. return this.onMainButtonStateChangedObservable;
  66504. },
  66505. enumerable: true,
  66506. configurable: true
  66507. });
  66508. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66509. get: function () {
  66510. return this.onMainButtonStateChangedObservable;
  66511. },
  66512. enumerable: true,
  66513. configurable: true
  66514. });
  66515. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66516. get: function () {
  66517. return this.onSecondaryButtonStateChangedObservable;
  66518. },
  66519. enumerable: true,
  66520. configurable: true
  66521. });
  66522. /**
  66523. * Vive mapping:
  66524. * 0: touchpad
  66525. * 1: trigger
  66526. * 2: left AND right buttons
  66527. * 3: menu button
  66528. */
  66529. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66530. var notifyObject = state; //{ state: state, changes: changes };
  66531. switch (buttonIdx) {
  66532. case 0:
  66533. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66534. return;
  66535. case 1:// index trigger
  66536. if (this._defaultModel) {
  66537. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66538. }
  66539. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66540. return;
  66541. case 2:// left AND right button
  66542. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66543. return;
  66544. case 3:
  66545. if (this._defaultModel) {
  66546. if (notifyObject.pressed) {
  66547. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66548. }
  66549. else {
  66550. (this._defaultModel.getChildren()[2]).position.y = 0;
  66551. }
  66552. }
  66553. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66554. return;
  66555. }
  66556. };
  66557. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66558. ViveController.MODEL_FILENAME = 'wand.babylon';
  66559. return ViveController;
  66560. }(BABYLON.WebVRController));
  66561. BABYLON.ViveController = ViveController;
  66562. })(BABYLON || (BABYLON = {}));
  66563. //# sourceMappingURL=babylon.viveController.js.map
  66564. var BABYLON;
  66565. (function (BABYLON) {
  66566. var GenericController = /** @class */ (function (_super) {
  66567. __extends(GenericController, _super);
  66568. function GenericController(vrGamepad) {
  66569. return _super.call(this, vrGamepad) || this;
  66570. }
  66571. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66572. var _this = this;
  66573. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66574. _this._defaultModel = newMeshes[1];
  66575. _this.attachToMesh(_this._defaultModel);
  66576. if (meshLoaded) {
  66577. meshLoaded(_this._defaultModel);
  66578. }
  66579. });
  66580. };
  66581. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66582. console.log("Button id: " + buttonIdx + "state: ");
  66583. console.dir(state);
  66584. };
  66585. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66586. GenericController.MODEL_FILENAME = 'generic.babylon';
  66587. return GenericController;
  66588. }(BABYLON.WebVRController));
  66589. BABYLON.GenericController = GenericController;
  66590. })(BABYLON || (BABYLON = {}));
  66591. //# sourceMappingURL=babylon.genericController.js.map
  66592. var BABYLON;
  66593. (function (BABYLON) {
  66594. var LoadedMeshInfo = /** @class */ (function () {
  66595. function LoadedMeshInfo() {
  66596. this.buttonMeshes = {};
  66597. this.axisMeshes = {};
  66598. }
  66599. return LoadedMeshInfo;
  66600. }());
  66601. var WindowsMotionController = /** @class */ (function (_super) {
  66602. __extends(WindowsMotionController, _super);
  66603. function WindowsMotionController(vrGamepad) {
  66604. var _this = _super.call(this, vrGamepad) || this;
  66605. _this._mapping = {
  66606. // Semantic button names
  66607. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66608. // A mapping of the button name to glTF model node name
  66609. // that should be transformed by button value.
  66610. buttonMeshNames: {
  66611. 'trigger': 'SELECT',
  66612. 'menu': 'MENU',
  66613. 'grip': 'GRASP',
  66614. 'thumbstick': 'THUMBSTICK_PRESS',
  66615. 'trackpad': 'TOUCHPAD_PRESS'
  66616. },
  66617. // This mapping is used to translate from the Motion Controller to Babylon semantics
  66618. buttonObservableNames: {
  66619. 'trigger': 'onTriggerStateChangedObservable',
  66620. 'menu': 'onSecondaryButtonStateChangedObservable',
  66621. 'grip': 'onMainButtonStateChangedObservable',
  66622. 'thumbstick': 'onPadStateChangedObservable',
  66623. 'trackpad': 'onTrackpadChangedObservable'
  66624. },
  66625. // A mapping of the axis name to glTF model node name
  66626. // that should be transformed by axis value.
  66627. // This array mirrors the browserGamepad.axes array, such that
  66628. // the mesh corresponding to axis 0 is in this array index 0.
  66629. axisMeshNames: [
  66630. 'THUMBSTICK_X',
  66631. 'THUMBSTICK_Y',
  66632. 'TOUCHPAD_TOUCH_X',
  66633. 'TOUCHPAD_TOUCH_Y'
  66634. ],
  66635. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66636. };
  66637. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66638. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66639. _this.trackpad = { x: 0, y: 0 };
  66640. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66641. _this._loadedMeshInfo = null;
  66642. return _this;
  66643. }
  66644. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66645. get: function () {
  66646. return this.onTriggerStateChangedObservable;
  66647. },
  66648. enumerable: true,
  66649. configurable: true
  66650. });
  66651. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66652. get: function () {
  66653. return this.onSecondaryButtonStateChangedObservable;
  66654. },
  66655. enumerable: true,
  66656. configurable: true
  66657. });
  66658. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66659. get: function () {
  66660. return this.onMainButtonStateChangedObservable;
  66661. },
  66662. enumerable: true,
  66663. configurable: true
  66664. });
  66665. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66666. get: function () {
  66667. return this.onPadStateChangedObservable;
  66668. },
  66669. enumerable: true,
  66670. configurable: true
  66671. });
  66672. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66673. get: function () {
  66674. return this.onTrackpadChangedObservable;
  66675. },
  66676. enumerable: true,
  66677. configurable: true
  66678. });
  66679. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66680. get: function () {
  66681. return this.onTrackpadValuesChangedObservable;
  66682. },
  66683. enumerable: true,
  66684. configurable: true
  66685. });
  66686. /**
  66687. * Called once per frame by the engine.
  66688. */
  66689. WindowsMotionController.prototype.update = function () {
  66690. _super.prototype.update.call(this);
  66691. if (this.browserGamepad.axes) {
  66692. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66693. this.trackpad.x = this.browserGamepad["axes"][2];
  66694. this.trackpad.y = this.browserGamepad["axes"][3];
  66695. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66696. }
  66697. // Only need to animate axes if there is a loaded mesh
  66698. if (this._loadedMeshInfo) {
  66699. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66700. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66701. }
  66702. }
  66703. }
  66704. };
  66705. /**
  66706. * Called once for each button that changed state since the last frame
  66707. * @param buttonIdx Which button index changed
  66708. * @param state New state of the button
  66709. * @param changes Which properties on the state changed since last frame
  66710. */
  66711. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66712. var buttonName = this._mapping.buttons[buttonIdx];
  66713. if (!buttonName) {
  66714. return;
  66715. }
  66716. // Only emit events for buttons that we know how to map from index to name
  66717. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66718. if (observable) {
  66719. observable.notifyObservers(state);
  66720. }
  66721. this.lerpButtonTransform(buttonName, state.value);
  66722. };
  66723. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66724. // If there is no loaded mesh, there is nothing to transform.
  66725. if (!this._loadedMeshInfo) {
  66726. return;
  66727. }
  66728. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66729. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66730. return;
  66731. }
  66732. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66733. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66734. };
  66735. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66736. if (!this._loadedMeshInfo) {
  66737. return;
  66738. }
  66739. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66740. if (!meshInfo) {
  66741. return;
  66742. }
  66743. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66744. return;
  66745. }
  66746. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66747. var lerpValue = axisValue * 0.5 + 0.5;
  66748. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66749. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66750. };
  66751. /**
  66752. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66753. * @param scene scene in which to add meshes
  66754. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66755. */
  66756. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66757. var _this = this;
  66758. if (forceDefault === void 0) { forceDefault = false; }
  66759. var path;
  66760. var filename;
  66761. // Checking if GLB loader is present
  66762. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66763. // Determine the device specific folder based on the ID suffix
  66764. var device = 'default';
  66765. if (this.id && !forceDefault) {
  66766. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66767. device = ((match && match[0]) || device);
  66768. }
  66769. // Hand
  66770. if (this.hand === 'left') {
  66771. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66772. }
  66773. else {
  66774. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66775. }
  66776. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66777. }
  66778. else {
  66779. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66780. path = BABYLON.GenericController.MODEL_BASE_URL;
  66781. filename = BABYLON.GenericController.MODEL_FILENAME;
  66782. }
  66783. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66784. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66785. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66786. if (!_this._loadedMeshInfo) {
  66787. return;
  66788. }
  66789. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66790. _this.attachToMesh(_this._defaultModel);
  66791. if (meshLoaded) {
  66792. meshLoaded(_this._defaultModel);
  66793. }
  66794. }, null, function (scene, message) {
  66795. BABYLON.Tools.Log(message);
  66796. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66797. if (!forceDefault) {
  66798. _this.initControllerMesh(scene, meshLoaded, true);
  66799. }
  66800. });
  66801. };
  66802. /**
  66803. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66804. * can be transformed by button presses and axes values, based on this._mapping.
  66805. *
  66806. * @param scene scene in which the meshes exist
  66807. * @param meshes list of meshes that make up the controller model to process
  66808. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66809. */
  66810. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66811. var loadedMeshInfo = null;
  66812. // Create a new mesh to contain the glTF hierarchy
  66813. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66814. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66815. var childMesh = null;
  66816. for (var i = 0; i < meshes.length; i++) {
  66817. var mesh = meshes[i];
  66818. if (!mesh.parent) {
  66819. // Exclude controller meshes from picking results
  66820. mesh.isPickable = false;
  66821. // Handle root node, attach to the new parentMesh
  66822. childMesh = mesh;
  66823. break;
  66824. }
  66825. }
  66826. if (childMesh) {
  66827. childMesh.setParent(parentMesh);
  66828. // Create our mesh info. Note that this method will always return non-null.
  66829. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66830. }
  66831. else {
  66832. BABYLON.Tools.Warn('Could not find root node in model file.');
  66833. }
  66834. return loadedMeshInfo;
  66835. };
  66836. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66837. var loadedMeshInfo = new LoadedMeshInfo();
  66838. var i;
  66839. loadedMeshInfo.rootNode = rootNode;
  66840. // Reset the caches
  66841. loadedMeshInfo.buttonMeshes = {};
  66842. loadedMeshInfo.axisMeshes = {};
  66843. // Button Meshes
  66844. for (i = 0; i < this._mapping.buttons.length; i++) {
  66845. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66846. if (!buttonMeshName) {
  66847. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66848. continue;
  66849. }
  66850. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66851. if (!buttonMesh) {
  66852. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66853. continue;
  66854. }
  66855. var buttonMeshInfo = {
  66856. index: i,
  66857. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66858. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66859. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66860. };
  66861. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66862. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66863. }
  66864. else {
  66865. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66866. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66867. '(VALUE: ' + !!buttonMeshInfo.value +
  66868. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66869. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66870. ')');
  66871. }
  66872. }
  66873. // Axis Meshes
  66874. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66875. var axisMeshName = this._mapping.axisMeshNames[i];
  66876. if (!axisMeshName) {
  66877. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66878. continue;
  66879. }
  66880. var axisMesh = getChildByName(rootNode, axisMeshName);
  66881. if (!axisMesh) {
  66882. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66883. continue;
  66884. }
  66885. var axisMeshInfo = {
  66886. index: i,
  66887. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66888. min: getImmediateChildByName(axisMesh, 'MIN'),
  66889. max: getImmediateChildByName(axisMesh, 'MAX')
  66890. };
  66891. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66892. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66893. }
  66894. else {
  66895. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66896. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66897. '(VALUE: ' + !!axisMeshInfo.value +
  66898. ', MIN: ' + !!axisMeshInfo.min +
  66899. ', MAX:' + !!axisMeshInfo.max +
  66900. ')');
  66901. }
  66902. }
  66903. // Pointing Ray
  66904. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66905. if (!loadedMeshInfo.pointingPoseNode) {
  66906. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66907. }
  66908. return loadedMeshInfo;
  66909. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66910. function getChildByName(node, name) {
  66911. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66912. }
  66913. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66914. function getImmediateChildByName(node, name) {
  66915. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66916. }
  66917. };
  66918. WindowsMotionController.prototype.getForwardRay = function (length) {
  66919. if (length === void 0) { length = 100; }
  66920. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66921. return _super.prototype.getForwardRay.call(this, length);
  66922. }
  66923. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66924. var origin = m.getTranslation();
  66925. var forward = new BABYLON.Vector3(0, 0, -1);
  66926. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66927. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66928. return new BABYLON.Ray(origin, direction, length);
  66929. };
  66930. WindowsMotionController.prototype.dispose = function () {
  66931. _super.prototype.dispose.call(this);
  66932. this.onTrackpadChangedObservable.clear();
  66933. };
  66934. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66935. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66936. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66937. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66938. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66939. return WindowsMotionController;
  66940. }(BABYLON.WebVRController));
  66941. BABYLON.WindowsMotionController = WindowsMotionController;
  66942. })(BABYLON || (BABYLON = {}));
  66943. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66944. var BABYLON;
  66945. (function (BABYLON) {
  66946. var GearVRController = /** @class */ (function (_super) {
  66947. __extends(GearVRController, _super);
  66948. function GearVRController(vrGamepad) {
  66949. var _this = _super.call(this, vrGamepad) || this;
  66950. _this._buttonIndexToObservableNameMap = [
  66951. 'onTrackpadChangedObservable',
  66952. 'onTriggerStateChangedObservable' // Trigger
  66953. ];
  66954. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66955. return _this;
  66956. }
  66957. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66958. var _this = this;
  66959. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66960. _this._defaultModel = newMeshes[1];
  66961. _this.attachToMesh(_this._defaultModel);
  66962. if (meshLoaded) {
  66963. meshLoaded(_this._defaultModel);
  66964. }
  66965. });
  66966. };
  66967. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66968. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66969. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66970. // Only emit events for buttons that we know how to map from index to observable
  66971. var observable = this[observableName];
  66972. if (observable) {
  66973. observable.notifyObservers(state);
  66974. }
  66975. }
  66976. };
  66977. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66978. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66979. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66980. return GearVRController;
  66981. }(BABYLON.WebVRController));
  66982. BABYLON.GearVRController = GearVRController;
  66983. })(BABYLON || (BABYLON = {}));
  66984. //# sourceMappingURL=babylon.gearVRController.js.map
  66985. var BABYLON;
  66986. (function (BABYLON) {
  66987. /**
  66988. * Google Daydream controller
  66989. */
  66990. var DaydreamController = /** @class */ (function (_super) {
  66991. __extends(DaydreamController, _super);
  66992. function DaydreamController(vrGamepad) {
  66993. var _this = _super.call(this, vrGamepad) || this;
  66994. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66995. return _this;
  66996. }
  66997. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66998. var _this = this;
  66999. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67000. _this._defaultModel = newMeshes[1];
  67001. _this.attachToMesh(_this._defaultModel);
  67002. if (meshLoaded) {
  67003. meshLoaded(_this._defaultModel);
  67004. }
  67005. });
  67006. };
  67007. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67008. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67009. if (buttonIdx === 0) {
  67010. var observable = this.onTriggerStateChangedObservable;
  67011. if (observable) {
  67012. observable.notifyObservers(state);
  67013. }
  67014. }
  67015. else {
  67016. // If the app or home buttons are ever made available
  67017. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67018. }
  67019. };
  67020. /**
  67021. * Base Url for the controller model.
  67022. */
  67023. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67024. /**
  67025. * File name for the controller model.
  67026. */
  67027. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67028. /**
  67029. * Gamepad Id prefix used to identify Daydream Controller.
  67030. */
  67031. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67032. return DaydreamController;
  67033. }(BABYLON.WebVRController));
  67034. BABYLON.DaydreamController = DaydreamController;
  67035. })(BABYLON || (BABYLON = {}));
  67036. //# sourceMappingURL=babylon.daydreamController.js.map
  67037. var BABYLON;
  67038. (function (BABYLON) {
  67039. var FollowCamera = /** @class */ (function (_super) {
  67040. __extends(FollowCamera, _super);
  67041. function FollowCamera(name, position, scene, lockedTarget) {
  67042. if (lockedTarget === void 0) { lockedTarget = null; }
  67043. var _this = _super.call(this, name, position, scene) || this;
  67044. _this.radius = 12;
  67045. _this.rotationOffset = 0;
  67046. _this.heightOffset = 4;
  67047. _this.cameraAcceleration = 0.05;
  67048. _this.maxCameraSpeed = 20;
  67049. _this.lockedTarget = lockedTarget;
  67050. return _this;
  67051. }
  67052. FollowCamera.prototype.getRadians = function (degrees) {
  67053. return degrees * Math.PI / 180;
  67054. };
  67055. FollowCamera.prototype.follow = function (cameraTarget) {
  67056. if (!cameraTarget)
  67057. return;
  67058. var yRotation;
  67059. if (cameraTarget.rotationQuaternion) {
  67060. var rotMatrix = new BABYLON.Matrix();
  67061. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67062. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67063. }
  67064. else {
  67065. yRotation = cameraTarget.rotation.y;
  67066. }
  67067. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67068. var targetPosition = cameraTarget.getAbsolutePosition();
  67069. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67070. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67071. var dx = targetX - this.position.x;
  67072. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67073. var dz = (targetZ) - this.position.z;
  67074. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67075. var vy = dy * this.cameraAcceleration;
  67076. var vz = dz * this.cameraAcceleration * 2;
  67077. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67078. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67079. }
  67080. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67081. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67082. }
  67083. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67084. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67085. }
  67086. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67087. this.setTarget(targetPosition);
  67088. };
  67089. FollowCamera.prototype._checkInputs = function () {
  67090. _super.prototype._checkInputs.call(this);
  67091. if (this.lockedTarget) {
  67092. this.follow(this.lockedTarget);
  67093. }
  67094. };
  67095. FollowCamera.prototype.getClassName = function () {
  67096. return "FollowCamera";
  67097. };
  67098. __decorate([
  67099. BABYLON.serialize()
  67100. ], FollowCamera.prototype, "radius", void 0);
  67101. __decorate([
  67102. BABYLON.serialize()
  67103. ], FollowCamera.prototype, "rotationOffset", void 0);
  67104. __decorate([
  67105. BABYLON.serialize()
  67106. ], FollowCamera.prototype, "heightOffset", void 0);
  67107. __decorate([
  67108. BABYLON.serialize()
  67109. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67110. __decorate([
  67111. BABYLON.serialize()
  67112. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67113. __decorate([
  67114. BABYLON.serializeAsMeshReference("lockedTargetId")
  67115. ], FollowCamera.prototype, "lockedTarget", void 0);
  67116. return FollowCamera;
  67117. }(BABYLON.TargetCamera));
  67118. BABYLON.FollowCamera = FollowCamera;
  67119. var ArcFollowCamera = /** @class */ (function (_super) {
  67120. __extends(ArcFollowCamera, _super);
  67121. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67122. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67123. _this.alpha = alpha;
  67124. _this.beta = beta;
  67125. _this.radius = radius;
  67126. _this.target = target;
  67127. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67128. _this.follow();
  67129. return _this;
  67130. }
  67131. ArcFollowCamera.prototype.follow = function () {
  67132. if (!this.target) {
  67133. return;
  67134. }
  67135. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67136. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67137. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67138. var targetPosition = this.target.getAbsolutePosition();
  67139. this.position = targetPosition.add(this._cartesianCoordinates);
  67140. this.setTarget(targetPosition);
  67141. };
  67142. ArcFollowCamera.prototype._checkInputs = function () {
  67143. _super.prototype._checkInputs.call(this);
  67144. this.follow();
  67145. };
  67146. ArcFollowCamera.prototype.getClassName = function () {
  67147. return "ArcFollowCamera";
  67148. };
  67149. return ArcFollowCamera;
  67150. }(BABYLON.TargetCamera));
  67151. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67152. })(BABYLON || (BABYLON = {}));
  67153. //# sourceMappingURL=babylon.followCamera.js.map
  67154. var BABYLON;
  67155. (function (BABYLON) {
  67156. // We're mainly based on the logic defined into the FreeCamera code
  67157. var UniversalCamera = /** @class */ (function (_super) {
  67158. __extends(UniversalCamera, _super);
  67159. //-- end properties for backward compatibility for inputs
  67160. function UniversalCamera(name, position, scene) {
  67161. var _this = _super.call(this, name, position, scene) || this;
  67162. _this.inputs.addGamepad();
  67163. return _this;
  67164. }
  67165. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67166. //-- Begin properties for backward compatibility for inputs
  67167. get: function () {
  67168. var gamepad = this.inputs.attached["gamepad"];
  67169. if (gamepad)
  67170. return gamepad.gamepadAngularSensibility;
  67171. return 0;
  67172. },
  67173. set: function (value) {
  67174. var gamepad = this.inputs.attached["gamepad"];
  67175. if (gamepad)
  67176. gamepad.gamepadAngularSensibility = value;
  67177. },
  67178. enumerable: true,
  67179. configurable: true
  67180. });
  67181. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67182. get: function () {
  67183. var gamepad = this.inputs.attached["gamepad"];
  67184. if (gamepad)
  67185. return gamepad.gamepadMoveSensibility;
  67186. return 0;
  67187. },
  67188. set: function (value) {
  67189. var gamepad = this.inputs.attached["gamepad"];
  67190. if (gamepad)
  67191. gamepad.gamepadMoveSensibility = value;
  67192. },
  67193. enumerable: true,
  67194. configurable: true
  67195. });
  67196. UniversalCamera.prototype.getClassName = function () {
  67197. return "UniversalCamera";
  67198. };
  67199. return UniversalCamera;
  67200. }(BABYLON.TouchCamera));
  67201. BABYLON.UniversalCamera = UniversalCamera;
  67202. })(BABYLON || (BABYLON = {}));
  67203. //# sourceMappingURL=babylon.universalCamera.js.map
  67204. var BABYLON;
  67205. (function (BABYLON) {
  67206. // We're mainly based on the logic defined into the FreeCamera code
  67207. var GamepadCamera = /** @class */ (function (_super) {
  67208. __extends(GamepadCamera, _super);
  67209. //-- end properties for backward compatibility for inputs
  67210. function GamepadCamera(name, position, scene) {
  67211. return _super.call(this, name, position, scene) || this;
  67212. }
  67213. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67214. //-- Begin properties for backward compatibility for inputs
  67215. get: function () {
  67216. var gamepad = this.inputs.attached["gamepad"];
  67217. if (gamepad)
  67218. return gamepad.gamepadAngularSensibility;
  67219. return 0;
  67220. },
  67221. set: function (value) {
  67222. var gamepad = this.inputs.attached["gamepad"];
  67223. if (gamepad)
  67224. gamepad.gamepadAngularSensibility = value;
  67225. },
  67226. enumerable: true,
  67227. configurable: true
  67228. });
  67229. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67230. get: function () {
  67231. var gamepad = this.inputs.attached["gamepad"];
  67232. if (gamepad)
  67233. return gamepad.gamepadMoveSensibility;
  67234. return 0;
  67235. },
  67236. set: function (value) {
  67237. var gamepad = this.inputs.attached["gamepad"];
  67238. if (gamepad)
  67239. gamepad.gamepadMoveSensibility = value;
  67240. },
  67241. enumerable: true,
  67242. configurable: true
  67243. });
  67244. GamepadCamera.prototype.getClassName = function () {
  67245. return "GamepadCamera";
  67246. };
  67247. return GamepadCamera;
  67248. }(BABYLON.UniversalCamera));
  67249. BABYLON.GamepadCamera = GamepadCamera;
  67250. })(BABYLON || (BABYLON = {}));
  67251. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67252. var BABYLON;
  67253. (function (BABYLON) {
  67254. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67255. function PostProcessRenderPipelineManager() {
  67256. this._renderPipelines = {};
  67257. }
  67258. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67259. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67260. };
  67261. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67262. if (unique === void 0) { unique = false; }
  67263. var renderPipeline = this._renderPipelines[renderPipelineName];
  67264. if (!renderPipeline) {
  67265. return;
  67266. }
  67267. renderPipeline._attachCameras(cameras, unique);
  67268. };
  67269. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67270. var renderPipeline = this._renderPipelines[renderPipelineName];
  67271. if (!renderPipeline) {
  67272. return;
  67273. }
  67274. renderPipeline._detachCameras(cameras);
  67275. };
  67276. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67277. var renderPipeline = this._renderPipelines[renderPipelineName];
  67278. if (!renderPipeline) {
  67279. return;
  67280. }
  67281. renderPipeline._enableEffect(renderEffectName, cameras);
  67282. };
  67283. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67284. var renderPipeline = this._renderPipelines[renderPipelineName];
  67285. if (!renderPipeline) {
  67286. return;
  67287. }
  67288. renderPipeline._disableEffect(renderEffectName, cameras);
  67289. };
  67290. PostProcessRenderPipelineManager.prototype.update = function () {
  67291. for (var renderPipelineName in this._renderPipelines) {
  67292. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67293. var pipeline = this._renderPipelines[renderPipelineName];
  67294. if (!pipeline.isSupported) {
  67295. pipeline.dispose();
  67296. delete this._renderPipelines[renderPipelineName];
  67297. }
  67298. else {
  67299. pipeline._update();
  67300. }
  67301. }
  67302. }
  67303. };
  67304. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67305. for (var renderPipelineName in this._renderPipelines) {
  67306. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67307. var pipeline = this._renderPipelines[renderPipelineName];
  67308. pipeline._rebuild();
  67309. }
  67310. }
  67311. };
  67312. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67313. for (var renderPipelineName in this._renderPipelines) {
  67314. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67315. var pipeline = this._renderPipelines[renderPipelineName];
  67316. pipeline.dispose();
  67317. }
  67318. }
  67319. };
  67320. return PostProcessRenderPipelineManager;
  67321. }());
  67322. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67323. })(BABYLON || (BABYLON = {}));
  67324. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67325. var BABYLON;
  67326. (function (BABYLON) {
  67327. /**
  67328. * This represents a set of one or more post processes in Babylon.
  67329. * A post process can be used to apply a shader to a texture after it is rendered.
  67330. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67331. */
  67332. var PostProcessRenderEffect = /** @class */ (function () {
  67333. /**
  67334. * Instantiates a post process render effect.
  67335. * A post process can be used to apply a shader to a texture after it is rendered.
  67336. * @param engine The engine the effect is tied to
  67337. * @param name The name of the effect
  67338. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67339. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67340. */
  67341. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67342. this._name = name;
  67343. this._singleInstance = singleInstance || true;
  67344. this._getPostProcesses = getPostProcesses;
  67345. this._cameras = {};
  67346. this._indicesForCamera = {};
  67347. this._postProcesses = {};
  67348. }
  67349. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67350. /**
  67351. * Checks if all the post processes in the effect are supported.
  67352. */
  67353. get: function () {
  67354. for (var index in this._postProcesses) {
  67355. for (var ppIndex in this._postProcesses[index]) {
  67356. if (!this._postProcesses[index][ppIndex].isSupported) {
  67357. return false;
  67358. }
  67359. }
  67360. }
  67361. return true;
  67362. },
  67363. enumerable: true,
  67364. configurable: true
  67365. });
  67366. /**
  67367. * Updates the current state of the effect
  67368. */
  67369. PostProcessRenderEffect.prototype._update = function () {
  67370. };
  67371. /**
  67372. * Attaches the effect on cameras
  67373. * @param cameras The camera to attach to.
  67374. */
  67375. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67376. var _this = this;
  67377. var cameraKey;
  67378. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67379. if (!cams) {
  67380. return;
  67381. }
  67382. for (var i = 0; i < cams.length; i++) {
  67383. var camera = cams[i];
  67384. var cameraName = camera.name;
  67385. if (this._singleInstance) {
  67386. cameraKey = 0;
  67387. }
  67388. else {
  67389. cameraKey = cameraName;
  67390. }
  67391. if (!this._postProcesses[cameraKey]) {
  67392. var postProcess = this._getPostProcesses();
  67393. if (postProcess) {
  67394. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67395. }
  67396. }
  67397. if (!this._indicesForCamera[cameraName]) {
  67398. this._indicesForCamera[cameraName] = [];
  67399. }
  67400. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67401. var index = camera.attachPostProcess(postProcess);
  67402. _this._indicesForCamera[cameraName].push(index);
  67403. });
  67404. if (!this._cameras[cameraName]) {
  67405. this._cameras[cameraName] = camera;
  67406. }
  67407. }
  67408. };
  67409. /**
  67410. * Detatches the effect on cameras
  67411. * @param cameras The camera to detatch from.
  67412. */
  67413. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67414. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67415. if (!cams) {
  67416. return;
  67417. }
  67418. for (var i = 0; i < cams.length; i++) {
  67419. var camera = cams[i];
  67420. var cameraName = camera.name;
  67421. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67422. camera.detachPostProcess(postProcess);
  67423. });
  67424. if (this._cameras[cameraName]) {
  67425. //this._indicesForCamera.splice(index, 1);
  67426. this._cameras[cameraName] = null;
  67427. }
  67428. }
  67429. };
  67430. /**
  67431. * Enables the effect on given cameras
  67432. * @param cameras The camera to enable.
  67433. */
  67434. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67435. var _this = this;
  67436. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67437. if (!cams) {
  67438. return;
  67439. }
  67440. for (var i = 0; i < cams.length; i++) {
  67441. var camera = cams[i];
  67442. var cameraName = camera.name;
  67443. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67444. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67445. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67446. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67447. });
  67448. }
  67449. }
  67450. }
  67451. };
  67452. /**
  67453. * Disables the effect on the given cameras
  67454. * @param cameras The camera to disable.
  67455. */
  67456. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67457. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67458. if (!cams) {
  67459. return;
  67460. }
  67461. for (var i = 0; i < cams.length; i++) {
  67462. var camera = cams[i];
  67463. var cameraName = camera.name;
  67464. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67465. camera.detachPostProcess(postProcess);
  67466. });
  67467. }
  67468. };
  67469. /**
  67470. * Gets a list of the post processes contained in the effect.
  67471. * @param camera The camera to get the post processes on.
  67472. * @returns The list of the post processes in the effect.
  67473. */
  67474. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67475. if (this._singleInstance) {
  67476. return this._postProcesses[0];
  67477. }
  67478. else {
  67479. if (!camera) {
  67480. return null;
  67481. }
  67482. return this._postProcesses[camera.name];
  67483. }
  67484. };
  67485. return PostProcessRenderEffect;
  67486. }());
  67487. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67488. })(BABYLON || (BABYLON = {}));
  67489. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67490. var BABYLON;
  67491. (function (BABYLON) {
  67492. var PostProcessRenderPipeline = /** @class */ (function () {
  67493. function PostProcessRenderPipeline(engine, name) {
  67494. this.engine = engine;
  67495. this._name = name;
  67496. this._renderEffects = {};
  67497. this._renderEffectsForIsolatedPass = new Array();
  67498. this._cameras = [];
  67499. }
  67500. PostProcessRenderPipeline.prototype.getClassName = function () {
  67501. return "PostProcessRenderPipeline";
  67502. };
  67503. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67504. get: function () {
  67505. for (var renderEffectName in this._renderEffects) {
  67506. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67507. if (!this._renderEffects[renderEffectName].isSupported) {
  67508. return false;
  67509. }
  67510. }
  67511. }
  67512. return true;
  67513. },
  67514. enumerable: true,
  67515. configurable: true
  67516. });
  67517. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  67518. this._renderEffects[renderEffect._name] = renderEffect;
  67519. };
  67520. // private
  67521. PostProcessRenderPipeline.prototype._rebuild = function () {
  67522. };
  67523. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67524. var renderEffects = this._renderEffects[renderEffectName];
  67525. if (!renderEffects) {
  67526. return;
  67527. }
  67528. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67529. };
  67530. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67531. var renderEffects = this._renderEffects[renderEffectName];
  67532. if (!renderEffects) {
  67533. return;
  67534. }
  67535. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67536. };
  67537. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67538. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67539. if (!cams) {
  67540. return;
  67541. }
  67542. var indicesToDelete = [];
  67543. var i;
  67544. for (i = 0; i < cams.length; i++) {
  67545. var camera = cams[i];
  67546. var cameraName = camera.name;
  67547. if (this._cameras.indexOf(camera) === -1) {
  67548. this._cameras[cameraName] = camera;
  67549. }
  67550. else if (unique) {
  67551. indicesToDelete.push(i);
  67552. }
  67553. }
  67554. for (i = 0; i < indicesToDelete.length; i++) {
  67555. cameras.splice(indicesToDelete[i], 1);
  67556. }
  67557. for (var renderEffectName in this._renderEffects) {
  67558. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67559. this._renderEffects[renderEffectName]._attachCameras(cams);
  67560. }
  67561. }
  67562. };
  67563. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67564. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67565. if (!cams) {
  67566. return;
  67567. }
  67568. for (var renderEffectName in this._renderEffects) {
  67569. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67570. this._renderEffects[renderEffectName]._detachCameras(cams);
  67571. }
  67572. }
  67573. for (var i = 0; i < cams.length; i++) {
  67574. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67575. }
  67576. };
  67577. PostProcessRenderPipeline.prototype._update = function () {
  67578. for (var renderEffectName in this._renderEffects) {
  67579. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67580. this._renderEffects[renderEffectName]._update();
  67581. }
  67582. }
  67583. for (var i = 0; i < this._cameras.length; i++) {
  67584. var cameraName = this._cameras[i].name;
  67585. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67586. this._renderEffectsForIsolatedPass[cameraName]._update();
  67587. }
  67588. }
  67589. };
  67590. PostProcessRenderPipeline.prototype._reset = function () {
  67591. this._renderEffects = {};
  67592. this._renderEffectsForIsolatedPass = new Array();
  67593. };
  67594. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67595. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  67596. var effectKeys = Object.keys(this._renderEffects);
  67597. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67598. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67599. if (postProcesses) {
  67600. postProcesses[0].samples = 4;
  67601. return true;
  67602. }
  67603. }
  67604. return false;
  67605. };
  67606. PostProcessRenderPipeline.prototype.dispose = function () {
  67607. // Must be implemented by children
  67608. };
  67609. __decorate([
  67610. BABYLON.serialize()
  67611. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  67612. return PostProcessRenderPipeline;
  67613. }());
  67614. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  67615. })(BABYLON || (BABYLON = {}));
  67616. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  67617. var BABYLON;
  67618. (function (BABYLON) {
  67619. /**
  67620. * This represents a depth renderer in Babylon.
  67621. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  67622. */
  67623. var DepthRenderer = /** @class */ (function () {
  67624. /**
  67625. * Instantiates a depth renderer
  67626. * @param scene The scene the renderer belongs to
  67627. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67628. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67629. */
  67630. function DepthRenderer(scene, type, camera) {
  67631. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67632. if (camera === void 0) { camera = null; }
  67633. var _this = this;
  67634. this._scene = scene;
  67635. this._camera = camera;
  67636. var engine = scene.getEngine();
  67637. // Render target
  67638. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67639. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67640. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67641. this._depthMap.refreshRate = 1;
  67642. this._depthMap.renderParticles = false;
  67643. this._depthMap.renderList = null;
  67644. // Camera to get depth map from to support multiple concurrent cameras
  67645. this._depthMap.activeCamera = this._camera;
  67646. this._depthMap.ignoreCameraViewport = true;
  67647. this._depthMap.useCameraPostProcesses = false;
  67648. // set default depth value to 1.0 (far away)
  67649. this._depthMap.onClearObservable.add(function (engine) {
  67650. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67651. });
  67652. // Custom render function
  67653. var renderSubMesh = function (subMesh) {
  67654. var mesh = subMesh.getRenderingMesh();
  67655. var scene = _this._scene;
  67656. var engine = scene.getEngine();
  67657. var material = subMesh.getMaterial();
  67658. if (!material) {
  67659. return;
  67660. }
  67661. // Culling and reverse (right handed system)
  67662. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67663. // Managing instances
  67664. var batch = mesh._getInstancesRenderList(subMesh._id);
  67665. if (batch.mustReturn) {
  67666. return;
  67667. }
  67668. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67669. var camera = _this._camera || scene.activeCamera;
  67670. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67671. engine.enableEffect(_this._effect);
  67672. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67673. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67674. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67675. // Alpha test
  67676. if (material && material.needAlphaTesting()) {
  67677. var alphaTexture = material.getAlphaTestTexture();
  67678. if (alphaTexture) {
  67679. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67680. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67681. }
  67682. }
  67683. // Bones
  67684. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67685. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67686. }
  67687. // Draw
  67688. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67689. }
  67690. };
  67691. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67692. var index;
  67693. if (depthOnlySubMeshes.length) {
  67694. engine.setColorWrite(false);
  67695. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67696. renderSubMesh(depthOnlySubMeshes.data[index]);
  67697. }
  67698. engine.setColorWrite(true);
  67699. }
  67700. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67701. renderSubMesh(opaqueSubMeshes.data[index]);
  67702. }
  67703. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67704. renderSubMesh(alphaTestSubMeshes.data[index]);
  67705. }
  67706. };
  67707. }
  67708. /**
  67709. * Creates the depth rendering effect and checks if the effect is ready.
  67710. * @param subMesh The submesh to be used to render the depth map of
  67711. * @param useInstances If multiple world instances should be used
  67712. * @returns if the depth renderer is ready to render the depth map
  67713. */
  67714. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67715. var material = subMesh.getMaterial();
  67716. if (material.disableDepthWrite) {
  67717. return false;
  67718. }
  67719. var defines = [];
  67720. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67721. var mesh = subMesh.getMesh();
  67722. // Alpha test
  67723. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67724. defines.push("#define ALPHATEST");
  67725. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67726. attribs.push(BABYLON.VertexBuffer.UVKind);
  67727. defines.push("#define UV1");
  67728. }
  67729. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67730. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67731. defines.push("#define UV2");
  67732. }
  67733. }
  67734. // Bones
  67735. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67736. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67737. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67738. if (mesh.numBoneInfluencers > 4) {
  67739. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67740. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67741. }
  67742. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67743. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67744. }
  67745. else {
  67746. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67747. }
  67748. // Instances
  67749. if (useInstances) {
  67750. defines.push("#define INSTANCES");
  67751. attribs.push("world0");
  67752. attribs.push("world1");
  67753. attribs.push("world2");
  67754. attribs.push("world3");
  67755. }
  67756. // Get correct effect
  67757. var join = defines.join("\n");
  67758. if (this._cachedDefines !== join) {
  67759. this._cachedDefines = join;
  67760. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67761. }
  67762. return this._effect.isReady();
  67763. };
  67764. /**
  67765. * Gets the texture which the depth map will be written to.
  67766. * @returns The depth map texture
  67767. */
  67768. DepthRenderer.prototype.getDepthMap = function () {
  67769. return this._depthMap;
  67770. };
  67771. /**
  67772. * Disposes of the depth renderer.
  67773. */
  67774. DepthRenderer.prototype.dispose = function () {
  67775. this._depthMap.dispose();
  67776. };
  67777. return DepthRenderer;
  67778. }());
  67779. BABYLON.DepthRenderer = DepthRenderer;
  67780. })(BABYLON || (BABYLON = {}));
  67781. //# sourceMappingURL=babylon.depthRenderer.js.map
  67782. var BABYLON;
  67783. (function (BABYLON) {
  67784. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67785. __extends(SSAORenderingPipeline, _super);
  67786. /**
  67787. * @constructor
  67788. * @param {string} name - The rendering pipeline name
  67789. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67790. * @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 }
  67791. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67792. */
  67793. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67794. var _this = _super.call(this, scene.getEngine(), name) || this;
  67795. // Members
  67796. /**
  67797. * The PassPostProcess id in the pipeline that contains the original scene color
  67798. * @type {string}
  67799. */
  67800. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67801. /**
  67802. * The SSAO PostProcess id in the pipeline
  67803. * @type {string}
  67804. */
  67805. _this.SSAORenderEffect = "SSAORenderEffect";
  67806. /**
  67807. * The horizontal blur PostProcess id in the pipeline
  67808. * @type {string}
  67809. */
  67810. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67811. /**
  67812. * The vertical blur PostProcess id in the pipeline
  67813. * @type {string}
  67814. */
  67815. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67816. /**
  67817. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67818. * @type {string}
  67819. */
  67820. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67821. /**
  67822. * The output strength of the SSAO post-process. Default value is 1.0.
  67823. * @type {number}
  67824. */
  67825. _this.totalStrength = 1.0;
  67826. /**
  67827. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67828. * @type {number}
  67829. */
  67830. _this.radius = 0.0001;
  67831. /**
  67832. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67833. * Must not be equal to fallOff and superior to fallOff.
  67834. * Default value is 0.975
  67835. * @type {number}
  67836. */
  67837. _this.area = 0.0075;
  67838. /**
  67839. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67840. * Must not be equal to area and inferior to area.
  67841. * Default value is 0.0
  67842. * @type {number}
  67843. */
  67844. _this.fallOff = 0.000001;
  67845. /**
  67846. * The base color of the SSAO post-process
  67847. * The final result is "base + ssao" between [0, 1]
  67848. * @type {number}
  67849. */
  67850. _this.base = 0.5;
  67851. _this._firstUpdate = true;
  67852. _this._scene = scene;
  67853. // Set up assets
  67854. _this._createRandomTexture();
  67855. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67856. var ssaoRatio = ratio.ssaoRatio || ratio;
  67857. var combineRatio = ratio.combineRatio || ratio;
  67858. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67859. _this._createSSAOPostProcess(ssaoRatio);
  67860. _this._createBlurPostProcess(ssaoRatio);
  67861. _this._createSSAOCombinePostProcess(combineRatio);
  67862. // Set up pipeline
  67863. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67864. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67865. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67866. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67867. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67868. // Finish
  67869. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67870. if (cameras)
  67871. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67872. return _this;
  67873. }
  67874. // Public Methods
  67875. /**
  67876. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67877. */
  67878. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67879. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67880. for (var i = 0; i < this._scene.cameras.length; i++) {
  67881. var camera = this._scene.cameras[i];
  67882. this._originalColorPostProcess.dispose(camera);
  67883. this._ssaoPostProcess.dispose(camera);
  67884. this._blurHPostProcess.dispose(camera);
  67885. this._blurVPostProcess.dispose(camera);
  67886. this._ssaoCombinePostProcess.dispose(camera);
  67887. }
  67888. this._randomTexture.dispose();
  67889. if (disableDepthRender)
  67890. this._scene.disableDepthRenderer();
  67891. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67892. _super.prototype.dispose.call(this);
  67893. };
  67894. // Private Methods
  67895. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67896. var _this = this;
  67897. var size = 16;
  67898. 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);
  67899. 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);
  67900. this._blurHPostProcess.onActivateObservable.add(function () {
  67901. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67902. _this._blurHPostProcess.kernel = size * dw;
  67903. });
  67904. this._blurVPostProcess.onActivateObservable.add(function () {
  67905. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67906. _this._blurVPostProcess.kernel = size * dw;
  67907. });
  67908. };
  67909. SSAORenderingPipeline.prototype._rebuild = function () {
  67910. this._firstUpdate = true;
  67911. _super.prototype._rebuild.call(this);
  67912. };
  67913. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67914. var _this = this;
  67915. var numSamples = 16;
  67916. var sampleSphere = [
  67917. 0.5381, 0.1856, -0.4319,
  67918. 0.1379, 0.2486, 0.4430,
  67919. 0.3371, 0.5679, -0.0057,
  67920. -0.6999, -0.0451, -0.0019,
  67921. 0.0689, -0.1598, -0.8547,
  67922. 0.0560, 0.0069, -0.1843,
  67923. -0.0146, 0.1402, 0.0762,
  67924. 0.0100, -0.1924, -0.0344,
  67925. -0.3577, -0.5301, -0.4358,
  67926. -0.3169, 0.1063, 0.0158,
  67927. 0.0103, -0.5869, 0.0046,
  67928. -0.0897, -0.4940, 0.3287,
  67929. 0.7119, -0.0154, -0.0918,
  67930. -0.0533, 0.0596, -0.5411,
  67931. 0.0352, -0.0631, 0.5460,
  67932. -0.4776, 0.2847, -0.0271
  67933. ];
  67934. var samplesFactor = 1.0 / numSamples;
  67935. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67936. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67937. "area", "fallOff", "base", "range", "viewport"
  67938. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67939. this._ssaoPostProcess.onApply = function (effect) {
  67940. if (_this._firstUpdate) {
  67941. effect.setArray3("sampleSphere", sampleSphere);
  67942. effect.setFloat("samplesFactor", samplesFactor);
  67943. effect.setFloat("randTextureTiles", 4.0);
  67944. }
  67945. effect.setFloat("totalStrength", _this.totalStrength);
  67946. effect.setFloat("radius", _this.radius);
  67947. effect.setFloat("area", _this.area);
  67948. effect.setFloat("fallOff", _this.fallOff);
  67949. effect.setFloat("base", _this.base);
  67950. effect.setTexture("textureSampler", _this._depthTexture);
  67951. effect.setTexture("randomSampler", _this._randomTexture);
  67952. };
  67953. };
  67954. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67955. var _this = this;
  67956. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67957. this._ssaoCombinePostProcess.onApply = function (effect) {
  67958. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67959. };
  67960. };
  67961. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67962. var size = 512;
  67963. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67964. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67965. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67966. var context = this._randomTexture.getContext();
  67967. var rand = function (min, max) {
  67968. return Math.random() * (max - min) + min;
  67969. };
  67970. var randVector = BABYLON.Vector3.Zero();
  67971. for (var x = 0; x < size; x++) {
  67972. for (var y = 0; y < size; y++) {
  67973. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67974. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67975. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67976. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67977. context.fillRect(x, y, 1, 1);
  67978. }
  67979. }
  67980. this._randomTexture.update(false);
  67981. };
  67982. __decorate([
  67983. BABYLON.serialize()
  67984. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67985. __decorate([
  67986. BABYLON.serialize()
  67987. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67988. __decorate([
  67989. BABYLON.serialize()
  67990. ], SSAORenderingPipeline.prototype, "area", void 0);
  67991. __decorate([
  67992. BABYLON.serialize()
  67993. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67994. __decorate([
  67995. BABYLON.serialize()
  67996. ], SSAORenderingPipeline.prototype, "base", void 0);
  67997. return SSAORenderingPipeline;
  67998. }(BABYLON.PostProcessRenderPipeline));
  67999. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68000. })(BABYLON || (BABYLON = {}));
  68001. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68002. var BABYLON;
  68003. (function (BABYLON) {
  68004. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68005. __extends(SSAO2RenderingPipeline, _super);
  68006. /**
  68007. * @constructor
  68008. * @param {string} name - The rendering pipeline name
  68009. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68010. * @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 }
  68011. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68012. */
  68013. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68014. var _this = _super.call(this, scene.getEngine(), name) || this;
  68015. // Members
  68016. /**
  68017. * The PassPostProcess id in the pipeline that contains the original scene color
  68018. * @type {string}
  68019. */
  68020. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68021. /**
  68022. * The SSAO PostProcess id in the pipeline
  68023. * @type {string}
  68024. */
  68025. _this.SSAORenderEffect = "SSAORenderEffect";
  68026. /**
  68027. * The horizontal blur PostProcess id in the pipeline
  68028. * @type {string}
  68029. */
  68030. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68031. /**
  68032. * The vertical blur PostProcess id in the pipeline
  68033. * @type {string}
  68034. */
  68035. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68036. /**
  68037. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68038. * @type {string}
  68039. */
  68040. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68041. /**
  68042. * The output strength of the SSAO post-process. Default value is 1.0.
  68043. * @type {number}
  68044. */
  68045. _this.totalStrength = 1.0;
  68046. /**
  68047. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68048. * @type {number}
  68049. */
  68050. _this.maxZ = 100.0;
  68051. /**
  68052. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68053. * @type {number}
  68054. */
  68055. _this.minZAspect = 0.2;
  68056. /**
  68057. * Number of samples used for the SSAO calculations. Default value is 8
  68058. * @type {number}
  68059. */
  68060. _this._samples = 8;
  68061. /**
  68062. * Are we using bilateral blur ?
  68063. * @type {boolean}
  68064. */
  68065. _this._expensiveBlur = true;
  68066. /**
  68067. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68068. * @type {number}
  68069. */
  68070. _this.radius = 2.0;
  68071. /**
  68072. * The base color of the SSAO post-process
  68073. * The final result is "base + ssao" between [0, 1]
  68074. * @type {number}
  68075. */
  68076. _this.base = 0.1;
  68077. _this._firstUpdate = true;
  68078. _this._scene = scene;
  68079. if (!_this.isSupported) {
  68080. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68081. return _this;
  68082. }
  68083. var ssaoRatio = ratio.ssaoRatio || ratio;
  68084. var blurRatio = ratio.blurRatio || ratio;
  68085. // Set up assets
  68086. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68087. _this._createRandomTexture();
  68088. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68089. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68090. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68091. _this._createSSAOPostProcess(1.0);
  68092. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68093. _this._createSSAOCombinePostProcess(blurRatio);
  68094. // Set up pipeline
  68095. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68096. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68097. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68098. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68099. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68100. // Finish
  68101. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68102. if (cameras)
  68103. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68104. return _this;
  68105. }
  68106. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68107. get: function () {
  68108. return this._samples;
  68109. },
  68110. set: function (n) {
  68111. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68112. this._samples = n;
  68113. this._sampleSphere = this._generateHemisphere();
  68114. this._firstUpdate = true;
  68115. },
  68116. enumerable: true,
  68117. configurable: true
  68118. });
  68119. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68120. get: function () {
  68121. return this._expensiveBlur;
  68122. },
  68123. set: function (b) {
  68124. 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"]);
  68125. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68126. this._expensiveBlur = b;
  68127. this._firstUpdate = true;
  68128. },
  68129. enumerable: true,
  68130. configurable: true
  68131. });
  68132. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68133. /**
  68134. * Support test.
  68135. * @type {boolean}
  68136. */
  68137. get: function () {
  68138. var engine = BABYLON.Engine.LastCreatedEngine;
  68139. if (!engine) {
  68140. return false;
  68141. }
  68142. return engine.getCaps().drawBuffersExtension;
  68143. },
  68144. enumerable: true,
  68145. configurable: true
  68146. });
  68147. // Public Methods
  68148. /**
  68149. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68150. */
  68151. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68152. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68153. for (var i = 0; i < this._scene.cameras.length; i++) {
  68154. var camera = this._scene.cameras[i];
  68155. this._originalColorPostProcess.dispose(camera);
  68156. this._ssaoPostProcess.dispose(camera);
  68157. this._blurHPostProcess.dispose(camera);
  68158. this._blurVPostProcess.dispose(camera);
  68159. this._ssaoCombinePostProcess.dispose(camera);
  68160. }
  68161. this._randomTexture.dispose();
  68162. if (disableGeometryBufferRenderer)
  68163. this._scene.disableGeometryBufferRenderer();
  68164. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68165. _super.prototype.dispose.call(this);
  68166. };
  68167. // Private Methods
  68168. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68169. var _this = this;
  68170. this._samplerOffsets = [];
  68171. var expensive = this.expensiveBlur;
  68172. for (var i = -8; i < 8; i++) {
  68173. this._samplerOffsets.push(i * 2 + 0.5);
  68174. }
  68175. 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");
  68176. this._blurHPostProcess.onApply = function (effect) {
  68177. if (!_this._scene.activeCamera) {
  68178. return;
  68179. }
  68180. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68181. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68182. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68183. effect.setFloat("radius", _this.radius);
  68184. effect.setTexture("depthSampler", _this._depthTexture);
  68185. if (_this._firstUpdate) {
  68186. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68187. }
  68188. };
  68189. 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");
  68190. this._blurVPostProcess.onApply = function (effect) {
  68191. if (!_this._scene.activeCamera) {
  68192. return;
  68193. }
  68194. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68195. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68196. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68197. effect.setFloat("radius", _this.radius);
  68198. effect.setTexture("depthSampler", _this._depthTexture);
  68199. if (_this._firstUpdate) {
  68200. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68201. _this._firstUpdate = false;
  68202. }
  68203. };
  68204. };
  68205. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68206. this._firstUpdate = true;
  68207. _super.prototype._rebuild.call(this);
  68208. };
  68209. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68210. var numSamples = this.samples;
  68211. var result = [];
  68212. var vector, scale;
  68213. var rand = function (min, max) {
  68214. return Math.random() * (max - min) + min;
  68215. };
  68216. var i = 0;
  68217. while (i < numSamples) {
  68218. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68219. vector.normalize();
  68220. scale = i / numSamples;
  68221. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68222. vector.scaleInPlace(scale);
  68223. result.push(vector.x, vector.y, vector.z);
  68224. i++;
  68225. }
  68226. return result;
  68227. };
  68228. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68229. var _this = this;
  68230. var numSamples = this.samples;
  68231. this._sampleSphere = this._generateHemisphere();
  68232. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68233. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68234. "base", "range", "projection", "near", "far", "texelSize",
  68235. "xViewport", "yViewport", "maxZ", "minZAspect"
  68236. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68237. this._ssaoPostProcess.onApply = function (effect) {
  68238. if (_this._firstUpdate) {
  68239. effect.setArray3("sampleSphere", _this._sampleSphere);
  68240. effect.setFloat("randTextureTiles", 4.0);
  68241. }
  68242. if (!_this._scene.activeCamera) {
  68243. return;
  68244. }
  68245. effect.setFloat("samplesFactor", 1 / _this.samples);
  68246. effect.setFloat("totalStrength", _this.totalStrength);
  68247. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68248. effect.setFloat("radius", _this.radius);
  68249. effect.setFloat("maxZ", _this.maxZ);
  68250. effect.setFloat("minZAspect", _this.minZAspect);
  68251. effect.setFloat("base", _this.base);
  68252. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68253. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68254. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68255. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68256. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68257. effect.setTexture("textureSampler", _this._depthTexture);
  68258. effect.setTexture("normalSampler", _this._normalTexture);
  68259. effect.setTexture("randomSampler", _this._randomTexture);
  68260. };
  68261. };
  68262. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68263. var _this = this;
  68264. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68265. this._ssaoCombinePostProcess.onApply = function (effect) {
  68266. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68267. };
  68268. };
  68269. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68270. var size = 512;
  68271. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68272. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68273. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68274. var context = this._randomTexture.getContext();
  68275. var rand = function (min, max) {
  68276. return Math.random() * (max - min) + min;
  68277. };
  68278. var randVector = BABYLON.Vector3.Zero();
  68279. for (var x = 0; x < size; x++) {
  68280. for (var y = 0; y < size; y++) {
  68281. randVector.x = rand(0.0, 1.0);
  68282. randVector.y = rand(0.0, 1.0);
  68283. randVector.z = 0.0;
  68284. randVector.normalize();
  68285. randVector.scaleInPlace(255);
  68286. randVector.x = Math.floor(randVector.x);
  68287. randVector.y = Math.floor(randVector.y);
  68288. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68289. context.fillRect(x, y, 1, 1);
  68290. }
  68291. }
  68292. this._randomTexture.update(false);
  68293. };
  68294. __decorate([
  68295. BABYLON.serialize()
  68296. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68297. __decorate([
  68298. BABYLON.serialize()
  68299. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68300. __decorate([
  68301. BABYLON.serialize()
  68302. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68303. __decorate([
  68304. BABYLON.serialize("samples")
  68305. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68306. __decorate([
  68307. BABYLON.serialize("expensiveBlur")
  68308. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68309. __decorate([
  68310. BABYLON.serialize()
  68311. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68312. __decorate([
  68313. BABYLON.serialize()
  68314. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68315. return SSAO2RenderingPipeline;
  68316. }(BABYLON.PostProcessRenderPipeline));
  68317. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68318. })(BABYLON || (BABYLON = {}));
  68319. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68320. // BABYLON.JS Chromatic Aberration GLSL Shader
  68321. // Author: Olivier Guyot
  68322. // Separates very slightly R, G and B colors on the edges of the screen
  68323. // Inspired by Francois Tarlier & Martins Upitis
  68324. var BABYLON;
  68325. (function (BABYLON) {
  68326. var LensRenderingPipeline = /** @class */ (function (_super) {
  68327. __extends(LensRenderingPipeline, _super);
  68328. /**
  68329. * @constructor
  68330. *
  68331. * Effect parameters are as follow:
  68332. * {
  68333. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68334. * edge_blur: number; // from 0 to x (1 for realism)
  68335. * distortion: number; // from 0 to x (1 for realism)
  68336. * grain_amount: number; // from 0 to 1
  68337. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68338. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68339. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68340. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68341. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68342. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68343. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68344. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68345. * }
  68346. * Note: if an effect parameter is unset, effect is disabled
  68347. *
  68348. * @param {string} name - The rendering pipeline name
  68349. * @param {object} parameters - An object containing all parameters (see above)
  68350. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68351. * @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)
  68352. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68353. */
  68354. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68355. if (ratio === void 0) { ratio = 1.0; }
  68356. var _this = _super.call(this, scene.getEngine(), name) || this;
  68357. // Lens effects can be of the following:
  68358. // - chromatic aberration (slight shift of RGB colors)
  68359. // - blur on the edge of the lens
  68360. // - lens distortion
  68361. // - depth-of-field blur & highlights enhancing
  68362. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68363. // - grain effect (noise or custom texture)
  68364. // Two additional texture samplers are needed:
  68365. // - depth map (for depth-of-field)
  68366. // - grain texture
  68367. /**
  68368. * The chromatic aberration PostProcess id in the pipeline
  68369. * @type {string}
  68370. */
  68371. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68372. /**
  68373. * The highlights enhancing PostProcess id in the pipeline
  68374. * @type {string}
  68375. */
  68376. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68377. /**
  68378. * The depth-of-field PostProcess id in the pipeline
  68379. * @type {string}
  68380. */
  68381. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68382. _this._scene = scene;
  68383. // Fetch texture samplers
  68384. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68385. if (parameters.grain_texture) {
  68386. _this._grainTexture = parameters.grain_texture;
  68387. }
  68388. else {
  68389. _this._createGrainTexture();
  68390. }
  68391. // save parameters
  68392. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68393. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68394. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68395. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68396. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68397. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68398. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68399. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68400. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68401. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68402. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68403. // Create effects
  68404. _this._createChromaticAberrationPostProcess(ratio);
  68405. _this._createHighlightsPostProcess(ratio);
  68406. _this._createDepthOfFieldPostProcess(ratio / 4);
  68407. // Set up pipeline
  68408. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68409. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68410. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68411. if (_this._highlightsGain === -1) {
  68412. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68413. }
  68414. // Finish
  68415. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68416. if (cameras) {
  68417. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68418. }
  68419. return _this;
  68420. }
  68421. // public methods (self explanatory)
  68422. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68423. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68424. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68425. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68426. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68427. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68428. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68429. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68430. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68431. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68432. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68433. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68434. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68435. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68436. };
  68437. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68438. this._highlightsPostProcess.updateEffect();
  68439. };
  68440. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68441. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68442. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68443. this._highlightsGain = amount;
  68444. };
  68445. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68446. if (this._highlightsGain === -1) {
  68447. this._highlightsGain = 1.0;
  68448. }
  68449. this._highlightsThreshold = amount;
  68450. };
  68451. LensRenderingPipeline.prototype.disableHighlights = function () {
  68452. this._highlightsGain = -1;
  68453. };
  68454. /**
  68455. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68456. */
  68457. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68458. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68459. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68460. this._chromaticAberrationPostProcess = null;
  68461. this._highlightsPostProcess = null;
  68462. this._depthOfFieldPostProcess = null;
  68463. this._grainTexture.dispose();
  68464. if (disableDepthRender)
  68465. this._scene.disableDepthRenderer();
  68466. };
  68467. // colors shifting and distortion
  68468. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68469. var _this = this;
  68470. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68471. [], // samplers
  68472. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68473. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68474. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68475. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68476. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68477. effect.setFloat('radialIntensity', 1);
  68478. effect.setFloat2('direction', 17, 17);
  68479. effect.setFloat2('centerPosition', 0.5, 0.5);
  68480. };
  68481. };
  68482. // highlights enhancing
  68483. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68484. var _this = this;
  68485. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68486. [], // samplers
  68487. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68488. this._highlightsPostProcess.onApply = function (effect) {
  68489. effect.setFloat('gain', _this._highlightsGain);
  68490. effect.setFloat('threshold', _this._highlightsThreshold);
  68491. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68492. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68493. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68494. };
  68495. };
  68496. // colors shifting and distortion
  68497. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68498. var _this = this;
  68499. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68500. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68501. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68502. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68503. this._depthOfFieldPostProcess.onApply = function (effect) {
  68504. effect.setTexture("depthSampler", _this._depthTexture);
  68505. effect.setTexture("grainSampler", _this._grainTexture);
  68506. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  68507. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  68508. effect.setFloat('grain_amount', _this._grainAmount);
  68509. effect.setBool('blur_noise', _this._blurNoise);
  68510. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68511. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68512. effect.setFloat('distortion', _this._distortion);
  68513. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  68514. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  68515. effect.setFloat('aperture', _this._dofAperture);
  68516. effect.setFloat('darken', _this._dofDarken);
  68517. effect.setFloat('edge_blur', _this._edgeBlur);
  68518. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68519. if (_this._scene.activeCamera) {
  68520. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68521. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68522. }
  68523. };
  68524. };
  68525. // creates a black and white random noise texture, 512x512
  68526. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68527. var size = 512;
  68528. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68529. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68530. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68531. var context = this._grainTexture.getContext();
  68532. var rand = function (min, max) {
  68533. return Math.random() * (max - min) + min;
  68534. };
  68535. var value;
  68536. for (var x = 0; x < size; x++) {
  68537. for (var y = 0; y < size; y++) {
  68538. value = Math.floor(rand(0.42, 0.58) * 255);
  68539. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68540. context.fillRect(x, y, 1, 1);
  68541. }
  68542. }
  68543. this._grainTexture.update(false);
  68544. };
  68545. return LensRenderingPipeline;
  68546. }(BABYLON.PostProcessRenderPipeline));
  68547. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68548. })(BABYLON || (BABYLON = {}));
  68549. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68550. var BABYLON;
  68551. (function (BABYLON) {
  68552. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68553. __extends(StandardRenderingPipeline, _super);
  68554. /**
  68555. * @constructor
  68556. * @param {string} name - The rendering pipeline name
  68557. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68558. * @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)
  68559. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68560. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68561. */
  68562. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68563. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68564. var _this = _super.call(this, scene.getEngine(), name) || this;
  68565. _this.downSampleX4PostProcess = null;
  68566. _this.brightPassPostProcess = null;
  68567. _this.blurHPostProcesses = [];
  68568. _this.blurVPostProcesses = [];
  68569. _this.textureAdderPostProcess = null;
  68570. _this.volumetricLightPostProcess = null;
  68571. _this.volumetricLightSmoothXPostProcess = null;
  68572. _this.volumetricLightSmoothYPostProcess = null;
  68573. _this.volumetricLightMergePostProces = null;
  68574. _this.volumetricLightFinalPostProcess = null;
  68575. _this.luminancePostProcess = null;
  68576. _this.luminanceDownSamplePostProcesses = [];
  68577. _this.hdrPostProcess = null;
  68578. _this.textureAdderFinalPostProcess = null;
  68579. _this.lensFlareFinalPostProcess = null;
  68580. _this.hdrFinalPostProcess = null;
  68581. _this.lensFlarePostProcess = null;
  68582. _this.lensFlareComposePostProcess = null;
  68583. _this.motionBlurPostProcess = null;
  68584. _this.depthOfFieldPostProcess = null;
  68585. // Values
  68586. _this.brightThreshold = 1.0;
  68587. _this.blurWidth = 512.0;
  68588. _this.horizontalBlur = false;
  68589. _this.exposure = 1.0;
  68590. _this.lensTexture = null;
  68591. _this.volumetricLightCoefficient = 0.2;
  68592. _this.volumetricLightPower = 4.0;
  68593. _this.volumetricLightBlurScale = 64.0;
  68594. _this.sourceLight = null;
  68595. _this.hdrMinimumLuminance = 1.0;
  68596. _this.hdrDecreaseRate = 0.5;
  68597. _this.hdrIncreaseRate = 0.5;
  68598. _this.lensColorTexture = null;
  68599. _this.lensFlareStrength = 20.0;
  68600. _this.lensFlareGhostDispersal = 1.4;
  68601. _this.lensFlareHaloWidth = 0.7;
  68602. _this.lensFlareDistortionStrength = 16.0;
  68603. _this.lensStarTexture = null;
  68604. _this.lensFlareDirtTexture = null;
  68605. _this.depthOfFieldDistance = 10.0;
  68606. _this.depthOfFieldBlurWidth = 64.0;
  68607. _this.motionStrength = 1.0;
  68608. // IAnimatable
  68609. _this.animations = [];
  68610. _this._currentDepthOfFieldSource = null;
  68611. _this._hdrCurrentLuminance = 1.0;
  68612. // Getters and setters
  68613. _this._bloomEnabled = true;
  68614. _this._depthOfFieldEnabled = false;
  68615. _this._vlsEnabled = false;
  68616. _this._lensFlareEnabled = false;
  68617. _this._hdrEnabled = false;
  68618. _this._motionBlurEnabled = false;
  68619. _this._motionBlurSamples = 64.0;
  68620. _this._volumetricLightStepsCount = 50.0;
  68621. _this._cameras = cameras || [];
  68622. // Initialize
  68623. _this._scene = scene;
  68624. _this._basePostProcess = originalPostProcess;
  68625. _this._ratio = ratio;
  68626. // Misc
  68627. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68628. // Finish
  68629. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68630. _this._buildPipeline();
  68631. return _this;
  68632. }
  68633. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68634. get: function () {
  68635. return this._bloomEnabled;
  68636. },
  68637. set: function (enabled) {
  68638. if (this._bloomEnabled === enabled) {
  68639. return;
  68640. }
  68641. this._bloomEnabled = enabled;
  68642. this._buildPipeline();
  68643. },
  68644. enumerable: true,
  68645. configurable: true
  68646. });
  68647. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68648. get: function () {
  68649. return this._depthOfFieldEnabled;
  68650. },
  68651. set: function (enabled) {
  68652. if (this._depthOfFieldEnabled === enabled) {
  68653. return;
  68654. }
  68655. this._depthOfFieldEnabled = enabled;
  68656. this._buildPipeline();
  68657. },
  68658. enumerable: true,
  68659. configurable: true
  68660. });
  68661. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68662. get: function () {
  68663. return this._lensFlareEnabled;
  68664. },
  68665. set: function (enabled) {
  68666. if (this._lensFlareEnabled === enabled) {
  68667. return;
  68668. }
  68669. this._lensFlareEnabled = enabled;
  68670. this._buildPipeline();
  68671. },
  68672. enumerable: true,
  68673. configurable: true
  68674. });
  68675. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68676. get: function () {
  68677. return this._hdrEnabled;
  68678. },
  68679. set: function (enabled) {
  68680. if (this._hdrEnabled === enabled) {
  68681. return;
  68682. }
  68683. this._hdrEnabled = enabled;
  68684. this._buildPipeline();
  68685. },
  68686. enumerable: true,
  68687. configurable: true
  68688. });
  68689. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68690. get: function () {
  68691. return this._vlsEnabled;
  68692. },
  68693. set: function (enabled) {
  68694. if (this._vlsEnabled === enabled) {
  68695. return;
  68696. }
  68697. if (enabled) {
  68698. var geometry = this._scene.enableGeometryBufferRenderer();
  68699. if (!geometry) {
  68700. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68701. return;
  68702. }
  68703. }
  68704. this._vlsEnabled = enabled;
  68705. this._buildPipeline();
  68706. },
  68707. enumerable: true,
  68708. configurable: true
  68709. });
  68710. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68711. get: function () {
  68712. return this._motionBlurEnabled;
  68713. },
  68714. set: function (enabled) {
  68715. if (this._motionBlurEnabled === enabled) {
  68716. return;
  68717. }
  68718. this._motionBlurEnabled = enabled;
  68719. this._buildPipeline();
  68720. },
  68721. enumerable: true,
  68722. configurable: true
  68723. });
  68724. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68725. get: function () {
  68726. return this._volumetricLightStepsCount;
  68727. },
  68728. set: function (count) {
  68729. if (this.volumetricLightPostProcess) {
  68730. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68731. }
  68732. this._volumetricLightStepsCount = count;
  68733. },
  68734. enumerable: true,
  68735. configurable: true
  68736. });
  68737. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68738. get: function () {
  68739. return this._motionBlurSamples;
  68740. },
  68741. set: function (samples) {
  68742. if (this.motionBlurPostProcess) {
  68743. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68744. }
  68745. this._motionBlurSamples = samples;
  68746. },
  68747. enumerable: true,
  68748. configurable: true
  68749. });
  68750. StandardRenderingPipeline.prototype._buildPipeline = function () {
  68751. var _this = this;
  68752. var ratio = this._ratio;
  68753. var scene = this._scene;
  68754. this._disposePostProcesses();
  68755. this._reset();
  68756. // Create pass post-process
  68757. if (!this._basePostProcess) {
  68758. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68759. this.originalPostProcess.onApply = function (effect) {
  68760. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68761. };
  68762. }
  68763. else {
  68764. this.originalPostProcess = this._basePostProcess;
  68765. }
  68766. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68767. this._currentDepthOfFieldSource = this.originalPostProcess;
  68768. if (this._vlsEnabled) {
  68769. // Create volumetric light
  68770. this._createVolumetricLightPostProcess(scene, ratio);
  68771. // Create volumetric light final post-process
  68772. 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);
  68773. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68774. }
  68775. if (this._bloomEnabled) {
  68776. // Create down sample X4 post-process
  68777. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68778. // Create bright pass post-process
  68779. this._createBrightPassPostProcess(scene, ratio / 2);
  68780. // Create gaussian blur post-processes (down sampling blurs)
  68781. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68782. // Create texture adder post-process
  68783. this._createTextureAdderPostProcess(scene, ratio);
  68784. // Create depth-of-field source post-process
  68785. 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);
  68786. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68787. }
  68788. if (this._lensFlareEnabled) {
  68789. // Create lens flare post-process
  68790. this._createLensFlarePostProcess(scene, ratio);
  68791. // Create depth-of-field source post-process post lens-flare and disable it now
  68792. 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);
  68793. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68794. }
  68795. if (this._hdrEnabled) {
  68796. // Create luminance
  68797. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68798. // Create HDR
  68799. this._createHdrPostProcess(scene, ratio);
  68800. // Create depth-of-field source post-process post hdr and disable it now
  68801. 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);
  68802. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68803. }
  68804. if (this._depthOfFieldEnabled) {
  68805. // Create gaussian blur used by depth-of-field
  68806. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68807. // Create depth-of-field post-process
  68808. this._createDepthOfFieldPostProcess(scene, ratio);
  68809. }
  68810. if (this._motionBlurEnabled) {
  68811. // Create motion blur post-process
  68812. this._createMotionBlurPostProcess(scene, ratio);
  68813. }
  68814. if (this._cameras !== null) {
  68815. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68816. }
  68817. };
  68818. // Down Sample X4 Post-Processs
  68819. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68820. var _this = this;
  68821. var downSampleX4Offsets = new Array(32);
  68822. 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);
  68823. this.downSampleX4PostProcess.onApply = function (effect) {
  68824. var id = 0;
  68825. var width = _this.downSampleX4PostProcess.width;
  68826. var height = _this.downSampleX4PostProcess.height;
  68827. for (var i = -2; i < 2; i++) {
  68828. for (var j = -2; j < 2; j++) {
  68829. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68830. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68831. id += 2;
  68832. }
  68833. }
  68834. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68835. };
  68836. // Add to pipeline
  68837. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68838. };
  68839. // Brightpass Post-Process
  68840. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68841. var _this = this;
  68842. var brightOffsets = new Array(8);
  68843. 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);
  68844. this.brightPassPostProcess.onApply = function (effect) {
  68845. var sU = (1.0 / _this.brightPassPostProcess.width);
  68846. var sV = (1.0 / _this.brightPassPostProcess.height);
  68847. brightOffsets[0] = -0.5 * sU;
  68848. brightOffsets[1] = 0.5 * sV;
  68849. brightOffsets[2] = 0.5 * sU;
  68850. brightOffsets[3] = 0.5 * sV;
  68851. brightOffsets[4] = -0.5 * sU;
  68852. brightOffsets[5] = -0.5 * sV;
  68853. brightOffsets[6] = 0.5 * sU;
  68854. brightOffsets[7] = -0.5 * sV;
  68855. effect.setArray2("dsOffsets", brightOffsets);
  68856. effect.setFloat("brightThreshold", _this.brightThreshold);
  68857. };
  68858. // Add to pipeline
  68859. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68860. };
  68861. // Create blur H&V post-processes
  68862. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68863. var _this = this;
  68864. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68865. var engine = scene.getEngine();
  68866. 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);
  68867. 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);
  68868. blurX.onActivateObservable.add(function () {
  68869. var dw = blurX.width / engine.getRenderWidth();
  68870. blurX.kernel = _this[blurWidthKey] * dw;
  68871. });
  68872. blurY.onActivateObservable.add(function () {
  68873. var dw = blurY.height / engine.getRenderHeight();
  68874. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68875. });
  68876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68877. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68878. this.blurHPostProcesses.push(blurX);
  68879. this.blurVPostProcesses.push(blurY);
  68880. };
  68881. // Create texture adder post-process
  68882. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68883. var _this = this;
  68884. 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);
  68885. this.textureAdderPostProcess.onApply = function (effect) {
  68886. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68887. effect.setTexture("lensSampler", _this.lensTexture);
  68888. effect.setFloat("exposure", _this.exposure);
  68889. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68890. };
  68891. // Add to pipeline
  68892. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68893. };
  68894. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68895. var _this = this;
  68896. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68897. geometryRenderer.enablePosition = true;
  68898. var geometry = geometryRenderer.getGBuffer();
  68899. // Base post-process
  68900. 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));
  68901. var depthValues = BABYLON.Vector2.Zero();
  68902. this.volumetricLightPostProcess.onApply = function (effect) {
  68903. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68904. var generator = _this.sourceLight.getShadowGenerator();
  68905. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68906. effect.setTexture("positionSampler", geometry.textures[2]);
  68907. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68908. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68909. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68910. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68911. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68912. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68913. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68914. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68915. effect.setVector2("depthValues", depthValues);
  68916. }
  68917. };
  68918. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68919. // Smooth
  68920. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68921. // Merge
  68922. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68923. this.volumetricLightMergePostProces.onApply = function (effect) {
  68924. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68925. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68926. };
  68927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68928. };
  68929. // Create luminance
  68930. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68931. var _this = this;
  68932. // Create luminance
  68933. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68934. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68935. var offsets = [];
  68936. this.luminancePostProcess.onApply = function (effect) {
  68937. var sU = (1.0 / _this.luminancePostProcess.width);
  68938. var sV = (1.0 / _this.luminancePostProcess.height);
  68939. offsets[0] = -0.5 * sU;
  68940. offsets[1] = 0.5 * sV;
  68941. offsets[2] = 0.5 * sU;
  68942. offsets[3] = 0.5 * sV;
  68943. offsets[4] = -0.5 * sU;
  68944. offsets[5] = -0.5 * sV;
  68945. offsets[6] = 0.5 * sU;
  68946. offsets[7] = -0.5 * sV;
  68947. effect.setArray2("lumOffsets", offsets);
  68948. };
  68949. // Add to pipeline
  68950. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68951. // Create down sample luminance
  68952. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68953. var size = Math.pow(3, i);
  68954. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68955. if (i === 0) {
  68956. defines += "#define FINAL_DOWN_SAMPLER";
  68957. }
  68958. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68959. this.luminanceDownSamplePostProcesses.push(postProcess);
  68960. }
  68961. // Create callbacks and add effects
  68962. var lastLuminance = this.luminancePostProcess;
  68963. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68964. var downSampleOffsets = new Array(18);
  68965. pp.onApply = function (effect) {
  68966. if (!lastLuminance) {
  68967. return;
  68968. }
  68969. var id = 0;
  68970. for (var x = -1; x < 2; x++) {
  68971. for (var y = -1; y < 2; y++) {
  68972. downSampleOffsets[id] = x / lastLuminance.width;
  68973. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68974. id += 2;
  68975. }
  68976. }
  68977. effect.setArray2("dsOffsets", downSampleOffsets);
  68978. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68979. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68980. lastLuminance = _this.luminancePostProcess;
  68981. }
  68982. else {
  68983. lastLuminance = pp;
  68984. }
  68985. };
  68986. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68987. pp.onAfterRender = function (effect) {
  68988. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68989. 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);
  68990. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68991. };
  68992. }
  68993. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68994. });
  68995. };
  68996. // Create HDR post-process
  68997. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68998. var _this = this;
  68999. 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);
  69000. var outputLiminance = 1;
  69001. var time = 0;
  69002. var lastTime = 0;
  69003. this.hdrPostProcess.onApply = function (effect) {
  69004. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69005. time += scene.getEngine().getDeltaTime();
  69006. if (outputLiminance < 0) {
  69007. outputLiminance = _this._hdrCurrentLuminance;
  69008. }
  69009. else {
  69010. var dt = (lastTime - time) / 1000.0;
  69011. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69012. outputLiminance += _this.hdrDecreaseRate * dt;
  69013. }
  69014. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69015. outputLiminance -= _this.hdrIncreaseRate * dt;
  69016. }
  69017. else {
  69018. outputLiminance = _this._hdrCurrentLuminance;
  69019. }
  69020. }
  69021. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69022. effect.setFloat("averageLuminance", outputLiminance);
  69023. lastTime = time;
  69024. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69025. };
  69026. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69027. };
  69028. // Create lens flare post-process
  69029. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69030. var _this = this;
  69031. 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);
  69032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69033. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69034. 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);
  69035. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69036. var resolution = new BABYLON.Vector2(0, 0);
  69037. // Lens flare
  69038. this.lensFlarePostProcess.onApply = function (effect) {
  69039. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69040. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69041. effect.setFloat("strength", _this.lensFlareStrength);
  69042. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69043. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69044. // Shift
  69045. resolution.x = _this.lensFlarePostProcess.width;
  69046. resolution.y = _this.lensFlarePostProcess.height;
  69047. effect.setVector2("resolution", resolution);
  69048. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69049. };
  69050. // Compose
  69051. 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);
  69052. 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);
  69053. this.lensFlareComposePostProcess.onApply = function (effect) {
  69054. if (!_this._scene.activeCamera) {
  69055. return;
  69056. }
  69057. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69058. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69059. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69060. // Lens start rotation matrix
  69061. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69062. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69063. 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));
  69064. camRot *= 4.0;
  69065. 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);
  69066. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69067. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69068. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69069. };
  69070. };
  69071. // Create depth-of-field post-process
  69072. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69073. var _this = this;
  69074. 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);
  69075. this.depthOfFieldPostProcess.onApply = function (effect) {
  69076. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69077. effect.setTexture("depthSampler", _this._getDepthTexture());
  69078. effect.setFloat("distance", _this.depthOfFieldDistance);
  69079. };
  69080. // Add to pipeline
  69081. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69082. };
  69083. // Create motion blur post-process
  69084. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69085. var _this = this;
  69086. 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);
  69087. var motionScale = 0;
  69088. var prevViewProjection = BABYLON.Matrix.Identity();
  69089. var invViewProjection = BABYLON.Matrix.Identity();
  69090. var viewProjection = BABYLON.Matrix.Identity();
  69091. var screenSize = BABYLON.Vector2.Zero();
  69092. this.motionBlurPostProcess.onApply = function (effect) {
  69093. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69094. viewProjection.invertToRef(invViewProjection);
  69095. effect.setMatrix("inverseViewProjection", invViewProjection);
  69096. effect.setMatrix("prevViewProjection", prevViewProjection);
  69097. prevViewProjection = viewProjection;
  69098. screenSize.x = _this.motionBlurPostProcess.width;
  69099. screenSize.y = _this.motionBlurPostProcess.height;
  69100. effect.setVector2("screenSize", screenSize);
  69101. motionScale = scene.getEngine().getFps() / 60.0;
  69102. effect.setFloat("motionScale", motionScale);
  69103. effect.setFloat("motionStrength", _this.motionStrength);
  69104. effect.setTexture("depthSampler", _this._getDepthTexture());
  69105. };
  69106. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69107. };
  69108. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69109. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69110. var renderer = this._scene.enableGeometryBufferRenderer();
  69111. return renderer.getGBuffer().textures[0];
  69112. }
  69113. return this._scene.enableDepthRenderer().getDepthMap();
  69114. };
  69115. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69116. for (var i = 0; i < this._cameras.length; i++) {
  69117. var camera = this._cameras[i];
  69118. if (this.originalPostProcess) {
  69119. this.originalPostProcess.dispose(camera);
  69120. }
  69121. if (this.downSampleX4PostProcess) {
  69122. this.downSampleX4PostProcess.dispose(camera);
  69123. }
  69124. if (this.brightPassPostProcess) {
  69125. this.brightPassPostProcess.dispose(camera);
  69126. }
  69127. if (this.textureAdderPostProcess) {
  69128. this.textureAdderPostProcess.dispose(camera);
  69129. }
  69130. if (this.textureAdderFinalPostProcess) {
  69131. this.textureAdderFinalPostProcess.dispose(camera);
  69132. }
  69133. if (this.volumetricLightPostProcess) {
  69134. this.volumetricLightPostProcess.dispose(camera);
  69135. }
  69136. if (this.volumetricLightSmoothXPostProcess) {
  69137. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69138. }
  69139. if (this.volumetricLightSmoothYPostProcess) {
  69140. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69141. }
  69142. if (this.volumetricLightMergePostProces) {
  69143. this.volumetricLightMergePostProces.dispose(camera);
  69144. }
  69145. if (this.volumetricLightFinalPostProcess) {
  69146. this.volumetricLightFinalPostProcess.dispose(camera);
  69147. }
  69148. if (this.lensFlarePostProcess) {
  69149. this.lensFlarePostProcess.dispose(camera);
  69150. }
  69151. if (this.lensFlareComposePostProcess) {
  69152. this.lensFlareComposePostProcess.dispose(camera);
  69153. }
  69154. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69155. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69156. }
  69157. if (this.luminancePostProcess) {
  69158. this.luminancePostProcess.dispose(camera);
  69159. }
  69160. if (this.hdrPostProcess) {
  69161. this.hdrPostProcess.dispose(camera);
  69162. }
  69163. if (this.hdrFinalPostProcess) {
  69164. this.hdrFinalPostProcess.dispose(camera);
  69165. }
  69166. if (this.depthOfFieldPostProcess) {
  69167. this.depthOfFieldPostProcess.dispose(camera);
  69168. }
  69169. if (this.motionBlurPostProcess) {
  69170. this.motionBlurPostProcess.dispose(camera);
  69171. }
  69172. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69173. this.blurHPostProcesses[j].dispose(camera);
  69174. }
  69175. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69176. this.blurVPostProcesses[j].dispose(camera);
  69177. }
  69178. }
  69179. this.originalPostProcess = null;
  69180. this.downSampleX4PostProcess = null;
  69181. this.brightPassPostProcess = null;
  69182. this.textureAdderPostProcess = null;
  69183. this.textureAdderFinalPostProcess = null;
  69184. this.volumetricLightPostProcess = null;
  69185. this.volumetricLightSmoothXPostProcess = null;
  69186. this.volumetricLightSmoothYPostProcess = null;
  69187. this.volumetricLightMergePostProces = null;
  69188. this.volumetricLightFinalPostProcess = null;
  69189. this.lensFlarePostProcess = null;
  69190. this.lensFlareComposePostProcess = null;
  69191. this.luminancePostProcess = null;
  69192. this.hdrPostProcess = null;
  69193. this.hdrFinalPostProcess = null;
  69194. this.depthOfFieldPostProcess = null;
  69195. this.motionBlurPostProcess = null;
  69196. this.luminanceDownSamplePostProcesses = [];
  69197. this.blurHPostProcesses = [];
  69198. this.blurVPostProcesses = [];
  69199. };
  69200. // Dispose
  69201. StandardRenderingPipeline.prototype.dispose = function () {
  69202. this._disposePostProcesses();
  69203. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69204. _super.prototype.dispose.call(this);
  69205. };
  69206. // Serialize rendering pipeline
  69207. StandardRenderingPipeline.prototype.serialize = function () {
  69208. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69209. serializationObject.customType = "StandardRenderingPipeline";
  69210. return serializationObject;
  69211. };
  69212. /**
  69213. * Static members
  69214. */
  69215. // Parse serialized pipeline
  69216. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69217. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69218. };
  69219. // Luminance steps
  69220. StandardRenderingPipeline.LuminanceSteps = 6;
  69221. __decorate([
  69222. BABYLON.serialize()
  69223. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69224. __decorate([
  69225. BABYLON.serialize()
  69226. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69227. __decorate([
  69228. BABYLON.serialize()
  69229. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69230. __decorate([
  69231. BABYLON.serialize()
  69232. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69233. __decorate([
  69234. BABYLON.serializeAsTexture("lensTexture")
  69235. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69236. __decorate([
  69237. BABYLON.serialize()
  69238. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69239. __decorate([
  69240. BABYLON.serialize()
  69241. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69242. __decorate([
  69243. BABYLON.serialize()
  69244. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69245. __decorate([
  69246. BABYLON.serialize()
  69247. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69248. __decorate([
  69249. BABYLON.serialize()
  69250. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69251. __decorate([
  69252. BABYLON.serialize()
  69253. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69254. __decorate([
  69255. BABYLON.serializeAsTexture("lensColorTexture")
  69256. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69257. __decorate([
  69258. BABYLON.serialize()
  69259. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69260. __decorate([
  69261. BABYLON.serialize()
  69262. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69263. __decorate([
  69264. BABYLON.serialize()
  69265. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69266. __decorate([
  69267. BABYLON.serialize()
  69268. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69269. __decorate([
  69270. BABYLON.serializeAsTexture("lensStarTexture")
  69271. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69272. __decorate([
  69273. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69274. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69275. __decorate([
  69276. BABYLON.serialize()
  69277. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69278. __decorate([
  69279. BABYLON.serialize()
  69280. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69281. __decorate([
  69282. BABYLON.serialize()
  69283. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69284. __decorate([
  69285. BABYLON.serialize()
  69286. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69287. __decorate([
  69288. BABYLON.serialize()
  69289. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69290. __decorate([
  69291. BABYLON.serialize()
  69292. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69293. __decorate([
  69294. BABYLON.serialize()
  69295. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69296. __decorate([
  69297. BABYLON.serialize()
  69298. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69299. __decorate([
  69300. BABYLON.serialize()
  69301. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69302. __decorate([
  69303. BABYLON.serialize()
  69304. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69305. __decorate([
  69306. BABYLON.serialize()
  69307. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69308. __decorate([
  69309. BABYLON.serialize()
  69310. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69311. return StandardRenderingPipeline;
  69312. }(BABYLON.PostProcessRenderPipeline));
  69313. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69314. })(BABYLON || (BABYLON = {}));
  69315. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69316. var BABYLON;
  69317. (function (BABYLON) {
  69318. var FxaaPostProcess = /** @class */ (function (_super) {
  69319. __extends(FxaaPostProcess, _super);
  69320. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69321. if (camera === void 0) { camera = null; }
  69322. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69323. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69324. _this.onApplyObservable.add(function (effect) {
  69325. var texelSize = _this.texelSize;
  69326. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69327. });
  69328. return _this;
  69329. }
  69330. return FxaaPostProcess;
  69331. }(BABYLON.PostProcess));
  69332. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69333. })(BABYLON || (BABYLON = {}));
  69334. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69335. var BABYLON;
  69336. (function (BABYLON) {
  69337. /**
  69338. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69339. */
  69340. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69341. __extends(ChromaticAberrationPostProcess, _super);
  69342. /**
  69343. * Creates a new instance of @see ChromaticAberrationPostProcess
  69344. * @param name The name of the effect.
  69345. * @param screenWidth The width of the screen to apply the effect on.
  69346. * @param screenHeight The height of the screen to apply the effect on.
  69347. * @param options The required width/height ratio to downsize to before computing the render pass.
  69348. * @param camera The camera to apply the render pass to.
  69349. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69350. * @param engine The engine which the post process will be applied. (default: current engine)
  69351. * @param reusable If the post process can be reused on the same frame. (default: false)
  69352. * @param textureType Type of textures used when performing the post process. (default: 0)
  69353. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69354. */
  69355. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69356. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69357. if (blockCompilation === void 0) { blockCompilation = false; }
  69358. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69359. /**
  69360. * The amount of seperation of rgb channels (default: 30)
  69361. */
  69362. _this.aberrationAmount = 30;
  69363. /**
  69364. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69365. */
  69366. _this.radialIntensity = 0;
  69367. /**
  69368. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  69369. */
  69370. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69371. /**
  69372. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  69373. */
  69374. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69375. _this.onApplyObservable.add(function (effect) {
  69376. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69377. effect.setFloat('screen_width', screenWidth);
  69378. effect.setFloat('screen_height', screenHeight);
  69379. effect.setFloat('radialIntensity', _this.radialIntensity);
  69380. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69381. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69382. });
  69383. return _this;
  69384. }
  69385. return ChromaticAberrationPostProcess;
  69386. }(BABYLON.PostProcess));
  69387. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69388. })(BABYLON || (BABYLON = {}));
  69389. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69390. var BABYLON;
  69391. (function (BABYLON) {
  69392. /**
  69393. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69394. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69395. */
  69396. var SharpenPostProcess = /** @class */ (function (_super) {
  69397. __extends(SharpenPostProcess, _super);
  69398. /**
  69399. * Creates a new instance of @see ConvolutionPostProcess
  69400. * @param name The name of the effect.
  69401. * @param options The required width/height ratio to downsize to before computing the render pass.
  69402. * @param camera The camera to apply the render pass to.
  69403. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69404. * @param engine The engine which the post process will be applied. (default: current engine)
  69405. * @param reusable If the post process can be reused on the same frame. (default: false)
  69406. * @param textureType Type of textures used when performing the post process. (default: 0)
  69407. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69408. */
  69409. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69410. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69411. if (blockCompilation === void 0) { blockCompilation = false; }
  69412. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69413. /**
  69414. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69415. */
  69416. _this.colorAmount = 1.0;
  69417. /**
  69418. * How much sharpness should be applied (default: 0.3)
  69419. */
  69420. _this.edgeAmount = 0.3;
  69421. _this.onApply = function (effect) {
  69422. effect.setFloat2("screenSize", _this.width, _this.height);
  69423. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69424. };
  69425. return _this;
  69426. }
  69427. return SharpenPostProcess;
  69428. }(BABYLON.PostProcess));
  69429. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69430. })(BABYLON || (BABYLON = {}));
  69431. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69432. var BABYLON;
  69433. (function (BABYLON) {
  69434. /**
  69435. * The Blur Post Process which blurs an image based on a kernel and direction.
  69436. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69437. */
  69438. var BlurPostProcess = /** @class */ (function (_super) {
  69439. __extends(BlurPostProcess, _super);
  69440. /**
  69441. * Creates a new instance of @see BlurPostProcess
  69442. * @param name The name of the effect.
  69443. * @param direction The direction in which to blur the image.
  69444. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  69445. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69446. * @param camera The camera to apply the render pass to.
  69447. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69448. * @param engine The engine which the post process will be applied. (default: current engine)
  69449. * @param reusable If the post process can be reused on the same frame. (default: false)
  69450. * @param textureType Type of textures used when performing the post process. (default: 0)
  69451. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69452. */
  69453. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69455. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69456. if (defines === void 0) { defines = ""; }
  69457. if (blockCompilation === void 0) { blockCompilation = false; }
  69458. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  69459. _this.direction = direction;
  69460. _this.blockCompilation = blockCompilation;
  69461. _this._packedFloat = false;
  69462. _this._staticDefines = "";
  69463. _this._staticDefines = defines;
  69464. _this.onApplyObservable.add(function (effect) {
  69465. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69466. });
  69467. _this.kernel = kernel;
  69468. return _this;
  69469. }
  69470. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69471. /**
  69472. * Gets the length in pixels of the blur sample region
  69473. */
  69474. get: function () {
  69475. return this._idealKernel;
  69476. },
  69477. /**
  69478. * Sets the length in pixels of the blur sample region
  69479. */
  69480. set: function (v) {
  69481. if (this._idealKernel === v) {
  69482. return;
  69483. }
  69484. v = Math.max(v, 1);
  69485. this._idealKernel = v;
  69486. this._kernel = this._nearestBestKernel(v);
  69487. if (!this.blockCompilation) {
  69488. this._updateParameters();
  69489. }
  69490. },
  69491. enumerable: true,
  69492. configurable: true
  69493. });
  69494. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69495. /**
  69496. * Gets wether or not the blur is unpacking/repacking floats
  69497. */
  69498. get: function () {
  69499. return this._packedFloat;
  69500. },
  69501. /**
  69502. * Sets wether or not the blur needs to unpack/repack floats
  69503. */
  69504. set: function (v) {
  69505. if (this._packedFloat === v) {
  69506. return;
  69507. }
  69508. this._packedFloat = v;
  69509. if (!this.blockCompilation) {
  69510. this._updateParameters();
  69511. }
  69512. },
  69513. enumerable: true,
  69514. configurable: true
  69515. });
  69516. /**
  69517. * Updates the effect with the current post process compile time values and recompiles the shader.
  69518. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69519. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69520. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69521. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  69522. * @param onCompiled Called when the shader has been compiled.
  69523. * @param onError Called if there is an error when compiling a shader.
  69524. */
  69525. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69526. if (defines === void 0) { defines = null; }
  69527. if (uniforms === void 0) { uniforms = null; }
  69528. if (samplers === void 0) { samplers = null; }
  69529. this._updateParameters(onCompiled, onError);
  69530. };
  69531. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69532. // Generate sampling offsets and weights
  69533. var N = this._kernel;
  69534. var centerIndex = (N - 1) / 2;
  69535. // Generate Gaussian sampling weights over kernel
  69536. var offsets = [];
  69537. var weights = [];
  69538. var totalWeight = 0;
  69539. for (var i = 0; i < N; i++) {
  69540. var u = i / (N - 1);
  69541. var w = this._gaussianWeight(u * 2.0 - 1);
  69542. offsets[i] = (i - centerIndex);
  69543. weights[i] = w;
  69544. totalWeight += w;
  69545. }
  69546. // Normalize weights
  69547. for (var i = 0; i < weights.length; i++) {
  69548. weights[i] /= totalWeight;
  69549. }
  69550. // Optimize: combine samples to take advantage of hardware linear sampling
  69551. // Walk from left to center, combining pairs (symmetrically)
  69552. var linearSamplingWeights = [];
  69553. var linearSamplingOffsets = [];
  69554. var linearSamplingMap = [];
  69555. for (var i = 0; i <= centerIndex; i += 2) {
  69556. var j = Math.min(i + 1, Math.floor(centerIndex));
  69557. var singleCenterSample = i === j;
  69558. if (singleCenterSample) {
  69559. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69560. }
  69561. else {
  69562. var sharedCell = j === centerIndex;
  69563. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69564. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69565. if (offsetLinear === 0) {
  69566. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69567. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69568. }
  69569. else {
  69570. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69571. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69572. }
  69573. }
  69574. }
  69575. for (var i = 0; i < linearSamplingMap.length; i++) {
  69576. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69577. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69578. }
  69579. // Replace with optimized
  69580. offsets = linearSamplingOffsets;
  69581. weights = linearSamplingWeights;
  69582. // Generate shaders
  69583. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69584. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69585. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69586. var defines = "";
  69587. defines += this._staticDefines;
  69588. for (var i = 0; i < varyingCount; i++) {
  69589. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69590. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69591. }
  69592. var depCount = 0;
  69593. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69594. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69595. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69596. depCount++;
  69597. }
  69598. if (this.packedFloat) {
  69599. defines += "#define PACKEDFLOAT 1";
  69600. }
  69601. _super.prototype.updateEffect.call(this, defines, null, null, {
  69602. varyingCount: varyingCount,
  69603. depCount: depCount
  69604. }, onCompiled, onError);
  69605. };
  69606. /**
  69607. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69608. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69609. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69610. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69611. * The gaps between physical kernels are compensated for in the weighting of the samples
  69612. * @param idealKernel Ideal blur kernel.
  69613. * @return Nearest best kernel.
  69614. */
  69615. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69616. var v = Math.round(idealKernel);
  69617. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69618. var k = _a[_i];
  69619. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69620. return Math.max(k, 3);
  69621. }
  69622. }
  69623. return Math.max(v, 3);
  69624. };
  69625. /**
  69626. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69627. * @param x The point on the Gaussian distribution to sample.
  69628. * @return the value of the Gaussian function at x.
  69629. */
  69630. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69631. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69632. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69633. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69634. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69635. // truncated at around 1.3% of peak strength.
  69636. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69637. var sigma = (1 / 3);
  69638. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69639. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69640. var weight = (1.0 / denominator) * Math.exp(exponent);
  69641. return weight;
  69642. };
  69643. /**
  69644. * Generates a string that can be used as a floating point number in GLSL.
  69645. * @param x Value to print.
  69646. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69647. * @return GLSL float string.
  69648. */
  69649. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69650. if (decimalFigures === void 0) { decimalFigures = 8; }
  69651. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69652. };
  69653. return BlurPostProcess;
  69654. }(BABYLON.PostProcess));
  69655. BABYLON.BlurPostProcess = BlurPostProcess;
  69656. })(BABYLON || (BABYLON = {}));
  69657. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69658. var BABYLON;
  69659. (function (BABYLON) {
  69660. /**
  69661. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69662. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69663. * based on samples that have a large difference in distance than the center pixel.
  69664. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69665. */
  69666. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69667. __extends(DepthOfFieldBlurPostProcess, _super);
  69668. /**
  69669. * Creates a new instance of @see CircleOfConfusionPostProcess
  69670. * @param name The name of the effect.
  69671. * @param scene The scene the effect belongs to.
  69672. * @param direction The direction the blur should be applied.
  69673. * @param kernel The size of the kernel used to blur.
  69674. * @param options The required width/height ratio to downsize to before computing the render pass.
  69675. * @param camera The camera to apply the render pass to.
  69676. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69677. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69678. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69679. * @param engine The engine which the post process will be applied. (default: current engine)
  69680. * @param reusable If the post process can be reused on the same frame. (default: false)
  69681. * @param textureType Type of textures used when performing the post process. (default: 0)
  69682. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69683. */
  69684. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69685. if (imageToBlur === void 0) { imageToBlur = null; }
  69686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69687. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69688. if (blockCompilation === void 0) { blockCompilation = false; }
  69689. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  69690. _this.direction = direction;
  69691. _this.onApplyObservable.add(function (effect) {
  69692. if (imageToBlur != null) {
  69693. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69694. }
  69695. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69696. if (scene.activeCamera) {
  69697. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69698. }
  69699. });
  69700. return _this;
  69701. }
  69702. return DepthOfFieldBlurPostProcess;
  69703. }(BABYLON.BlurPostProcess));
  69704. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69705. })(BABYLON || (BABYLON = {}));
  69706. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69707. var BABYLON;
  69708. (function (BABYLON) {
  69709. /**
  69710. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69711. */
  69712. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69713. __extends(DepthOfFieldMergePostProcess, _super);
  69714. /**
  69715. * Creates a new instance of @see CircleOfConfusionPostProcess
  69716. * @param name The name of the effect.
  69717. * @param original The non-blurred image to be modified
  69718. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69719. * @param blurSteps Incrimental bluring post processes.
  69720. * @param options The required width/height ratio to downsize to before computing the render pass.
  69721. * @param camera The camera to apply the render pass to.
  69722. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69723. * @param engine The engine which the post process will be applied. (default: current engine)
  69724. * @param reusable If the post process can be reused on the same frame. (default: false)
  69725. * @param textureType Type of textures used when performing the post process. (default: 0)
  69726. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69727. */
  69728. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69729. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69730. if (blockCompilation === void 0) { blockCompilation = false; }
  69731. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69732. _this.blurSteps = blurSteps;
  69733. _this.onApplyObservable.add(function (effect) {
  69734. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69735. effect.setTextureFromPostProcess("originalSampler", original);
  69736. blurSteps.forEach(function (step, index) {
  69737. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  69738. });
  69739. });
  69740. if (!blockCompilation) {
  69741. _this.updateEffect();
  69742. }
  69743. return _this;
  69744. }
  69745. /**
  69746. * Updates the effect with the current post process compile time values and recompiles the shader.
  69747. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69748. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69749. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69750. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  69751. * @param onCompiled Called when the shader has been compiled.
  69752. * @param onError Called if there is an error when compiling a shader.
  69753. */
  69754. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69755. if (defines === void 0) { defines = null; }
  69756. if (uniforms === void 0) { uniforms = null; }
  69757. if (samplers === void 0) { samplers = null; }
  69758. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69759. };
  69760. return DepthOfFieldMergePostProcess;
  69761. }(BABYLON.PostProcess));
  69762. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69763. })(BABYLON || (BABYLON = {}));
  69764. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69765. var BABYLON;
  69766. (function (BABYLON) {
  69767. /**
  69768. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69769. */
  69770. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69771. __extends(CircleOfConfusionPostProcess, _super);
  69772. /**
  69773. * Creates a new instance of @see CircleOfConfusionPostProcess
  69774. * @param name The name of the effect.
  69775. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  69776. * @param options The required width/height ratio to downsize to before computing the render pass.
  69777. * @param camera The camera to apply the render pass to.
  69778. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69779. * @param engine The engine which the post process will be applied. (default: current engine)
  69780. * @param reusable If the post process can be reused on the same frame. (default: false)
  69781. * @param textureType Type of textures used when performing the post process. (default: 0)
  69782. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69783. */
  69784. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69785. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69786. if (blockCompilation === void 0) { blockCompilation = false; }
  69787. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69788. /**
  69789. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  69790. */
  69791. _this.lensSize = 50;
  69792. /**
  69793. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69794. */
  69795. _this.fStop = 1.4;
  69796. /**
  69797. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69798. */
  69799. _this.focusDistance = 2000;
  69800. /**
  69801. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69802. */
  69803. _this.focalLength = 50;
  69804. _this._depthTexture = null;
  69805. _this._depthTexture = depthTexture;
  69806. _this.onApplyObservable.add(function (effect) {
  69807. if (!_this._depthTexture) {
  69808. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69809. return;
  69810. }
  69811. effect.setTexture("depthSampler", _this._depthTexture);
  69812. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  69813. var aperture = _this.lensSize / _this.fStop;
  69814. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  69815. effect.setFloat('focusDistance', _this.focusDistance);
  69816. effect.setFloat('cocPrecalculation', cocPrecalculation);
  69817. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  69818. });
  69819. return _this;
  69820. }
  69821. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  69822. /**
  69823. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69824. */
  69825. set: function (value) {
  69826. this._depthTexture = value;
  69827. },
  69828. enumerable: true,
  69829. configurable: true
  69830. });
  69831. return CircleOfConfusionPostProcess;
  69832. }(BABYLON.PostProcess));
  69833. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  69834. })(BABYLON || (BABYLON = {}));
  69835. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  69836. var BABYLON;
  69837. (function (BABYLON) {
  69838. /**
  69839. * Specifies the level of max blur that should be applied when using the depth of field effect
  69840. */
  69841. var DepthOfFieldEffectBlurLevel;
  69842. (function (DepthOfFieldEffectBlurLevel) {
  69843. /**
  69844. * Subtle blur
  69845. */
  69846. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  69847. /**
  69848. * Medium blur
  69849. */
  69850. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  69851. /**
  69852. * Large blur
  69853. */
  69854. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  69855. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  69856. ;
  69857. /**
  69858. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  69859. */
  69860. var DepthOfFieldEffect = /** @class */ (function (_super) {
  69861. __extends(DepthOfFieldEffect, _super);
  69862. /**
  69863. * Creates a new instance of @see DepthOfFieldEffect
  69864. * @param scene The scene the effect belongs to.
  69865. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  69866. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  69867. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69868. */
  69869. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  69870. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69871. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69872. if (blockCompilation === void 0) { blockCompilation = false; }
  69873. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69874. return _this._effects;
  69875. }, true) || this;
  69876. _this._effects = [];
  69877. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69878. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69879. // Capture circle of confusion texture
  69880. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69881. _this._depthOfFieldPass.autoClear = false;
  69882. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  69883. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69884. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69885. _this._depthOfFieldBlurY = [];
  69886. _this._depthOfFieldBlurX = [];
  69887. var blurCount = 1;
  69888. var kernelSize = 15;
  69889. switch (blurLevel) {
  69890. case DepthOfFieldEffectBlurLevel.High: {
  69891. blurCount = 3;
  69892. kernelSize = 51;
  69893. break;
  69894. }
  69895. case DepthOfFieldEffectBlurLevel.Medium: {
  69896. blurCount = 2;
  69897. kernelSize = 31;
  69898. break;
  69899. }
  69900. default: {
  69901. kernelSize = 15;
  69902. blurCount = 1;
  69903. break;
  69904. }
  69905. }
  69906. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69907. for (var i = 0; i < blurCount; i++) {
  69908. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69909. blurY.autoClear = false;
  69910. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69911. blurX.autoClear = false;
  69912. _this._depthOfFieldBlurY.push(blurY);
  69913. _this._depthOfFieldBlurX.push(blurX);
  69914. }
  69915. // Merge blurred images with original image based on circleOfConfusion
  69916. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69917. _this._depthOfFieldMerge.autoClear = false;
  69918. // Set all post processes on the effect.
  69919. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  69920. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69921. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69922. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69923. }
  69924. _this._effects.push(_this._depthOfFieldMerge);
  69925. return _this;
  69926. }
  69927. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69928. get: function () {
  69929. return this._circleOfConfusion.focalLength;
  69930. },
  69931. /**
  69932. * The focal the length of the camera used in the effect
  69933. */
  69934. set: function (value) {
  69935. this._circleOfConfusion.focalLength = value;
  69936. },
  69937. enumerable: true,
  69938. configurable: true
  69939. });
  69940. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69941. get: function () {
  69942. return this._circleOfConfusion.fStop;
  69943. },
  69944. /**
  69945. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69946. */
  69947. set: function (value) {
  69948. this._circleOfConfusion.fStop = value;
  69949. },
  69950. enumerable: true,
  69951. configurable: true
  69952. });
  69953. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69954. get: function () {
  69955. return this._circleOfConfusion.focusDistance;
  69956. },
  69957. /**
  69958. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69959. */
  69960. set: function (value) {
  69961. this._circleOfConfusion.focusDistance = value;
  69962. },
  69963. enumerable: true,
  69964. configurable: true
  69965. });
  69966. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69967. get: function () {
  69968. return this._circleOfConfusion.lensSize;
  69969. },
  69970. /**
  69971. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  69972. */
  69973. set: function (value) {
  69974. this._circleOfConfusion.lensSize = value;
  69975. },
  69976. enumerable: true,
  69977. configurable: true
  69978. });
  69979. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69980. /**
  69981. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69982. */
  69983. set: function (value) {
  69984. this._circleOfConfusion.depthTexture = value;
  69985. },
  69986. enumerable: true,
  69987. configurable: true
  69988. });
  69989. /**
  69990. * Disposes each of the internal effects for a given camera.
  69991. * @param camera The camera to dispose the effect on.
  69992. */
  69993. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69994. this._depthOfFieldPass.dispose(camera);
  69995. this._circleOfConfusion.dispose(camera);
  69996. this._depthOfFieldBlurX.forEach(function (element) {
  69997. element.dispose(camera);
  69998. });
  69999. this._depthOfFieldBlurY.forEach(function (element) {
  70000. element.dispose(camera);
  70001. });
  70002. this._depthOfFieldMerge.dispose(camera);
  70003. };
  70004. /**
  70005. * Internal
  70006. */
  70007. DepthOfFieldEffect.prototype._updateEffects = function () {
  70008. for (var effect in this._effects) {
  70009. this._effects[effect].updateEffect();
  70010. }
  70011. };
  70012. /**
  70013. * Internal
  70014. * @returns if all the contained post processes are ready.
  70015. */
  70016. DepthOfFieldEffect.prototype._isReady = function () {
  70017. for (var effect in this._effects) {
  70018. if (!this._effects[effect].isReady()) {
  70019. return false;
  70020. }
  70021. }
  70022. return true;
  70023. };
  70024. return DepthOfFieldEffect;
  70025. }(BABYLON.PostProcessRenderEffect));
  70026. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70027. })(BABYLON || (BABYLON = {}));
  70028. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70029. var BABYLON;
  70030. (function (BABYLON) {
  70031. /**
  70032. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70033. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70034. */
  70035. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70036. __extends(DefaultRenderingPipeline, _super);
  70037. /**
  70038. * @constructor
  70039. * @param {string} name - The rendering pipeline name
  70040. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70041. * @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)
  70042. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70043. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70044. */
  70045. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70046. if (automaticBuild === void 0) { automaticBuild = true; }
  70047. var _this = _super.call(this, scene.getEngine(), name) || this;
  70048. _this._originalCameras = [];
  70049. /**
  70050. * ID of the sharpen post process,
  70051. */
  70052. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70053. /**
  70054. * ID of the pass post process used for bloom,
  70055. */
  70056. _this.PassPostProcessId = "PassPostProcessEffect";
  70057. /**
  70058. * ID of the highlight post process used for bloom,
  70059. */
  70060. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  70061. /**
  70062. * ID of the blurX post process used for bloom,
  70063. */
  70064. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  70065. /**
  70066. * ID of the blurY post process used for bloom,
  70067. */
  70068. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  70069. /**
  70070. * ID of the copy back post process used for bloom,
  70071. */
  70072. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  70073. /**
  70074. * ID of the image processing post process;
  70075. */
  70076. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70077. /**
  70078. * ID of the Fast Approximate Anti-Aliasing post process;
  70079. */
  70080. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70081. /**
  70082. * ID of the final merge post process;
  70083. */
  70084. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  70085. /**
  70086. * ID of the chromatic aberration post process,
  70087. */
  70088. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70089. /**
  70090. * Animations which can be used to tweak settings over a period of time
  70091. */
  70092. _this.animations = [];
  70093. // Values
  70094. _this._sharpenEnabled = false;
  70095. _this._bloomEnabled = false;
  70096. _this._depthOfFieldEnabled = false;
  70097. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70098. _this._fxaaEnabled = false;
  70099. _this._msaaEnabled = false;
  70100. _this._imageProcessingEnabled = true;
  70101. _this._bloomScale = 0.6;
  70102. _this._chromaticAberrationEnabled = false;
  70103. _this._buildAllowed = true;
  70104. /**
  70105. * Specifies the size of the bloom blur kernel, relative to the final output size
  70106. */
  70107. _this.bloomKernel = 64;
  70108. /**
  70109. * Specifies the weight of the bloom in the final rendering
  70110. */
  70111. _this._bloomWeight = 0.15;
  70112. _this._prevPostProcess = null;
  70113. _this._prevPrevPostProcess = null;
  70114. _this._cameras = cameras || [];
  70115. _this._originalCameras = _this._cameras.slice();
  70116. _this._buildAllowed = automaticBuild;
  70117. // Initialize
  70118. _this._scene = scene;
  70119. var caps = _this._scene.getEngine().getCaps();
  70120. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70121. // Misc
  70122. if (_this._hdr) {
  70123. if (caps.textureHalfFloatRender) {
  70124. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70125. }
  70126. else if (caps.textureFloatRender) {
  70127. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70128. }
  70129. }
  70130. else {
  70131. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70132. }
  70133. // Attach
  70134. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70135. var engine = _this._scene.getEngine();
  70136. // Create post processes before hand so they can be modified before enabled.
  70137. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70138. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70139. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70140. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70141. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70142. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70143. _this._buildPipeline();
  70144. return _this;
  70145. }
  70146. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70147. get: function () {
  70148. return this._sharpenEnabled;
  70149. },
  70150. /**
  70151. * Enable or disable the sharpen process from the pipeline
  70152. */
  70153. set: function (enabled) {
  70154. if (this._sharpenEnabled === enabled) {
  70155. return;
  70156. }
  70157. this._sharpenEnabled = enabled;
  70158. this._buildPipeline();
  70159. },
  70160. enumerable: true,
  70161. configurable: true
  70162. });
  70163. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70164. get: function () {
  70165. return this._bloomWeight;
  70166. },
  70167. /**
  70168. * The strength of the bloom.
  70169. */
  70170. set: function (value) {
  70171. if (this._bloomWeight === value) {
  70172. return;
  70173. }
  70174. this._bloomWeight = value;
  70175. if (this._hdr && this.copyBack) {
  70176. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  70177. }
  70178. },
  70179. enumerable: true,
  70180. configurable: true
  70181. });
  70182. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70183. get: function () {
  70184. return this._bloomScale;
  70185. },
  70186. /**
  70187. * The scale of the bloom, lower value will provide better performance.
  70188. */
  70189. set: function (value) {
  70190. if (this._bloomScale === value) {
  70191. return;
  70192. }
  70193. this._bloomScale = value;
  70194. this._buildPipeline();
  70195. },
  70196. enumerable: true,
  70197. configurable: true
  70198. });
  70199. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70200. get: function () {
  70201. return this._bloomEnabled;
  70202. },
  70203. /**
  70204. * Enable or disable the bloom from the pipeline
  70205. */
  70206. set: function (enabled) {
  70207. if (this._bloomEnabled === enabled) {
  70208. return;
  70209. }
  70210. this._bloomEnabled = enabled;
  70211. this._buildPipeline();
  70212. },
  70213. enumerable: true,
  70214. configurable: true
  70215. });
  70216. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70217. /**
  70218. * If the depth of field is enabled.
  70219. */
  70220. get: function () {
  70221. return this._depthOfFieldEnabled;
  70222. },
  70223. set: function (enabled) {
  70224. if (this._depthOfFieldEnabled === enabled) {
  70225. return;
  70226. }
  70227. this._depthOfFieldEnabled = enabled;
  70228. this._buildPipeline();
  70229. },
  70230. enumerable: true,
  70231. configurable: true
  70232. });
  70233. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70234. /**
  70235. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70236. */
  70237. get: function () {
  70238. return this._depthOfFieldBlurLevel;
  70239. },
  70240. set: function (value) {
  70241. if (this._depthOfFieldBlurLevel === value) {
  70242. return;
  70243. }
  70244. this._depthOfFieldBlurLevel = value;
  70245. // recreate dof and dispose old as this setting is not dynamic
  70246. var oldDof = this.depthOfField;
  70247. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  70248. this.depthOfField.focalLength = oldDof.focalLength;
  70249. this.depthOfField.focusDistance = oldDof.focusDistance;
  70250. this.depthOfField.fStop = oldDof.fStop;
  70251. this.depthOfField.lensSize = oldDof.lensSize;
  70252. for (var i = 0; i < this._cameras.length; i++) {
  70253. oldDof.disposeEffects(this._cameras[i]);
  70254. }
  70255. this._buildPipeline();
  70256. },
  70257. enumerable: true,
  70258. configurable: true
  70259. });
  70260. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70261. get: function () {
  70262. return this._fxaaEnabled;
  70263. },
  70264. /**
  70265. * If the anti aliasing is enabled.
  70266. */
  70267. set: function (enabled) {
  70268. if (this._fxaaEnabled === enabled) {
  70269. return;
  70270. }
  70271. this._fxaaEnabled = enabled;
  70272. this._buildPipeline();
  70273. },
  70274. enumerable: true,
  70275. configurable: true
  70276. });
  70277. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  70278. get: function () {
  70279. return this._msaaEnabled;
  70280. },
  70281. /**
  70282. * If the multisample anti-aliasing is enabled.
  70283. */
  70284. set: function (enabled) {
  70285. if (this._msaaEnabled === enabled) {
  70286. return;
  70287. }
  70288. this._msaaEnabled = enabled;
  70289. this._buildPipeline();
  70290. },
  70291. enumerable: true,
  70292. configurable: true
  70293. });
  70294. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70295. get: function () {
  70296. return this._imageProcessingEnabled;
  70297. },
  70298. /**
  70299. * If image processing is enabled.
  70300. */
  70301. set: function (enabled) {
  70302. if (this._imageProcessingEnabled === enabled) {
  70303. return;
  70304. }
  70305. this._imageProcessingEnabled = enabled;
  70306. this._buildPipeline();
  70307. },
  70308. enumerable: true,
  70309. configurable: true
  70310. });
  70311. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  70312. get: function () {
  70313. return this._chromaticAberrationEnabled;
  70314. },
  70315. /**
  70316. * Enable or disable the chromaticAberration process from the pipeline
  70317. */
  70318. set: function (enabled) {
  70319. if (this._chromaticAberrationEnabled === enabled) {
  70320. return;
  70321. }
  70322. this._chromaticAberrationEnabled = enabled;
  70323. this._buildPipeline();
  70324. },
  70325. enumerable: true,
  70326. configurable: true
  70327. });
  70328. /**
  70329. * Force the compilation of the entire pipeline.
  70330. */
  70331. DefaultRenderingPipeline.prototype.prepare = function () {
  70332. var previousState = this._buildAllowed;
  70333. this._buildAllowed = true;
  70334. this._buildPipeline();
  70335. this._buildAllowed = previousState;
  70336. };
  70337. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70338. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70339. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70340. postProcess.autoClear = false;
  70341. }
  70342. else {
  70343. postProcess.autoClear = true;
  70344. }
  70345. if (!skipTextureSharing) {
  70346. if (this._prevPrevPostProcess) {
  70347. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70348. }
  70349. else {
  70350. postProcess.useOwnOutput();
  70351. }
  70352. if (this._prevPostProcess) {
  70353. this._prevPrevPostProcess = this._prevPostProcess;
  70354. }
  70355. this._prevPostProcess = postProcess;
  70356. }
  70357. };
  70358. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70359. var _this = this;
  70360. if (!this._buildAllowed) {
  70361. return;
  70362. }
  70363. var engine = this._scene.getEngine();
  70364. this._disposePostProcesses();
  70365. if (this._cameras !== null) {
  70366. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70367. // get back cameras to be used to reattach pipeline
  70368. this._cameras = this._originalCameras.slice();
  70369. }
  70370. this._reset();
  70371. this._prevPostProcess = null;
  70372. this._prevPrevPostProcess = null;
  70373. if (this.sharpenEnabled) {
  70374. if (!this.sharpen.isReady()) {
  70375. this.sharpen.updateEffect();
  70376. }
  70377. this.addEffect(this._sharpenEffect);
  70378. this._setAutoClearAndTextureSharing(this.sharpen);
  70379. }
  70380. if (this.depthOfFieldEnabled) {
  70381. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70382. this.depthOfField.depthTexture = depthTexture;
  70383. if (!this.depthOfField._isReady()) {
  70384. this.depthOfField._updateEffects();
  70385. }
  70386. this.addEffect(this.depthOfField);
  70387. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70388. }
  70389. if (this.bloomEnabled) {
  70390. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70391. this._setAutoClearAndTextureSharing(this.pass, true);
  70392. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70393. if (!this._hdr) {
  70394. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70395. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70396. this.highlights.autoClear = false;
  70397. this.highlights.alwaysForcePOT = true;
  70398. }
  70399. 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);
  70400. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70401. this.blurX.alwaysForcePOT = true;
  70402. this.blurX.autoClear = false;
  70403. this.blurX.onActivateObservable.add(function () {
  70404. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70405. _this.blurX.kernel = _this.bloomKernel * dw;
  70406. });
  70407. 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);
  70408. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70409. this.blurY.alwaysForcePOT = true;
  70410. this.blurY.autoClear = false;
  70411. this.blurY.onActivateObservable.add(function () {
  70412. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70413. _this.blurY.kernel = _this.bloomKernel * dh;
  70414. });
  70415. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70416. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  70417. this.copyBack.alwaysForcePOT = true;
  70418. if (this._hdr) {
  70419. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  70420. var w = this.bloomWeight;
  70421. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  70422. }
  70423. else {
  70424. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  70425. }
  70426. this.copyBack.autoClear = false;
  70427. }
  70428. if (this._imageProcessingEnabled) {
  70429. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70430. if (this._hdr) {
  70431. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  70432. }
  70433. else {
  70434. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  70435. }
  70436. }
  70437. if (this._hdr && this.imageProcessing) {
  70438. this.finalMerge = this.imageProcessing;
  70439. }
  70440. else {
  70441. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70442. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  70443. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  70444. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  70445. }
  70446. if (this.bloomEnabled) {
  70447. if (this._hdr) {
  70448. this.copyBack.shareOutputWith(this.blurX);
  70449. if (this.imageProcessing) {
  70450. this.imageProcessing.shareOutputWith(this.pass);
  70451. this.imageProcessing.autoClear = false;
  70452. }
  70453. else {
  70454. this.finalMerge.shareOutputWith(this.pass);
  70455. }
  70456. }
  70457. else {
  70458. this.finalMerge.shareOutputWith(this.pass);
  70459. }
  70460. }
  70461. if (this.fxaaEnabled) {
  70462. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70463. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  70464. this._setAutoClearAndTextureSharing(this.fxaa);
  70465. }
  70466. if (this.chromaticAberrationEnabled) {
  70467. if (!this.chromaticAberration.isReady()) {
  70468. this.chromaticAberration.updateEffect();
  70469. }
  70470. this.addEffect(this._chromaticAberrationEffect);
  70471. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  70472. }
  70473. if (this._cameras !== null) {
  70474. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70475. }
  70476. if (this.msaaEnabled) {
  70477. if (!this._enableMSAAOnFirstPostProcess()) {
  70478. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  70479. }
  70480. }
  70481. };
  70482. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  70483. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  70484. for (var i = 0; i < this._cameras.length; i++) {
  70485. var camera = this._cameras[i];
  70486. if (this.pass) {
  70487. this.pass.dispose(camera);
  70488. }
  70489. if (this.highlights) {
  70490. this.highlights.dispose(camera);
  70491. }
  70492. if (this.blurX) {
  70493. this.blurX.dispose(camera);
  70494. }
  70495. if (this.blurY) {
  70496. this.blurY.dispose(camera);
  70497. }
  70498. if (this.copyBack) {
  70499. this.copyBack.dispose(camera);
  70500. }
  70501. if (this.imageProcessing) {
  70502. this.imageProcessing.dispose(camera);
  70503. }
  70504. if (this.fxaa) {
  70505. this.fxaa.dispose(camera);
  70506. }
  70507. if (this.finalMerge) {
  70508. this.finalMerge.dispose(camera);
  70509. }
  70510. // These are created in the constructor and should not be disposed on every pipeline change
  70511. if (disposeNonRecreated) {
  70512. if (this.sharpen) {
  70513. this.sharpen.dispose(camera);
  70514. }
  70515. if (this.depthOfField) {
  70516. this.depthOfField.disposeEffects(camera);
  70517. }
  70518. if (this.chromaticAberration) {
  70519. this.chromaticAberration.dispose(camera);
  70520. }
  70521. }
  70522. }
  70523. this.pass = null;
  70524. this.highlights = null;
  70525. this.blurX = null;
  70526. this.blurY = null;
  70527. this.copyBack = null;
  70528. this.imageProcessing = null;
  70529. this.fxaa = null;
  70530. this.finalMerge = null;
  70531. if (disposeNonRecreated) {
  70532. this.sharpen = null;
  70533. this.depthOfField = null;
  70534. this.chromaticAberration = null;
  70535. }
  70536. };
  70537. /**
  70538. * Dispose of the pipeline and stop all post processes
  70539. */
  70540. DefaultRenderingPipeline.prototype.dispose = function () {
  70541. this._disposePostProcesses(true);
  70542. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70543. _super.prototype.dispose.call(this);
  70544. };
  70545. /**
  70546. * Serialize the rendering pipeline (Used when exporting)
  70547. * @returns the serialized object
  70548. */
  70549. DefaultRenderingPipeline.prototype.serialize = function () {
  70550. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70551. serializationObject.customType = "DefaultRenderingPipeline";
  70552. return serializationObject;
  70553. };
  70554. /**
  70555. * Parse the serialized pipeline
  70556. * @param source Source pipeline.
  70557. * @param scene The scene to load the pipeline to.
  70558. * @param rootUrl The URL of the serialized pipeline.
  70559. * @returns An instantiated pipeline from the serialized object.
  70560. */
  70561. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70562. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70563. };
  70564. __decorate([
  70565. BABYLON.serialize()
  70566. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70567. __decorate([
  70568. BABYLON.serialize()
  70569. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70570. __decorate([
  70571. BABYLON.serialize()
  70572. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70573. __decorate([
  70574. BABYLON.serialize()
  70575. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70576. __decorate([
  70577. BABYLON.serialize()
  70578. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70579. __decorate([
  70580. BABYLON.serialize()
  70581. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70582. __decorate([
  70583. BABYLON.serialize()
  70584. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70585. __decorate([
  70586. BABYLON.serialize()
  70587. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70588. __decorate([
  70589. BABYLON.serialize()
  70590. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70591. __decorate([
  70592. BABYLON.serialize()
  70593. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70594. __decorate([
  70595. BABYLON.serialize()
  70596. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70597. __decorate([
  70598. BABYLON.serialize()
  70599. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  70600. __decorate([
  70601. BABYLON.serialize()
  70602. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  70603. return DefaultRenderingPipeline;
  70604. }(BABYLON.PostProcessRenderPipeline));
  70605. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  70606. })(BABYLON || (BABYLON = {}));
  70607. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  70608. var BABYLON;
  70609. (function (BABYLON) {
  70610. /**
  70611. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  70612. */
  70613. var GeometryBufferRenderer = /** @class */ (function () {
  70614. /**
  70615. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  70616. * @param scene The scene the buffer belongs to
  70617. * @param ratio How big is the buffer related to the main canvas.
  70618. */
  70619. function GeometryBufferRenderer(scene, ratio) {
  70620. if (ratio === void 0) { ratio = 1; }
  70621. this._enablePosition = false;
  70622. this._scene = scene;
  70623. this._ratio = ratio;
  70624. // Render target
  70625. this._createRenderTargets();
  70626. }
  70627. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70628. /**
  70629. * Set the render list (meshes to be rendered) used in the G buffer.
  70630. */
  70631. set: function (meshes) {
  70632. this._multiRenderTarget.renderList = meshes;
  70633. },
  70634. enumerable: true,
  70635. configurable: true
  70636. });
  70637. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70638. /**
  70639. * Gets wether or not G buffer are supported by the running hardware.
  70640. * This requires draw buffer supports
  70641. */
  70642. get: function () {
  70643. return this._multiRenderTarget.isSupported;
  70644. },
  70645. enumerable: true,
  70646. configurable: true
  70647. });
  70648. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70649. /**
  70650. * Gets wether or not position are enabled for the G buffer.
  70651. */
  70652. get: function () {
  70653. return this._enablePosition;
  70654. },
  70655. /**
  70656. * Sets wether or not position are enabled for the G buffer.
  70657. */
  70658. set: function (enable) {
  70659. this._enablePosition = enable;
  70660. this.dispose();
  70661. this._createRenderTargets();
  70662. },
  70663. enumerable: true,
  70664. configurable: true
  70665. });
  70666. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70667. /**
  70668. * Gets the scene associated with the buffer.
  70669. */
  70670. get: function () {
  70671. return this._scene;
  70672. },
  70673. enumerable: true,
  70674. configurable: true
  70675. });
  70676. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70677. /**
  70678. * Gets the ratio used by the buffer during its creation.
  70679. * How big is the buffer related to the main canvas.
  70680. */
  70681. get: function () {
  70682. return this._ratio;
  70683. },
  70684. enumerable: true,
  70685. configurable: true
  70686. });
  70687. /**
  70688. * Checks wether everything is ready to render a submesh to the G buffer.
  70689. * @param subMesh the submesh to check readiness for
  70690. * @param useInstances is the mesh drawn using instance or not
  70691. * @returns true if ready otherwise false
  70692. */
  70693. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70694. var material = subMesh.getMaterial();
  70695. if (material && material.disableDepthWrite) {
  70696. return false;
  70697. }
  70698. var defines = [];
  70699. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70700. var mesh = subMesh.getMesh();
  70701. // Alpha test
  70702. if (material && material.needAlphaTesting()) {
  70703. defines.push("#define ALPHATEST");
  70704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70705. attribs.push(BABYLON.VertexBuffer.UVKind);
  70706. defines.push("#define UV1");
  70707. }
  70708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70709. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70710. defines.push("#define UV2");
  70711. }
  70712. }
  70713. // Buffers
  70714. if (this._enablePosition) {
  70715. defines.push("#define POSITION");
  70716. }
  70717. // Bones
  70718. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70719. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70720. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70721. if (mesh.numBoneInfluencers > 4) {
  70722. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70723. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70724. }
  70725. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70726. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70727. }
  70728. else {
  70729. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70730. }
  70731. // Instances
  70732. if (useInstances) {
  70733. defines.push("#define INSTANCES");
  70734. attribs.push("world0");
  70735. attribs.push("world1");
  70736. attribs.push("world2");
  70737. attribs.push("world3");
  70738. }
  70739. // Get correct effect
  70740. var join = defines.join("\n");
  70741. if (this._cachedDefines !== join) {
  70742. this._cachedDefines = join;
  70743. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  70744. }
  70745. return this._effect.isReady();
  70746. };
  70747. /**
  70748. * Gets the current underlying G Buffer.
  70749. * @returns the buffer
  70750. */
  70751. GeometryBufferRenderer.prototype.getGBuffer = function () {
  70752. return this._multiRenderTarget;
  70753. };
  70754. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70755. /**
  70756. * Gets the number of samples used to render the buffer (anti aliasing).
  70757. */
  70758. get: function () {
  70759. return this._multiRenderTarget.samples;
  70760. },
  70761. /**
  70762. * Sets the number of samples used to render the buffer (anti aliasing).
  70763. */
  70764. set: function (value) {
  70765. this._multiRenderTarget.samples = value;
  70766. },
  70767. enumerable: true,
  70768. configurable: true
  70769. });
  70770. /**
  70771. * Disposes the renderer and frees up associated resources.
  70772. */
  70773. GeometryBufferRenderer.prototype.dispose = function () {
  70774. this.getGBuffer().dispose();
  70775. };
  70776. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70777. var _this = this;
  70778. var engine = this._scene.getEngine();
  70779. var count = this._enablePosition ? 3 : 2;
  70780. 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 });
  70781. if (!this.isSupported) {
  70782. return;
  70783. }
  70784. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70785. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70786. this._multiRenderTarget.refreshRate = 1;
  70787. this._multiRenderTarget.renderParticles = false;
  70788. this._multiRenderTarget.renderList = null;
  70789. // set default depth value to 1.0 (far away)
  70790. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70791. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70792. });
  70793. // Custom render function
  70794. var renderSubMesh = function (subMesh) {
  70795. var mesh = subMesh.getRenderingMesh();
  70796. var scene = _this._scene;
  70797. var engine = scene.getEngine();
  70798. var material = subMesh.getMaterial();
  70799. if (!material) {
  70800. return;
  70801. }
  70802. // Culling
  70803. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70804. // Managing instances
  70805. var batch = mesh._getInstancesRenderList(subMesh._id);
  70806. if (batch.mustReturn) {
  70807. return;
  70808. }
  70809. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70810. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70811. engine.enableEffect(_this._effect);
  70812. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70813. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70814. _this._effect.setMatrix("view", scene.getViewMatrix());
  70815. // Alpha test
  70816. if (material && material.needAlphaTesting()) {
  70817. var alphaTexture = material.getAlphaTestTexture();
  70818. if (alphaTexture) {
  70819. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70820. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70821. }
  70822. }
  70823. // Bones
  70824. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70825. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70826. }
  70827. // Draw
  70828. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70829. }
  70830. };
  70831. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70832. var index;
  70833. if (depthOnlySubMeshes.length) {
  70834. engine.setColorWrite(false);
  70835. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70836. renderSubMesh(depthOnlySubMeshes.data[index]);
  70837. }
  70838. engine.setColorWrite(true);
  70839. }
  70840. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70841. renderSubMesh(opaqueSubMeshes.data[index]);
  70842. }
  70843. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70844. renderSubMesh(alphaTestSubMeshes.data[index]);
  70845. }
  70846. };
  70847. };
  70848. return GeometryBufferRenderer;
  70849. }());
  70850. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  70851. })(BABYLON || (BABYLON = {}));
  70852. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  70853. var BABYLON;
  70854. (function (BABYLON) {
  70855. var RefractionPostProcess = /** @class */ (function (_super) {
  70856. __extends(RefractionPostProcess, _super);
  70857. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  70858. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  70859. _this.color = color;
  70860. _this.depth = depth;
  70861. _this.colorLevel = colorLevel;
  70862. _this._ownRefractionTexture = true;
  70863. _this.onActivateObservable.add(function (cam) {
  70864. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  70865. });
  70866. _this.onApplyObservable.add(function (effect) {
  70867. effect.setColor3("baseColor", _this.color);
  70868. effect.setFloat("depth", _this.depth);
  70869. effect.setFloat("colorLevel", _this.colorLevel);
  70870. effect.setTexture("refractionSampler", _this._refTexture);
  70871. });
  70872. return _this;
  70873. }
  70874. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  70875. /**
  70876. * Gets or sets the refraction texture
  70877. * Please note that you are responsible for disposing the texture if you set it manually
  70878. */
  70879. get: function () {
  70880. return this._refTexture;
  70881. },
  70882. set: function (value) {
  70883. if (this._refTexture && this._ownRefractionTexture) {
  70884. this._refTexture.dispose();
  70885. }
  70886. this._refTexture = value;
  70887. this._ownRefractionTexture = false;
  70888. },
  70889. enumerable: true,
  70890. configurable: true
  70891. });
  70892. // Methods
  70893. RefractionPostProcess.prototype.dispose = function (camera) {
  70894. if (this._refTexture && this._ownRefractionTexture) {
  70895. this._refTexture.dispose();
  70896. this._refTexture = null;
  70897. }
  70898. _super.prototype.dispose.call(this, camera);
  70899. };
  70900. return RefractionPostProcess;
  70901. }(BABYLON.PostProcess));
  70902. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70903. })(BABYLON || (BABYLON = {}));
  70904. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70905. var BABYLON;
  70906. (function (BABYLON) {
  70907. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70908. __extends(BlackAndWhitePostProcess, _super);
  70909. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70910. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70911. _this.degree = 1;
  70912. _this.onApplyObservable.add(function (effect) {
  70913. effect.setFloat("degree", _this.degree);
  70914. });
  70915. return _this;
  70916. }
  70917. return BlackAndWhitePostProcess;
  70918. }(BABYLON.PostProcess));
  70919. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70920. })(BABYLON || (BABYLON = {}));
  70921. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70922. var BABYLON;
  70923. (function (BABYLON) {
  70924. /**
  70925. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70926. * input texture to perform effects such as edge detection or sharpening
  70927. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70928. */
  70929. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70930. __extends(ConvolutionPostProcess, _super);
  70931. /**
  70932. * Creates a new instance of @see ConvolutionPostProcess
  70933. * @param name The name of the effect.
  70934. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  70935. * @param options The required width/height ratio to downsize to before computing the render pass.
  70936. * @param camera The camera to apply the render pass to.
  70937. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70938. * @param engine The engine which the post process will be applied. (default: current engine)
  70939. * @param reusable If the post process can be reused on the same frame. (default: false)
  70940. * @param textureType Type of textures used when performing the post process. (default: 0)
  70941. */
  70942. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70943. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70944. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70945. _this.kernel = kernel;
  70946. _this.onApply = function (effect) {
  70947. effect.setFloat2("screenSize", _this.width, _this.height);
  70948. effect.setArray("kernel", _this.kernel);
  70949. };
  70950. return _this;
  70951. }
  70952. // Statics
  70953. /**
  70954. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70955. */
  70956. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70957. /**
  70958. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70959. */
  70960. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70961. /**
  70962. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70963. */
  70964. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70965. /**
  70966. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70967. */
  70968. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70969. /**
  70970. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70971. */
  70972. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70973. /**
  70974. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70975. */
  70976. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70977. return ConvolutionPostProcess;
  70978. }(BABYLON.PostProcess));
  70979. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70980. })(BABYLON || (BABYLON = {}));
  70981. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70982. var BABYLON;
  70983. (function (BABYLON) {
  70984. var FilterPostProcess = /** @class */ (function (_super) {
  70985. __extends(FilterPostProcess, _super);
  70986. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70987. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70988. _this.kernelMatrix = kernelMatrix;
  70989. _this.onApply = function (effect) {
  70990. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70991. };
  70992. return _this;
  70993. }
  70994. return FilterPostProcess;
  70995. }(BABYLON.PostProcess));
  70996. BABYLON.FilterPostProcess = FilterPostProcess;
  70997. })(BABYLON || (BABYLON = {}));
  70998. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70999. var BABYLON;
  71000. (function (BABYLON) {
  71001. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71002. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71003. __extends(VolumetricLightScatteringPostProcess, _super);
  71004. /**
  71005. * @constructor
  71006. * @param {string} name - The post-process name
  71007. * @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)
  71008. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71009. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71010. * @param {number} samples - The post-process quality, default 100
  71011. * @param {number} samplingMode - The post-process filtering mode
  71012. * @param {BABYLON.Engine} engine - The babylon engine
  71013. * @param {boolean} reusable - If the post-process is reusable
  71014. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71015. */
  71016. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71017. if (samples === void 0) { samples = 100; }
  71018. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71019. 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;
  71020. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71021. /**
  71022. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71023. * @type {Vector3}
  71024. */
  71025. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71026. /**
  71027. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71028. * @type {boolean}
  71029. */
  71030. _this.useCustomMeshPosition = false;
  71031. /**
  71032. * If the post-process should inverse the light scattering direction
  71033. * @type {boolean}
  71034. */
  71035. _this.invert = true;
  71036. /**
  71037. * Array containing the excluded meshes not rendered in the internal pass
  71038. */
  71039. _this.excludedMeshes = new Array();
  71040. /**
  71041. * Controls the overall intensity of the post-process
  71042. * @type {number}
  71043. */
  71044. _this.exposure = 0.3;
  71045. /**
  71046. * Dissipates each sample's contribution in range [0, 1]
  71047. * @type {number}
  71048. */
  71049. _this.decay = 0.96815;
  71050. /**
  71051. * Controls the overall intensity of each sample
  71052. * @type {number}
  71053. */
  71054. _this.weight = 0.58767;
  71055. /**
  71056. * Controls the density of each sample
  71057. * @type {number}
  71058. */
  71059. _this.density = 0.926;
  71060. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71061. engine = scene.getEngine();
  71062. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71063. // Configure mesh
  71064. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71065. // Configure
  71066. _this._createPass(scene, ratio.passRatio || ratio);
  71067. _this.onActivate = function (camera) {
  71068. if (!_this.isSupported) {
  71069. _this.dispose(camera);
  71070. }
  71071. _this.onActivate = null;
  71072. };
  71073. _this.onApplyObservable.add(function (effect) {
  71074. _this._updateMeshScreenCoordinates(scene);
  71075. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71076. effect.setFloat("exposure", _this.exposure);
  71077. effect.setFloat("decay", _this.decay);
  71078. effect.setFloat("weight", _this.weight);
  71079. effect.setFloat("density", _this.density);
  71080. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71081. });
  71082. return _this;
  71083. }
  71084. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71085. get: function () {
  71086. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71087. return false;
  71088. },
  71089. set: function (useDiffuseColor) {
  71090. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71091. },
  71092. enumerable: true,
  71093. configurable: true
  71094. });
  71095. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71096. return "VolumetricLightScatteringPostProcess";
  71097. };
  71098. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71099. var mesh = subMesh.getMesh();
  71100. // Render this.mesh as default
  71101. if (mesh === this.mesh && mesh.material) {
  71102. return mesh.material.isReady(mesh);
  71103. }
  71104. var defines = [];
  71105. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71106. var material = subMesh.getMaterial();
  71107. // Alpha test
  71108. if (material) {
  71109. if (material.needAlphaTesting()) {
  71110. defines.push("#define ALPHATEST");
  71111. }
  71112. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71113. attribs.push(BABYLON.VertexBuffer.UVKind);
  71114. defines.push("#define UV1");
  71115. }
  71116. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71117. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71118. defines.push("#define UV2");
  71119. }
  71120. }
  71121. // Bones
  71122. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71123. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71124. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71125. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71126. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71127. }
  71128. else {
  71129. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71130. }
  71131. // Instances
  71132. if (useInstances) {
  71133. defines.push("#define INSTANCES");
  71134. attribs.push("world0");
  71135. attribs.push("world1");
  71136. attribs.push("world2");
  71137. attribs.push("world3");
  71138. }
  71139. // Get correct effect
  71140. var join = defines.join("\n");
  71141. if (this._cachedDefines !== join) {
  71142. this._cachedDefines = join;
  71143. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71144. }
  71145. return this._volumetricLightScatteringPass.isReady();
  71146. };
  71147. /**
  71148. * Sets the new light position for light scattering effect
  71149. * @param {BABYLON.Vector3} The new custom light position
  71150. */
  71151. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71152. this.customMeshPosition = position;
  71153. };
  71154. /**
  71155. * Returns the light position for light scattering effect
  71156. * @return {BABYLON.Vector3} The custom light position
  71157. */
  71158. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71159. return this.customMeshPosition;
  71160. };
  71161. /**
  71162. * Disposes the internal assets and detaches the post-process from the camera
  71163. */
  71164. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71165. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71166. if (rttIndex !== -1) {
  71167. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71168. }
  71169. this._volumetricLightScatteringRTT.dispose();
  71170. _super.prototype.dispose.call(this, camera);
  71171. };
  71172. /**
  71173. * Returns the render target texture used by the post-process
  71174. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71175. */
  71176. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71177. return this._volumetricLightScatteringRTT;
  71178. };
  71179. // Private methods
  71180. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71181. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71182. return true;
  71183. }
  71184. return false;
  71185. };
  71186. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71187. var _this = this;
  71188. var engine = scene.getEngine();
  71189. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71190. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71191. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71192. this._volumetricLightScatteringRTT.renderList = null;
  71193. this._volumetricLightScatteringRTT.renderParticles = false;
  71194. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71195. var camera = this.getCamera();
  71196. if (camera) {
  71197. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71198. }
  71199. else {
  71200. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71201. }
  71202. // Custom render function for submeshes
  71203. var renderSubMesh = function (subMesh) {
  71204. var mesh = subMesh.getRenderingMesh();
  71205. if (_this._meshExcluded(mesh)) {
  71206. return;
  71207. }
  71208. var material = subMesh.getMaterial();
  71209. if (!material) {
  71210. return;
  71211. }
  71212. var scene = mesh.getScene();
  71213. var engine = scene.getEngine();
  71214. // Culling
  71215. engine.setState(material.backFaceCulling);
  71216. // Managing instances
  71217. var batch = mesh._getInstancesRenderList(subMesh._id);
  71218. if (batch.mustReturn) {
  71219. return;
  71220. }
  71221. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71222. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71223. var effect = _this._volumetricLightScatteringPass;
  71224. if (mesh === _this.mesh) {
  71225. if (subMesh.effect) {
  71226. effect = subMesh.effect;
  71227. }
  71228. else {
  71229. effect = material.getEffect();
  71230. }
  71231. }
  71232. engine.enableEffect(effect);
  71233. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71234. if (mesh === _this.mesh) {
  71235. material.bind(mesh.getWorldMatrix(), mesh);
  71236. }
  71237. else {
  71238. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71239. // Alpha test
  71240. if (material && material.needAlphaTesting()) {
  71241. var alphaTexture = material.getAlphaTestTexture();
  71242. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71243. if (alphaTexture) {
  71244. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71245. }
  71246. }
  71247. // Bones
  71248. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71249. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71250. }
  71251. }
  71252. // Draw
  71253. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71254. }
  71255. };
  71256. // Render target texture callbacks
  71257. var savedSceneClearColor;
  71258. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71259. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71260. savedSceneClearColor = scene.clearColor;
  71261. scene.clearColor = sceneClearColor;
  71262. });
  71263. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71264. scene.clearColor = savedSceneClearColor;
  71265. });
  71266. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71267. var engine = scene.getEngine();
  71268. var index;
  71269. if (depthOnlySubMeshes.length) {
  71270. engine.setColorWrite(false);
  71271. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71272. renderSubMesh(depthOnlySubMeshes.data[index]);
  71273. }
  71274. engine.setColorWrite(true);
  71275. }
  71276. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71277. renderSubMesh(opaqueSubMeshes.data[index]);
  71278. }
  71279. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71280. renderSubMesh(alphaTestSubMeshes.data[index]);
  71281. }
  71282. if (transparentSubMeshes.length) {
  71283. // Sort sub meshes
  71284. for (index = 0; index < transparentSubMeshes.length; index++) {
  71285. var submesh = transparentSubMeshes.data[index];
  71286. var boundingInfo = submesh.getBoundingInfo();
  71287. if (boundingInfo && scene.activeCamera) {
  71288. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71289. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71290. }
  71291. }
  71292. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71293. sortedArray.sort(function (a, b) {
  71294. // Alpha index first
  71295. if (a._alphaIndex > b._alphaIndex) {
  71296. return 1;
  71297. }
  71298. if (a._alphaIndex < b._alphaIndex) {
  71299. return -1;
  71300. }
  71301. // Then distance to camera
  71302. if (a._distanceToCamera < b._distanceToCamera) {
  71303. return 1;
  71304. }
  71305. if (a._distanceToCamera > b._distanceToCamera) {
  71306. return -1;
  71307. }
  71308. return 0;
  71309. });
  71310. // Render sub meshes
  71311. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71312. for (index = 0; index < sortedArray.length; index++) {
  71313. renderSubMesh(sortedArray[index]);
  71314. }
  71315. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71316. }
  71317. };
  71318. };
  71319. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71320. var transform = scene.getTransformMatrix();
  71321. var meshPosition;
  71322. if (this.useCustomMeshPosition) {
  71323. meshPosition = this.customMeshPosition;
  71324. }
  71325. else if (this.attachedNode) {
  71326. meshPosition = this.attachedNode.position;
  71327. }
  71328. else {
  71329. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  71330. }
  71331. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  71332. this._screenCoordinates.x = pos.x / this._viewPort.width;
  71333. this._screenCoordinates.y = pos.y / this._viewPort.height;
  71334. if (this.invert)
  71335. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  71336. };
  71337. // Static methods
  71338. /**
  71339. * Creates a default mesh for the Volumeric Light Scattering post-process
  71340. * @param {string} The mesh name
  71341. * @param {BABYLON.Scene} The scene where to create the mesh
  71342. * @return {BABYLON.Mesh} the default mesh
  71343. */
  71344. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71345. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71346. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71347. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71348. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71349. mesh.material = material;
  71350. return mesh;
  71351. };
  71352. __decorate([
  71353. BABYLON.serializeAsVector3()
  71354. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71355. __decorate([
  71356. BABYLON.serialize()
  71357. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71358. __decorate([
  71359. BABYLON.serialize()
  71360. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71361. __decorate([
  71362. BABYLON.serializeAsMeshReference()
  71363. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71364. __decorate([
  71365. BABYLON.serialize()
  71366. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71367. __decorate([
  71368. BABYLON.serialize()
  71369. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71370. __decorate([
  71371. BABYLON.serialize()
  71372. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71373. __decorate([
  71374. BABYLON.serialize()
  71375. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71376. __decorate([
  71377. BABYLON.serialize()
  71378. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71379. return VolumetricLightScatteringPostProcess;
  71380. }(BABYLON.PostProcess));
  71381. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71382. })(BABYLON || (BABYLON = {}));
  71383. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71384. //
  71385. // This post-process allows the modification of rendered colors by using
  71386. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71387. //
  71388. // The object needs to be provided an url to a texture containing the color
  71389. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71390. // Use an image editing software to tweak the LUT to match your needs.
  71391. //
  71392. // For an example of a color LUT, see here:
  71393. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71394. // For explanations on color grading, see here:
  71395. // http://udn.epicgames.com/Three/ColorGrading.html
  71396. //
  71397. var BABYLON;
  71398. (function (BABYLON) {
  71399. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71400. __extends(ColorCorrectionPostProcess, _super);
  71401. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71402. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71403. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71404. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71405. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71406. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71407. _this.onApply = function (effect) {
  71408. effect.setTexture("colorTable", _this._colorTableTexture);
  71409. };
  71410. return _this;
  71411. }
  71412. return ColorCorrectionPostProcess;
  71413. }(BABYLON.PostProcess));
  71414. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  71415. })(BABYLON || (BABYLON = {}));
  71416. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  71417. var BABYLON;
  71418. (function (BABYLON) {
  71419. var TonemappingOperator;
  71420. (function (TonemappingOperator) {
  71421. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  71422. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  71423. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  71424. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  71425. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  71426. ;
  71427. var TonemapPostProcess = /** @class */ (function (_super) {
  71428. __extends(TonemapPostProcess, _super);
  71429. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  71430. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71431. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71432. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  71433. _this._operator = _operator;
  71434. _this.exposureAdjustment = exposureAdjustment;
  71435. var defines = "#define ";
  71436. if (_this._operator === TonemappingOperator.Hable)
  71437. defines += "HABLE_TONEMAPPING";
  71438. else if (_this._operator === TonemappingOperator.Reinhard)
  71439. defines += "REINHARD_TONEMAPPING";
  71440. else if (_this._operator === TonemappingOperator.HejiDawson)
  71441. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  71442. else if (_this._operator === TonemappingOperator.Photographic)
  71443. defines += "PHOTOGRAPHIC_TONEMAPPING";
  71444. //sadly a second call to create the effect.
  71445. _this.updateEffect(defines);
  71446. _this.onApply = function (effect) {
  71447. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  71448. };
  71449. return _this;
  71450. }
  71451. return TonemapPostProcess;
  71452. }(BABYLON.PostProcess));
  71453. BABYLON.TonemapPostProcess = TonemapPostProcess;
  71454. })(BABYLON || (BABYLON = {}));
  71455. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  71456. var BABYLON;
  71457. (function (BABYLON) {
  71458. var DisplayPassPostProcess = /** @class */ (function (_super) {
  71459. __extends(DisplayPassPostProcess, _super);
  71460. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  71461. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  71462. }
  71463. return DisplayPassPostProcess;
  71464. }(BABYLON.PostProcess));
  71465. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  71466. })(BABYLON || (BABYLON = {}));
  71467. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  71468. var BABYLON;
  71469. (function (BABYLON) {
  71470. var HighlightsPostProcess = /** @class */ (function (_super) {
  71471. __extends(HighlightsPostProcess, _super);
  71472. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  71473. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71474. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71475. }
  71476. return HighlightsPostProcess;
  71477. }(BABYLON.PostProcess));
  71478. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  71479. })(BABYLON || (BABYLON = {}));
  71480. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  71481. var BABYLON;
  71482. (function (BABYLON) {
  71483. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  71484. __extends(ImageProcessingPostProcess, _super);
  71485. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  71486. if (camera === void 0) { camera = null; }
  71487. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71488. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  71489. _this._fromLinearSpace = true;
  71490. /**
  71491. * Defines cache preventing GC.
  71492. */
  71493. _this._defines = {
  71494. IMAGEPROCESSING: false,
  71495. VIGNETTE: false,
  71496. VIGNETTEBLENDMODEMULTIPLY: false,
  71497. VIGNETTEBLENDMODEOPAQUE: false,
  71498. TONEMAPPING: false,
  71499. CONTRAST: false,
  71500. COLORCURVES: false,
  71501. COLORGRADING: false,
  71502. COLORGRADING3D: false,
  71503. FROMLINEARSPACE: false,
  71504. SAMPLER3DGREENDEPTH: false,
  71505. SAMPLER3DBGRMAP: false,
  71506. IMAGEPROCESSINGPOSTPROCESS: false,
  71507. EXPOSURE: false,
  71508. GRAIN: false,
  71509. };
  71510. // Setup the configuration as forced by the constructor. This would then not force the
  71511. // scene materials output in linear space and let untouched the default forward pass.
  71512. if (imageProcessingConfiguration) {
  71513. imageProcessingConfiguration.applyByPostProcess = true;
  71514. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71515. // This will cause the shader to be compiled
  71516. _this.fromLinearSpace = false;
  71517. }
  71518. else {
  71519. _this._attachImageProcessingConfiguration(null, true);
  71520. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71521. }
  71522. _this.onApply = function (effect) {
  71523. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71524. };
  71525. return _this;
  71526. }
  71527. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71528. /**
  71529. * Gets the image processing configuration used either in this material.
  71530. */
  71531. get: function () {
  71532. return this._imageProcessingConfiguration;
  71533. },
  71534. /**
  71535. * Sets the Default image processing configuration used either in the this material.
  71536. *
  71537. * If sets to null, the scene one is in use.
  71538. */
  71539. set: function (value) {
  71540. this._attachImageProcessingConfiguration(value);
  71541. },
  71542. enumerable: true,
  71543. configurable: true
  71544. });
  71545. /**
  71546. * Attaches a new image processing configuration to the PBR Material.
  71547. * @param configuration
  71548. */
  71549. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71550. var _this = this;
  71551. if (doNotBuild === void 0) { doNotBuild = false; }
  71552. if (configuration === this._imageProcessingConfiguration) {
  71553. return;
  71554. }
  71555. // Detaches observer.
  71556. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71557. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71558. }
  71559. // Pick the scene configuration if needed.
  71560. if (!configuration) {
  71561. var scene = null;
  71562. var engine = this.getEngine();
  71563. var camera = this.getCamera();
  71564. if (camera) {
  71565. scene = camera.getScene();
  71566. }
  71567. else if (engine && engine.scenes) {
  71568. var scenes = engine.scenes;
  71569. scene = scenes[scenes.length - 1];
  71570. }
  71571. else {
  71572. scene = BABYLON.Engine.LastCreatedScene;
  71573. }
  71574. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71575. }
  71576. else {
  71577. this._imageProcessingConfiguration = configuration;
  71578. }
  71579. // Attaches observer.
  71580. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71581. _this._updateParameters();
  71582. });
  71583. // Ensure the effect will be rebuilt.
  71584. if (!doNotBuild) {
  71585. this._updateParameters();
  71586. }
  71587. };
  71588. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  71589. /**
  71590. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71591. */
  71592. get: function () {
  71593. return this.imageProcessingConfiguration.colorCurves;
  71594. },
  71595. /**
  71596. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71597. */
  71598. set: function (value) {
  71599. this.imageProcessingConfiguration.colorCurves = value;
  71600. },
  71601. enumerable: true,
  71602. configurable: true
  71603. });
  71604. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  71605. /**
  71606. * Gets wether the color curves effect is enabled.
  71607. */
  71608. get: function () {
  71609. return this.imageProcessingConfiguration.colorCurvesEnabled;
  71610. },
  71611. /**
  71612. * Sets wether the color curves effect is enabled.
  71613. */
  71614. set: function (value) {
  71615. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  71616. },
  71617. enumerable: true,
  71618. configurable: true
  71619. });
  71620. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  71621. /**
  71622. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71623. */
  71624. get: function () {
  71625. return this.imageProcessingConfiguration.colorGradingTexture;
  71626. },
  71627. /**
  71628. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71629. */
  71630. set: function (value) {
  71631. this.imageProcessingConfiguration.colorGradingTexture = value;
  71632. },
  71633. enumerable: true,
  71634. configurable: true
  71635. });
  71636. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71637. /**
  71638. * Gets wether the color grading effect is enabled.
  71639. */
  71640. get: function () {
  71641. return this.imageProcessingConfiguration.colorGradingEnabled;
  71642. },
  71643. /**
  71644. * Gets wether the color grading effect is enabled.
  71645. */
  71646. set: function (value) {
  71647. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71648. },
  71649. enumerable: true,
  71650. configurable: true
  71651. });
  71652. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71653. /**
  71654. * Gets exposure used in the effect.
  71655. */
  71656. get: function () {
  71657. return this.imageProcessingConfiguration.exposure;
  71658. },
  71659. /**
  71660. * Sets exposure used in the effect.
  71661. */
  71662. set: function (value) {
  71663. this.imageProcessingConfiguration.exposure = value;
  71664. },
  71665. enumerable: true,
  71666. configurable: true
  71667. });
  71668. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71669. /**
  71670. * Gets wether tonemapping is enabled or not.
  71671. */
  71672. get: function () {
  71673. return this._imageProcessingConfiguration.toneMappingEnabled;
  71674. },
  71675. /**
  71676. * Sets wether tonemapping is enabled or not
  71677. */
  71678. set: function (value) {
  71679. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71680. },
  71681. enumerable: true,
  71682. configurable: true
  71683. });
  71684. ;
  71685. ;
  71686. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71687. /**
  71688. * Gets contrast used in the effect.
  71689. */
  71690. get: function () {
  71691. return this.imageProcessingConfiguration.contrast;
  71692. },
  71693. /**
  71694. * Sets contrast used in the effect.
  71695. */
  71696. set: function (value) {
  71697. this.imageProcessingConfiguration.contrast = value;
  71698. },
  71699. enumerable: true,
  71700. configurable: true
  71701. });
  71702. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71703. /**
  71704. * Gets Vignette stretch size.
  71705. */
  71706. get: function () {
  71707. return this.imageProcessingConfiguration.vignetteStretch;
  71708. },
  71709. /**
  71710. * Sets Vignette stretch size.
  71711. */
  71712. set: function (value) {
  71713. this.imageProcessingConfiguration.vignetteStretch = value;
  71714. },
  71715. enumerable: true,
  71716. configurable: true
  71717. });
  71718. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71719. /**
  71720. * Gets Vignette centre X Offset.
  71721. */
  71722. get: function () {
  71723. return this.imageProcessingConfiguration.vignetteCentreX;
  71724. },
  71725. /**
  71726. * Sets Vignette centre X Offset.
  71727. */
  71728. set: function (value) {
  71729. this.imageProcessingConfiguration.vignetteCentreX = value;
  71730. },
  71731. enumerable: true,
  71732. configurable: true
  71733. });
  71734. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  71735. /**
  71736. * Gets Vignette centre Y Offset.
  71737. */
  71738. get: function () {
  71739. return this.imageProcessingConfiguration.vignetteCentreY;
  71740. },
  71741. /**
  71742. * Sets Vignette centre Y Offset.
  71743. */
  71744. set: function (value) {
  71745. this.imageProcessingConfiguration.vignetteCentreY = value;
  71746. },
  71747. enumerable: true,
  71748. configurable: true
  71749. });
  71750. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  71751. /**
  71752. * Gets Vignette weight or intensity of the vignette effect.
  71753. */
  71754. get: function () {
  71755. return this.imageProcessingConfiguration.vignetteWeight;
  71756. },
  71757. /**
  71758. * Sets Vignette weight or intensity of the vignette effect.
  71759. */
  71760. set: function (value) {
  71761. this.imageProcessingConfiguration.vignetteWeight = value;
  71762. },
  71763. enumerable: true,
  71764. configurable: true
  71765. });
  71766. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71767. /**
  71768. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71769. * if vignetteEnabled is set to true.
  71770. */
  71771. get: function () {
  71772. return this.imageProcessingConfiguration.vignetteColor;
  71773. },
  71774. /**
  71775. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71776. * if vignetteEnabled is set to true.
  71777. */
  71778. set: function (value) {
  71779. this.imageProcessingConfiguration.vignetteColor = value;
  71780. },
  71781. enumerable: true,
  71782. configurable: true
  71783. });
  71784. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71785. /**
  71786. * Gets Camera field of view used by the Vignette effect.
  71787. */
  71788. get: function () {
  71789. return this.imageProcessingConfiguration.vignetteCameraFov;
  71790. },
  71791. /**
  71792. * Sets Camera field of view used by the Vignette effect.
  71793. */
  71794. set: function (value) {
  71795. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71796. },
  71797. enumerable: true,
  71798. configurable: true
  71799. });
  71800. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71801. /**
  71802. * Gets the vignette blend mode allowing different kind of effect.
  71803. */
  71804. get: function () {
  71805. return this.imageProcessingConfiguration.vignetteBlendMode;
  71806. },
  71807. /**
  71808. * Sets the vignette blend mode allowing different kind of effect.
  71809. */
  71810. set: function (value) {
  71811. this.imageProcessingConfiguration.vignetteBlendMode = value;
  71812. },
  71813. enumerable: true,
  71814. configurable: true
  71815. });
  71816. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  71817. /**
  71818. * Gets wether the vignette effect is enabled.
  71819. */
  71820. get: function () {
  71821. return this.imageProcessingConfiguration.vignetteEnabled;
  71822. },
  71823. /**
  71824. * Sets wether the vignette effect is enabled.
  71825. */
  71826. set: function (value) {
  71827. this.imageProcessingConfiguration.vignetteEnabled = value;
  71828. },
  71829. enumerable: true,
  71830. configurable: true
  71831. });
  71832. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  71833. /**
  71834. * Gets wether the grain effect is enabled.
  71835. */
  71836. get: function () {
  71837. return this.imageProcessingConfiguration.grainEnabled;
  71838. },
  71839. /**
  71840. * Sets wether the grain effect is enabled.
  71841. */
  71842. set: function (value) {
  71843. this.imageProcessingConfiguration.grainEnabled = value;
  71844. },
  71845. enumerable: true,
  71846. configurable: true
  71847. });
  71848. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  71849. /**
  71850. * Gets the grain effect's intensity.
  71851. */
  71852. get: function () {
  71853. return this.imageProcessingConfiguration.grainIntensity;
  71854. },
  71855. /**
  71856. * Sets the grain effect's intensity.
  71857. */
  71858. set: function (value) {
  71859. this.imageProcessingConfiguration.grainIntensity = value;
  71860. },
  71861. enumerable: true,
  71862. configurable: true
  71863. });
  71864. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  71865. /**
  71866. * Gets wether the grain effect is animated.
  71867. */
  71868. get: function () {
  71869. return this.imageProcessingConfiguration.grainAnimated;
  71870. },
  71871. /**
  71872. * Sets wether the grain effect is animated.
  71873. */
  71874. set: function (value) {
  71875. this.imageProcessingConfiguration.grainAnimated = value;
  71876. },
  71877. enumerable: true,
  71878. configurable: true
  71879. });
  71880. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  71881. /**
  71882. * Gets wether the input of the processing is in Gamma or Linear Space.
  71883. */
  71884. get: function () {
  71885. return this._fromLinearSpace;
  71886. },
  71887. /**
  71888. * Sets wether the input of the processing is in Gamma or Linear Space.
  71889. */
  71890. set: function (value) {
  71891. if (this._fromLinearSpace === value) {
  71892. return;
  71893. }
  71894. this._fromLinearSpace = value;
  71895. this._updateParameters();
  71896. },
  71897. enumerable: true,
  71898. configurable: true
  71899. });
  71900. ImageProcessingPostProcess.prototype.getClassName = function () {
  71901. return "ImageProcessingPostProcess";
  71902. };
  71903. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71904. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71905. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71906. var defines = "";
  71907. for (var define in this._defines) {
  71908. if (this._defines[define]) {
  71909. defines += "#define " + define + ";\r\n";
  71910. }
  71911. }
  71912. var samplers = ["textureSampler"];
  71913. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71914. var uniforms = ["scale"];
  71915. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71916. this.updateEffect(defines, uniforms, samplers);
  71917. };
  71918. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71919. _super.prototype.dispose.call(this, camera);
  71920. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71921. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71922. }
  71923. this.imageProcessingConfiguration.applyByPostProcess = false;
  71924. };
  71925. __decorate([
  71926. BABYLON.serialize()
  71927. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71928. return ImageProcessingPostProcess;
  71929. }(BABYLON.PostProcess));
  71930. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71931. })(BABYLON || (BABYLON = {}));
  71932. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71933. var BABYLON;
  71934. (function (BABYLON) {
  71935. var Bone = /** @class */ (function (_super) {
  71936. __extends(Bone, _super);
  71937. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71938. if (parentBone === void 0) { parentBone = null; }
  71939. if (localMatrix === void 0) { localMatrix = null; }
  71940. if (restPose === void 0) { restPose = null; }
  71941. if (baseMatrix === void 0) { baseMatrix = null; }
  71942. if (index === void 0) { index = null; }
  71943. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71944. _this.name = name;
  71945. _this.children = new Array();
  71946. _this.animations = new Array();
  71947. // Set this value to map this bone to a different index in the transform matrices.
  71948. // Set this value to -1 to exclude the bone from the transform matrices.
  71949. _this._index = null;
  71950. _this._worldTransform = new BABYLON.Matrix();
  71951. _this._absoluteTransform = new BABYLON.Matrix();
  71952. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71953. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71954. _this._scaleVector = BABYLON.Vector3.One();
  71955. _this._negateScaleChildren = BABYLON.Vector3.One();
  71956. _this._scalingDeterminant = 1;
  71957. _this._skeleton = skeleton;
  71958. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71959. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71960. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71961. _this._index = index;
  71962. skeleton.bones.push(_this);
  71963. _this.setParent(parentBone, false);
  71964. _this._updateDifferenceMatrix();
  71965. return _this;
  71966. }
  71967. Object.defineProperty(Bone.prototype, "_matrix", {
  71968. get: function () {
  71969. return this._localMatrix;
  71970. },
  71971. set: function (val) {
  71972. if (this._localMatrix) {
  71973. this._localMatrix.copyFrom(val);
  71974. }
  71975. else {
  71976. this._localMatrix = val;
  71977. }
  71978. },
  71979. enumerable: true,
  71980. configurable: true
  71981. });
  71982. // Members
  71983. Bone.prototype.getSkeleton = function () {
  71984. return this._skeleton;
  71985. };
  71986. Bone.prototype.getParent = function () {
  71987. return this._parent;
  71988. };
  71989. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71990. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71991. if (this._parent === parent) {
  71992. return;
  71993. }
  71994. if (this._parent) {
  71995. var index = this._parent.children.indexOf(this);
  71996. if (index !== -1) {
  71997. this._parent.children.splice(index, 1);
  71998. }
  71999. }
  72000. this._parent = parent;
  72001. if (this._parent) {
  72002. this._parent.children.push(this);
  72003. }
  72004. if (updateDifferenceMatrix) {
  72005. this._updateDifferenceMatrix();
  72006. }
  72007. };
  72008. Bone.prototype.getLocalMatrix = function () {
  72009. return this._localMatrix;
  72010. };
  72011. Bone.prototype.getBaseMatrix = function () {
  72012. return this._baseMatrix;
  72013. };
  72014. Bone.prototype.getRestPose = function () {
  72015. return this._restPose;
  72016. };
  72017. Bone.prototype.returnToRest = function () {
  72018. this.updateMatrix(this._restPose.clone());
  72019. };
  72020. Bone.prototype.getWorldMatrix = function () {
  72021. return this._worldTransform;
  72022. };
  72023. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72024. return this._invertedAbsoluteTransform;
  72025. };
  72026. Bone.prototype.getAbsoluteTransform = function () {
  72027. return this._absoluteTransform;
  72028. };
  72029. Object.defineProperty(Bone.prototype, "position", {
  72030. // Properties (matches AbstractMesh properties)
  72031. get: function () {
  72032. return this.getPosition();
  72033. },
  72034. set: function (newPosition) {
  72035. this.setPosition(newPosition);
  72036. },
  72037. enumerable: true,
  72038. configurable: true
  72039. });
  72040. Object.defineProperty(Bone.prototype, "rotation", {
  72041. get: function () {
  72042. return this.getRotation();
  72043. },
  72044. set: function (newRotation) {
  72045. this.setRotation(newRotation);
  72046. },
  72047. enumerable: true,
  72048. configurable: true
  72049. });
  72050. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72051. get: function () {
  72052. return this.getRotationQuaternion();
  72053. },
  72054. set: function (newRotation) {
  72055. this.setRotationQuaternion(newRotation);
  72056. },
  72057. enumerable: true,
  72058. configurable: true
  72059. });
  72060. Object.defineProperty(Bone.prototype, "scaling", {
  72061. get: function () {
  72062. return this.getScale();
  72063. },
  72064. set: function (newScaling) {
  72065. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72066. },
  72067. enumerable: true,
  72068. configurable: true
  72069. });
  72070. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72071. /**
  72072. * Gets the animation properties override
  72073. */
  72074. get: function () {
  72075. return this._skeleton.animationPropertiesOverride;
  72076. },
  72077. enumerable: true,
  72078. configurable: true
  72079. });
  72080. // Methods
  72081. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72082. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72083. this._baseMatrix = matrix.clone();
  72084. this._localMatrix = matrix.clone();
  72085. this._skeleton._markAsDirty();
  72086. if (updateDifferenceMatrix) {
  72087. this._updateDifferenceMatrix();
  72088. }
  72089. };
  72090. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72091. if (!rootMatrix) {
  72092. rootMatrix = this._baseMatrix;
  72093. }
  72094. if (this._parent) {
  72095. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72096. }
  72097. else {
  72098. this._absoluteTransform.copyFrom(rootMatrix);
  72099. }
  72100. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72101. for (var index = 0; index < this.children.length; index++) {
  72102. this.children[index]._updateDifferenceMatrix();
  72103. }
  72104. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72105. };
  72106. Bone.prototype.markAsDirty = function () {
  72107. this._currentRenderId++;
  72108. this._skeleton._markAsDirty();
  72109. };
  72110. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72111. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72112. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72113. // all animation may be coming from a library skeleton, so may need to create animation
  72114. if (this.animations.length === 0) {
  72115. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72116. this.animations[0].setKeys([]);
  72117. }
  72118. // get animation info / verify there is such a range from the source bone
  72119. var sourceRange = source.animations[0].getRange(rangeName);
  72120. if (!sourceRange) {
  72121. return false;
  72122. }
  72123. var from = sourceRange.from;
  72124. var to = sourceRange.to;
  72125. var sourceKeys = source.animations[0].getKeys();
  72126. // rescaling prep
  72127. var sourceBoneLength = source.length;
  72128. var sourceParent = source.getParent();
  72129. var parent = this.getParent();
  72130. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72131. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72132. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72133. var destKeys = this.animations[0].getKeys();
  72134. // loop vars declaration
  72135. var orig;
  72136. var origTranslation;
  72137. var mat;
  72138. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72139. orig = sourceKeys[key];
  72140. if (orig.frame >= from && orig.frame <= to) {
  72141. if (rescaleAsRequired) {
  72142. mat = orig.value.clone();
  72143. // scale based on parent ratio, when bone has parent
  72144. if (parentScalingReqd) {
  72145. origTranslation = mat.getTranslation();
  72146. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72147. // scale based on skeleton dimension ratio when root bone, and value is passed
  72148. }
  72149. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72150. origTranslation = mat.getTranslation();
  72151. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72152. // use original when root bone, and no data for skelDimensionsRatio
  72153. }
  72154. else {
  72155. mat = orig.value;
  72156. }
  72157. }
  72158. else {
  72159. mat = orig.value;
  72160. }
  72161. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72162. }
  72163. }
  72164. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72165. return true;
  72166. };
  72167. /**
  72168. * Translate the bone in local or world space.
  72169. * @param vec The amount to translate the bone.
  72170. * @param space The space that the translation is in.
  72171. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72172. */
  72173. Bone.prototype.translate = function (vec, space, mesh) {
  72174. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72175. var lm = this.getLocalMatrix();
  72176. if (space == BABYLON.Space.LOCAL) {
  72177. lm.m[12] += vec.x;
  72178. lm.m[13] += vec.y;
  72179. lm.m[14] += vec.z;
  72180. }
  72181. else {
  72182. var wm = null;
  72183. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72184. if (mesh) {
  72185. wm = mesh.getWorldMatrix();
  72186. }
  72187. this._skeleton.computeAbsoluteTransforms();
  72188. var tmat = Bone._tmpMats[0];
  72189. var tvec = Bone._tmpVecs[0];
  72190. if (this._parent) {
  72191. if (mesh && wm) {
  72192. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72193. tmat.multiplyToRef(wm, tmat);
  72194. }
  72195. else {
  72196. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72197. }
  72198. }
  72199. tmat.m[12] = 0;
  72200. tmat.m[13] = 0;
  72201. tmat.m[14] = 0;
  72202. tmat.invert();
  72203. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72204. lm.m[12] += tvec.x;
  72205. lm.m[13] += tvec.y;
  72206. lm.m[14] += tvec.z;
  72207. }
  72208. this.markAsDirty();
  72209. };
  72210. /**
  72211. * Set the postion of the bone in local or world space.
  72212. * @param position The position to set the bone.
  72213. * @param space The space that the position is in.
  72214. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72215. */
  72216. Bone.prototype.setPosition = function (position, space, mesh) {
  72217. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72218. var lm = this.getLocalMatrix();
  72219. if (space == BABYLON.Space.LOCAL) {
  72220. lm.m[12] = position.x;
  72221. lm.m[13] = position.y;
  72222. lm.m[14] = position.z;
  72223. }
  72224. else {
  72225. var wm = null;
  72226. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72227. if (mesh) {
  72228. wm = mesh.getWorldMatrix();
  72229. }
  72230. this._skeleton.computeAbsoluteTransforms();
  72231. var tmat = Bone._tmpMats[0];
  72232. var vec = Bone._tmpVecs[0];
  72233. if (this._parent) {
  72234. if (mesh && wm) {
  72235. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72236. tmat.multiplyToRef(wm, tmat);
  72237. }
  72238. else {
  72239. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72240. }
  72241. }
  72242. tmat.invert();
  72243. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72244. lm.m[12] = vec.x;
  72245. lm.m[13] = vec.y;
  72246. lm.m[14] = vec.z;
  72247. }
  72248. this.markAsDirty();
  72249. };
  72250. /**
  72251. * Set the absolute postion of the bone (world space).
  72252. * @param position The position to set the bone.
  72253. * @param mesh The mesh that this bone is attached to.
  72254. */
  72255. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72256. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72257. };
  72258. /**
  72259. * Set the scale of the bone on the x, y and z axes.
  72260. * @param x The scale of the bone on the x axis.
  72261. * @param x The scale of the bone on the y axis.
  72262. * @param z The scale of the bone on the z axis.
  72263. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72264. */
  72265. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72266. if (scaleChildren === void 0) { scaleChildren = false; }
  72267. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72268. if (!scaleChildren) {
  72269. this._negateScaleChildren.x = 1 / x;
  72270. this._negateScaleChildren.y = 1 / y;
  72271. this._negateScaleChildren.z = 1 / z;
  72272. }
  72273. this._syncScaleVector();
  72274. }
  72275. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72276. };
  72277. /**
  72278. * Scale the bone on the x, y and z axes.
  72279. * @param x The amount to scale the bone on the x axis.
  72280. * @param x The amount to scale the bone on the y axis.
  72281. * @param z The amount to scale the bone on the z axis.
  72282. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72283. */
  72284. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72285. if (scaleChildren === void 0) { scaleChildren = false; }
  72286. var locMat = this.getLocalMatrix();
  72287. var origLocMat = Bone._tmpMats[0];
  72288. origLocMat.copyFrom(locMat);
  72289. var origLocMatInv = Bone._tmpMats[1];
  72290. origLocMatInv.copyFrom(origLocMat);
  72291. origLocMatInv.invert();
  72292. var scaleMat = Bone._tmpMats[2];
  72293. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72294. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72295. this._scaleVector.x *= x;
  72296. this._scaleVector.y *= y;
  72297. this._scaleVector.z *= z;
  72298. locMat.multiplyToRef(origLocMatInv, locMat);
  72299. locMat.multiplyToRef(scaleMat, locMat);
  72300. locMat.multiplyToRef(origLocMat, locMat);
  72301. var parent = this.getParent();
  72302. if (parent) {
  72303. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72304. }
  72305. else {
  72306. this.getAbsoluteTransform().copyFrom(locMat);
  72307. }
  72308. var len = this.children.length;
  72309. scaleMat.invert();
  72310. for (var i = 0; i < len; i++) {
  72311. var child = this.children[i];
  72312. var cm = child.getLocalMatrix();
  72313. cm.multiplyToRef(scaleMat, cm);
  72314. var lm = child.getLocalMatrix();
  72315. lm.m[12] *= x;
  72316. lm.m[13] *= y;
  72317. lm.m[14] *= z;
  72318. }
  72319. this.computeAbsoluteTransforms();
  72320. if (scaleChildren) {
  72321. for (var i = 0; i < len; i++) {
  72322. this.children[i].scale(x, y, z, scaleChildren);
  72323. }
  72324. }
  72325. this.markAsDirty();
  72326. };
  72327. /**
  72328. * Set the yaw, pitch, and roll of the bone in local or world space.
  72329. * @param yaw The rotation of the bone on the y axis.
  72330. * @param pitch The rotation of the bone on the x axis.
  72331. * @param roll The rotation of the bone on the z axis.
  72332. * @param space The space that the axes of rotation are in.
  72333. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72334. */
  72335. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72336. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72337. var rotMat = Bone._tmpMats[0];
  72338. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72339. var rotMatInv = Bone._tmpMats[1];
  72340. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72341. rotMatInv.multiplyToRef(rotMat, rotMat);
  72342. this._rotateWithMatrix(rotMat, space, mesh);
  72343. };
  72344. /**
  72345. * Rotate the bone on an axis in local or world space.
  72346. * @param axis The axis to rotate the bone on.
  72347. * @param amount The amount to rotate the bone.
  72348. * @param space The space that the axis is in.
  72349. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72350. */
  72351. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72352. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72353. var rmat = Bone._tmpMats[0];
  72354. rmat.m[12] = 0;
  72355. rmat.m[13] = 0;
  72356. rmat.m[14] = 0;
  72357. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72358. this._rotateWithMatrix(rmat, space, mesh);
  72359. };
  72360. /**
  72361. * Set the rotation of the bone to a particular axis angle in local or world space.
  72362. * @param axis The axis to rotate the bone on.
  72363. * @param angle The angle that the bone should be rotated to.
  72364. * @param space The space that the axis is in.
  72365. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72366. */
  72367. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72368. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72369. var rotMat = Bone._tmpMats[0];
  72370. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72371. var rotMatInv = Bone._tmpMats[1];
  72372. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72373. rotMatInv.multiplyToRef(rotMat, rotMat);
  72374. this._rotateWithMatrix(rotMat, space, mesh);
  72375. };
  72376. /**
  72377. * Set the euler rotation of the bone in local of world space.
  72378. * @param rotation The euler rotation that the bone should be set to.
  72379. * @param space The space that the rotation is in.
  72380. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72381. */
  72382. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72384. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72385. };
  72386. /**
  72387. * Set the quaternion rotation of the bone in local of world space.
  72388. * @param quat The quaternion rotation that the bone should be set to.
  72389. * @param space The space that the rotation is in.
  72390. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72391. */
  72392. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72393. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72394. var rotMatInv = Bone._tmpMats[0];
  72395. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72396. var rotMat = Bone._tmpMats[1];
  72397. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72398. rotMatInv.multiplyToRef(rotMat, rotMat);
  72399. this._rotateWithMatrix(rotMat, space, mesh);
  72400. };
  72401. /**
  72402. * Set the rotation matrix of the bone in local of world space.
  72403. * @param rotMat The rotation matrix that the bone should be set to.
  72404. * @param space The space that the rotation is in.
  72405. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72406. */
  72407. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  72408. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72409. var rotMatInv = Bone._tmpMats[0];
  72410. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72411. var rotMat2 = Bone._tmpMats[1];
  72412. rotMat2.copyFrom(rotMat);
  72413. rotMatInv.multiplyToRef(rotMat, rotMat2);
  72414. this._rotateWithMatrix(rotMat2, space, mesh);
  72415. };
  72416. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  72417. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72418. var lmat = this.getLocalMatrix();
  72419. var lx = lmat.m[12];
  72420. var ly = lmat.m[13];
  72421. var lz = lmat.m[14];
  72422. var parent = this.getParent();
  72423. var parentScale = Bone._tmpMats[3];
  72424. var parentScaleInv = Bone._tmpMats[4];
  72425. if (parent) {
  72426. if (space == BABYLON.Space.WORLD) {
  72427. if (mesh) {
  72428. parentScale.copyFrom(mesh.getWorldMatrix());
  72429. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  72430. }
  72431. else {
  72432. parentScale.copyFrom(parent.getAbsoluteTransform());
  72433. }
  72434. }
  72435. else {
  72436. parentScale = parent._scaleMatrix;
  72437. }
  72438. parentScaleInv.copyFrom(parentScale);
  72439. parentScaleInv.invert();
  72440. lmat.multiplyToRef(parentScale, lmat);
  72441. lmat.multiplyToRef(rmat, lmat);
  72442. lmat.multiplyToRef(parentScaleInv, lmat);
  72443. }
  72444. else {
  72445. if (space == BABYLON.Space.WORLD && mesh) {
  72446. parentScale.copyFrom(mesh.getWorldMatrix());
  72447. parentScaleInv.copyFrom(parentScale);
  72448. parentScaleInv.invert();
  72449. lmat.multiplyToRef(parentScale, lmat);
  72450. lmat.multiplyToRef(rmat, lmat);
  72451. lmat.multiplyToRef(parentScaleInv, lmat);
  72452. }
  72453. else {
  72454. lmat.multiplyToRef(rmat, lmat);
  72455. }
  72456. }
  72457. lmat.m[12] = lx;
  72458. lmat.m[13] = ly;
  72459. lmat.m[14] = lz;
  72460. this.computeAbsoluteTransforms();
  72461. this.markAsDirty();
  72462. };
  72463. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  72464. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72465. if (space == BABYLON.Space.WORLD) {
  72466. var scaleMatrix = Bone._tmpMats[2];
  72467. scaleMatrix.copyFrom(this._scaleMatrix);
  72468. rotMatInv.copyFrom(this.getAbsoluteTransform());
  72469. if (mesh) {
  72470. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  72471. var meshScale = Bone._tmpMats[3];
  72472. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  72473. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  72474. }
  72475. rotMatInv.invert();
  72476. scaleMatrix.m[0] *= this._scalingDeterminant;
  72477. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72478. }
  72479. else {
  72480. rotMatInv.copyFrom(this.getLocalMatrix());
  72481. rotMatInv.invert();
  72482. var scaleMatrix = Bone._tmpMats[2];
  72483. scaleMatrix.copyFrom(this._scaleMatrix);
  72484. if (this._parent) {
  72485. var pscaleMatrix = Bone._tmpMats[3];
  72486. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  72487. pscaleMatrix.invert();
  72488. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  72489. }
  72490. else {
  72491. scaleMatrix.m[0] *= this._scalingDeterminant;
  72492. }
  72493. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72494. }
  72495. };
  72496. /**
  72497. * Get the scale of the bone
  72498. * @returns the scale of the bone
  72499. */
  72500. Bone.prototype.getScale = function () {
  72501. return this._scaleVector.clone();
  72502. };
  72503. /**
  72504. * Copy the scale of the bone to a vector3.
  72505. * @param result The vector3 to copy the scale to
  72506. */
  72507. Bone.prototype.getScaleToRef = function (result) {
  72508. result.copyFrom(this._scaleVector);
  72509. };
  72510. /**
  72511. * Get the position of the bone in local or world space.
  72512. * @param space The space that the returned position is in.
  72513. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72514. * @returns The position of the bone
  72515. */
  72516. Bone.prototype.getPosition = function (space, mesh) {
  72517. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72518. if (mesh === void 0) { mesh = null; }
  72519. var pos = BABYLON.Vector3.Zero();
  72520. this.getPositionToRef(space, mesh, pos);
  72521. return pos;
  72522. };
  72523. /**
  72524. * Copy the position of the bone to a vector3 in local or world space.
  72525. * @param space The space that the returned position is in.
  72526. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72527. * @param result The vector3 to copy the position to.
  72528. */
  72529. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72530. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72531. if (space == BABYLON.Space.LOCAL) {
  72532. var lm = this.getLocalMatrix();
  72533. result.x = lm.m[12];
  72534. result.y = lm.m[13];
  72535. result.z = lm.m[14];
  72536. }
  72537. else {
  72538. var wm = null;
  72539. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72540. if (mesh) {
  72541. wm = mesh.getWorldMatrix();
  72542. }
  72543. this._skeleton.computeAbsoluteTransforms();
  72544. var tmat = Bone._tmpMats[0];
  72545. if (mesh && wm) {
  72546. tmat.copyFrom(this.getAbsoluteTransform());
  72547. tmat.multiplyToRef(wm, tmat);
  72548. }
  72549. else {
  72550. tmat = this.getAbsoluteTransform();
  72551. }
  72552. result.x = tmat.m[12];
  72553. result.y = tmat.m[13];
  72554. result.z = tmat.m[14];
  72555. }
  72556. };
  72557. /**
  72558. * Get the absolute position of the bone (world space).
  72559. * @param mesh The mesh that this bone is attached to.
  72560. * @returns The absolute position of the bone
  72561. */
  72562. Bone.prototype.getAbsolutePosition = function (mesh) {
  72563. if (mesh === void 0) { mesh = null; }
  72564. var pos = BABYLON.Vector3.Zero();
  72565. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72566. return pos;
  72567. };
  72568. /**
  72569. * Copy the absolute position of the bone (world space) to the result param.
  72570. * @param mesh The mesh that this bone is attached to.
  72571. * @param result The vector3 to copy the absolute position to.
  72572. */
  72573. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72574. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72575. };
  72576. /**
  72577. * Compute the absolute transforms of this bone and its children.
  72578. */
  72579. Bone.prototype.computeAbsoluteTransforms = function () {
  72580. if (this._parent) {
  72581. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72582. }
  72583. else {
  72584. this._absoluteTransform.copyFrom(this._localMatrix);
  72585. var poseMatrix = this._skeleton.getPoseMatrix();
  72586. if (poseMatrix) {
  72587. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  72588. }
  72589. }
  72590. var children = this.children;
  72591. var len = children.length;
  72592. for (var i = 0; i < len; i++) {
  72593. children[i].computeAbsoluteTransforms();
  72594. }
  72595. };
  72596. Bone.prototype._syncScaleVector = function () {
  72597. var lm = this.getLocalMatrix();
  72598. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  72599. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  72600. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  72601. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  72602. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  72603. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  72604. this._scaleVector.x = xs * Math.sqrt(xsq);
  72605. this._scaleVector.y = ys * Math.sqrt(ysq);
  72606. this._scaleVector.z = zs * Math.sqrt(zsq);
  72607. if (this._parent) {
  72608. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  72609. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  72610. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  72611. }
  72612. 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);
  72613. };
  72614. /**
  72615. * Get the world direction from an axis that is in the local space of the bone.
  72616. * @param localAxis The local direction that is used to compute the world direction.
  72617. * @param mesh The mesh that this bone is attached to.
  72618. * @returns The world direction
  72619. */
  72620. Bone.prototype.getDirection = function (localAxis, mesh) {
  72621. if (mesh === void 0) { mesh = null; }
  72622. var result = BABYLON.Vector3.Zero();
  72623. this.getDirectionToRef(localAxis, mesh, result);
  72624. return result;
  72625. };
  72626. /**
  72627. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72628. * @param localAxis The local direction that is used to compute the world direction.
  72629. * @param mesh The mesh that this bone is attached to.
  72630. * @param result The vector3 that the world direction will be copied to.
  72631. */
  72632. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72633. if (mesh === void 0) { mesh = null; }
  72634. var wm = null;
  72635. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72636. if (mesh) {
  72637. wm = mesh.getWorldMatrix();
  72638. }
  72639. this._skeleton.computeAbsoluteTransforms();
  72640. var mat = Bone._tmpMats[0];
  72641. mat.copyFrom(this.getAbsoluteTransform());
  72642. if (mesh && wm) {
  72643. mat.multiplyToRef(wm, mat);
  72644. }
  72645. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72646. result.normalize();
  72647. };
  72648. /**
  72649. * Get the euler rotation of the bone in local or world space.
  72650. * @param space The space that the rotation should be in.
  72651. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72652. * @returns The euler rotation
  72653. */
  72654. Bone.prototype.getRotation = function (space, mesh) {
  72655. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72656. if (mesh === void 0) { mesh = null; }
  72657. var result = BABYLON.Vector3.Zero();
  72658. this.getRotationToRef(space, mesh, result);
  72659. return result;
  72660. };
  72661. /**
  72662. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72663. * @param space The space that the rotation should be in.
  72664. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72665. * @param result The vector3 that the rotation should be copied to.
  72666. */
  72667. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72668. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72669. if (mesh === void 0) { mesh = null; }
  72670. var quat = Bone._tmpQuat;
  72671. this.getRotationQuaternionToRef(space, mesh, quat);
  72672. quat.toEulerAnglesToRef(result);
  72673. };
  72674. /**
  72675. * Get the quaternion rotation of the bone in either local or world space.
  72676. * @param space The space that the rotation should be in.
  72677. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72678. * @returns The quaternion rotation
  72679. */
  72680. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72681. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72682. if (mesh === void 0) { mesh = null; }
  72683. var result = BABYLON.Quaternion.Identity();
  72684. this.getRotationQuaternionToRef(space, mesh, result);
  72685. return result;
  72686. };
  72687. /**
  72688. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72689. * @param space The space that the rotation should be in.
  72690. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72691. * @param result The quaternion that the rotation should be copied to.
  72692. */
  72693. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72694. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72695. if (mesh === void 0) { mesh = null; }
  72696. if (space == BABYLON.Space.LOCAL) {
  72697. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72698. }
  72699. else {
  72700. var mat = Bone._tmpMats[0];
  72701. var amat = this.getAbsoluteTransform();
  72702. if (mesh) {
  72703. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72704. }
  72705. else {
  72706. mat.copyFrom(amat);
  72707. }
  72708. mat.m[0] *= this._scalingDeterminant;
  72709. mat.m[1] *= this._scalingDeterminant;
  72710. mat.m[2] *= this._scalingDeterminant;
  72711. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72712. }
  72713. };
  72714. /**
  72715. * Get the rotation matrix of the bone in local or world space.
  72716. * @param space The space that the rotation should be in.
  72717. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72718. * @returns The rotation matrix
  72719. */
  72720. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72721. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72722. var result = BABYLON.Matrix.Identity();
  72723. this.getRotationMatrixToRef(space, mesh, result);
  72724. return result;
  72725. };
  72726. /**
  72727. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72728. * @param space The space that the rotation should be in.
  72729. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72730. * @param result The quaternion that the rotation should be copied to.
  72731. */
  72732. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  72733. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72734. if (space == BABYLON.Space.LOCAL) {
  72735. this.getLocalMatrix().getRotationMatrixToRef(result);
  72736. }
  72737. else {
  72738. var mat = Bone._tmpMats[0];
  72739. var amat = this.getAbsoluteTransform();
  72740. if (mesh) {
  72741. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72742. }
  72743. else {
  72744. mat.copyFrom(amat);
  72745. }
  72746. mat.m[0] *= this._scalingDeterminant;
  72747. mat.m[1] *= this._scalingDeterminant;
  72748. mat.m[2] *= this._scalingDeterminant;
  72749. mat.getRotationMatrixToRef(result);
  72750. }
  72751. };
  72752. /**
  72753. * Get the world position of a point that is in the local space of the bone.
  72754. * @param position The local position
  72755. * @param mesh The mesh that this bone is attached to.
  72756. * @returns The world position
  72757. */
  72758. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72759. if (mesh === void 0) { mesh = null; }
  72760. var result = BABYLON.Vector3.Zero();
  72761. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72762. return result;
  72763. };
  72764. /**
  72765. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72766. * @param position The local position
  72767. * @param mesh The mesh that this bone is attached to.
  72768. * @param result The vector3 that the world position should be copied to.
  72769. */
  72770. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72771. if (mesh === void 0) { mesh = null; }
  72772. var wm = null;
  72773. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72774. if (mesh) {
  72775. wm = mesh.getWorldMatrix();
  72776. }
  72777. this._skeleton.computeAbsoluteTransforms();
  72778. var tmat = Bone._tmpMats[0];
  72779. if (mesh && wm) {
  72780. tmat.copyFrom(this.getAbsoluteTransform());
  72781. tmat.multiplyToRef(wm, tmat);
  72782. }
  72783. else {
  72784. tmat = this.getAbsoluteTransform();
  72785. }
  72786. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72787. };
  72788. /**
  72789. * Get the local position of a point that is in world space.
  72790. * @param position The world position
  72791. * @param mesh The mesh that this bone is attached to.
  72792. * @returns The local position
  72793. */
  72794. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72795. if (mesh === void 0) { mesh = null; }
  72796. var result = BABYLON.Vector3.Zero();
  72797. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72798. return result;
  72799. };
  72800. /**
  72801. * Get the local position of a point that is in world space and copy it to the result param.
  72802. * @param position The world position
  72803. * @param mesh The mesh that this bone is attached to.
  72804. * @param result The vector3 that the local position should be copied to.
  72805. */
  72806. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  72807. if (mesh === void 0) { mesh = null; }
  72808. var wm = null;
  72809. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72810. if (mesh) {
  72811. wm = mesh.getWorldMatrix();
  72812. }
  72813. this._skeleton.computeAbsoluteTransforms();
  72814. var tmat = Bone._tmpMats[0];
  72815. tmat.copyFrom(this.getAbsoluteTransform());
  72816. if (mesh && wm) {
  72817. tmat.multiplyToRef(wm, tmat);
  72818. }
  72819. tmat.invert();
  72820. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72821. };
  72822. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72823. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  72824. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72825. return Bone;
  72826. }(BABYLON.Node));
  72827. BABYLON.Bone = Bone;
  72828. })(BABYLON || (BABYLON = {}));
  72829. //# sourceMappingURL=babylon.bone.js.map
  72830. var BABYLON;
  72831. (function (BABYLON) {
  72832. var BoneIKController = /** @class */ (function () {
  72833. function BoneIKController(mesh, bone, options) {
  72834. this.targetPosition = BABYLON.Vector3.Zero();
  72835. this.poleTargetPosition = BABYLON.Vector3.Zero();
  72836. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  72837. this.poleAngle = 0;
  72838. this.slerpAmount = 1;
  72839. this._bone1Quat = BABYLON.Quaternion.Identity();
  72840. this._bone1Mat = BABYLON.Matrix.Identity();
  72841. this._bone2Ang = Math.PI;
  72842. this._maxAngle = Math.PI;
  72843. this._rightHandedSystem = false;
  72844. this._bendAxis = BABYLON.Vector3.Right();
  72845. this._slerping = false;
  72846. this._adjustRoll = 0;
  72847. this._bone2 = bone;
  72848. this._bone1 = bone.getParent();
  72849. if (!this._bone1) {
  72850. return;
  72851. }
  72852. this.mesh = mesh;
  72853. var bonePos = bone.getPosition();
  72854. if (bone.getAbsoluteTransform().determinant() > 0) {
  72855. this._rightHandedSystem = true;
  72856. this._bendAxis.x = 0;
  72857. this._bendAxis.y = 0;
  72858. this._bendAxis.z = -1;
  72859. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  72860. this._adjustRoll = Math.PI * .5;
  72861. this._bendAxis.z = 1;
  72862. }
  72863. }
  72864. if (this._bone1.length) {
  72865. var boneScale1 = this._bone1.getScale();
  72866. var boneScale2 = this._bone2.getScale();
  72867. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  72868. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  72869. }
  72870. else if (this._bone1.children[0]) {
  72871. mesh.computeWorldMatrix(true);
  72872. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  72873. var pos2 = this._bone2.getAbsolutePosition(mesh);
  72874. var pos3 = this._bone1.getAbsolutePosition(mesh);
  72875. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  72876. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  72877. }
  72878. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  72879. this.maxAngle = Math.PI;
  72880. if (options) {
  72881. if (options.targetMesh) {
  72882. this.targetMesh = options.targetMesh;
  72883. this.targetMesh.computeWorldMatrix(true);
  72884. }
  72885. if (options.poleTargetMesh) {
  72886. this.poleTargetMesh = options.poleTargetMesh;
  72887. this.poleTargetMesh.computeWorldMatrix(true);
  72888. }
  72889. else if (options.poleTargetBone) {
  72890. this.poleTargetBone = options.poleTargetBone;
  72891. }
  72892. else if (this._bone1.getParent()) {
  72893. this.poleTargetBone = this._bone1.getParent();
  72894. }
  72895. if (options.poleTargetLocalOffset) {
  72896. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  72897. }
  72898. if (options.poleAngle) {
  72899. this.poleAngle = options.poleAngle;
  72900. }
  72901. if (options.bendAxis) {
  72902. this._bendAxis.copyFrom(options.bendAxis);
  72903. }
  72904. if (options.maxAngle) {
  72905. this.maxAngle = options.maxAngle;
  72906. }
  72907. if (options.slerpAmount) {
  72908. this.slerpAmount = options.slerpAmount;
  72909. }
  72910. }
  72911. }
  72912. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72913. get: function () {
  72914. return this._maxAngle;
  72915. },
  72916. set: function (value) {
  72917. this._setMaxAngle(value);
  72918. },
  72919. enumerable: true,
  72920. configurable: true
  72921. });
  72922. BoneIKController.prototype._setMaxAngle = function (ang) {
  72923. if (ang < 0) {
  72924. ang = 0;
  72925. }
  72926. if (ang > Math.PI || ang == undefined) {
  72927. ang = Math.PI;
  72928. }
  72929. this._maxAngle = ang;
  72930. var a = this._bone1Length;
  72931. var b = this._bone2Length;
  72932. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72933. };
  72934. BoneIKController.prototype.update = function () {
  72935. var bone1 = this._bone1;
  72936. if (!bone1) {
  72937. return;
  72938. }
  72939. var target = this.targetPosition;
  72940. var poleTarget = this.poleTargetPosition;
  72941. var mat1 = BoneIKController._tmpMats[0];
  72942. var mat2 = BoneIKController._tmpMats[1];
  72943. if (this.targetMesh) {
  72944. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72945. }
  72946. if (this.poleTargetBone) {
  72947. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72948. }
  72949. else if (this.poleTargetMesh) {
  72950. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72951. }
  72952. var bonePos = BoneIKController._tmpVecs[0];
  72953. var zaxis = BoneIKController._tmpVecs[1];
  72954. var xaxis = BoneIKController._tmpVecs[2];
  72955. var yaxis = BoneIKController._tmpVecs[3];
  72956. var upAxis = BoneIKController._tmpVecs[4];
  72957. var _tmpQuat = BoneIKController._tmpQuat;
  72958. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72959. poleTarget.subtractToRef(bonePos, upAxis);
  72960. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72961. upAxis.y = 1;
  72962. }
  72963. else {
  72964. upAxis.normalize();
  72965. }
  72966. target.subtractToRef(bonePos, yaxis);
  72967. yaxis.normalize();
  72968. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72969. zaxis.normalize();
  72970. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72971. xaxis.normalize();
  72972. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72973. var a = this._bone1Length;
  72974. var b = this._bone2Length;
  72975. var c = BABYLON.Vector3.Distance(bonePos, target);
  72976. if (this._maxReach > 0) {
  72977. c = Math.min(this._maxReach, c);
  72978. }
  72979. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72980. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72981. if (acosa > 1) {
  72982. acosa = 1;
  72983. }
  72984. if (acosb > 1) {
  72985. acosb = 1;
  72986. }
  72987. if (acosa < -1) {
  72988. acosa = -1;
  72989. }
  72990. if (acosb < -1) {
  72991. acosb = -1;
  72992. }
  72993. var angA = Math.acos(acosa);
  72994. var angB = Math.acos(acosb);
  72995. var angC = -angA - angB;
  72996. if (this._rightHandedSystem) {
  72997. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72998. mat2.multiplyToRef(mat1, mat1);
  72999. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73000. mat2.multiplyToRef(mat1, mat1);
  73001. }
  73002. else {
  73003. var _tmpVec = BoneIKController._tmpVecs[5];
  73004. _tmpVec.copyFrom(this._bendAxis);
  73005. _tmpVec.x *= -1;
  73006. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73007. mat2.multiplyToRef(mat1, mat1);
  73008. }
  73009. if (this.poleAngle) {
  73010. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73011. mat1.multiplyToRef(mat2, mat1);
  73012. }
  73013. if (this._bone1) {
  73014. if (this.slerpAmount < 1) {
  73015. if (!this._slerping) {
  73016. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73017. }
  73018. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73019. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73020. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73021. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73022. this._slerping = true;
  73023. }
  73024. else {
  73025. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73026. this._bone1Mat.copyFrom(mat1);
  73027. this._slerping = false;
  73028. }
  73029. }
  73030. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73031. this._bone2Ang = angC;
  73032. };
  73033. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73034. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73035. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73036. return BoneIKController;
  73037. }());
  73038. BABYLON.BoneIKController = BoneIKController;
  73039. })(BABYLON || (BABYLON = {}));
  73040. //# sourceMappingURL=babylon.boneIKController.js.map
  73041. var BABYLON;
  73042. (function (BABYLON) {
  73043. var BoneLookController = /** @class */ (function () {
  73044. /**
  73045. * Create a BoneLookController
  73046. * @param mesh the mesh that the bone belongs to
  73047. * @param bone the bone that will be looking to the target
  73048. * @param target the target Vector3 to look at
  73049. * @param settings optional settings:
  73050. * - maxYaw: the maximum angle the bone will yaw to
  73051. * - minYaw: the minimum angle the bone will yaw to
  73052. * - maxPitch: the maximum angle the bone will pitch to
  73053. * - minPitch: the minimum angle the bone will yaw to
  73054. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73055. * - upAxis: the up axis of the coordinate system
  73056. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73057. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73058. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73059. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73060. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73061. * - adjustRoll: used to make an adjustment to the roll of the bone
  73062. **/
  73063. function BoneLookController(mesh, bone, target, options) {
  73064. /**
  73065. * The up axis of the coordinate system that is used when the bone is rotated.
  73066. */
  73067. this.upAxis = BABYLON.Vector3.Up();
  73068. /**
  73069. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73070. */
  73071. this.upAxisSpace = BABYLON.Space.LOCAL;
  73072. /**
  73073. * Used to make an adjustment to the yaw of the bone.
  73074. */
  73075. this.adjustYaw = 0;
  73076. /**
  73077. * Used to make an adjustment to the pitch of the bone.
  73078. */
  73079. this.adjustPitch = 0;
  73080. /**
  73081. * Used to make an adjustment to the roll of the bone.
  73082. */
  73083. this.adjustRoll = 0;
  73084. /**
  73085. * 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).
  73086. */
  73087. this.slerpAmount = 1;
  73088. this._boneQuat = BABYLON.Quaternion.Identity();
  73089. this._slerping = false;
  73090. this._firstFrameSkipped = false;
  73091. this._fowardAxis = BABYLON.Vector3.Forward();
  73092. this.mesh = mesh;
  73093. this.bone = bone;
  73094. this.target = target;
  73095. if (options) {
  73096. if (options.adjustYaw) {
  73097. this.adjustYaw = options.adjustYaw;
  73098. }
  73099. if (options.adjustPitch) {
  73100. this.adjustPitch = options.adjustPitch;
  73101. }
  73102. if (options.adjustRoll) {
  73103. this.adjustRoll = options.adjustRoll;
  73104. }
  73105. if (options.maxYaw != null) {
  73106. this.maxYaw = options.maxYaw;
  73107. }
  73108. else {
  73109. this.maxYaw = Math.PI;
  73110. }
  73111. if (options.minYaw != null) {
  73112. this.minYaw = options.minYaw;
  73113. }
  73114. else {
  73115. this.minYaw = -Math.PI;
  73116. }
  73117. if (options.maxPitch != null) {
  73118. this.maxPitch = options.maxPitch;
  73119. }
  73120. else {
  73121. this.maxPitch = Math.PI;
  73122. }
  73123. if (options.minPitch != null) {
  73124. this.minPitch = options.minPitch;
  73125. }
  73126. else {
  73127. this.minPitch = -Math.PI;
  73128. }
  73129. if (options.slerpAmount != null) {
  73130. this.slerpAmount = options.slerpAmount;
  73131. }
  73132. if (options.upAxis != null) {
  73133. this.upAxis = options.upAxis;
  73134. }
  73135. if (options.upAxisSpace != null) {
  73136. this.upAxisSpace = options.upAxisSpace;
  73137. }
  73138. if (options.yawAxis != null || options.pitchAxis != null) {
  73139. var newYawAxis = BABYLON.Axis.Y;
  73140. var newPitchAxis = BABYLON.Axis.X;
  73141. if (options.yawAxis != null) {
  73142. newYawAxis = options.yawAxis.clone();
  73143. newYawAxis.normalize();
  73144. }
  73145. if (options.pitchAxis != null) {
  73146. newPitchAxis = options.pitchAxis.clone();
  73147. newPitchAxis.normalize();
  73148. }
  73149. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73150. this._transformYawPitch = BABYLON.Matrix.Identity();
  73151. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73152. this._transformYawPitchInv = this._transformYawPitch.clone();
  73153. this._transformYawPitch.invert();
  73154. }
  73155. }
  73156. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73157. this.upAxisSpace = BABYLON.Space.LOCAL;
  73158. }
  73159. }
  73160. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73161. /**
  73162. * Get/set the minimum yaw angle that the bone can look to.
  73163. */
  73164. get: function () {
  73165. return this._minYaw;
  73166. },
  73167. set: function (value) {
  73168. this._minYaw = value;
  73169. this._minYawSin = Math.sin(value);
  73170. this._minYawCos = Math.cos(value);
  73171. if (this._maxYaw != null) {
  73172. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73173. this._yawRange = this._maxYaw - this._minYaw;
  73174. }
  73175. },
  73176. enumerable: true,
  73177. configurable: true
  73178. });
  73179. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73180. /**
  73181. * Get/set the maximum yaw angle that the bone can look to.
  73182. */
  73183. get: function () {
  73184. return this._maxYaw;
  73185. },
  73186. set: function (value) {
  73187. this._maxYaw = value;
  73188. this._maxYawSin = Math.sin(value);
  73189. this._maxYawCos = Math.cos(value);
  73190. if (this._minYaw != null) {
  73191. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73192. this._yawRange = this._maxYaw - this._minYaw;
  73193. }
  73194. },
  73195. enumerable: true,
  73196. configurable: true
  73197. });
  73198. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73199. /**
  73200. * Get/set the minimum pitch angle that the bone can look to.
  73201. */
  73202. get: function () {
  73203. return this._minPitch;
  73204. },
  73205. set: function (value) {
  73206. this._minPitch = value;
  73207. this._minPitchTan = Math.tan(value);
  73208. },
  73209. enumerable: true,
  73210. configurable: true
  73211. });
  73212. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73213. /**
  73214. * Get/set the maximum pitch angle that the bone can look to.
  73215. */
  73216. get: function () {
  73217. return this._maxPitch;
  73218. },
  73219. set: function (value) {
  73220. this._maxPitch = value;
  73221. this._maxPitchTan = Math.tan(value);
  73222. },
  73223. enumerable: true,
  73224. configurable: true
  73225. });
  73226. /**
  73227. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73228. */
  73229. BoneLookController.prototype.update = function () {
  73230. //skip the first frame when slerping so that the mesh rotation is correct
  73231. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73232. this._firstFrameSkipped = true;
  73233. return;
  73234. }
  73235. var bone = this.bone;
  73236. var bonePos = BoneLookController._tmpVecs[0];
  73237. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73238. var target = this.target;
  73239. var _tmpMat1 = BoneLookController._tmpMats[0];
  73240. var _tmpMat2 = BoneLookController._tmpMats[1];
  73241. var mesh = this.mesh;
  73242. var parentBone = bone.getParent();
  73243. var upAxis = BoneLookController._tmpVecs[1];
  73244. upAxis.copyFrom(this.upAxis);
  73245. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73246. if (this._transformYawPitch) {
  73247. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73248. }
  73249. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73250. }
  73251. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73252. mesh.getDirectionToRef(upAxis, upAxis);
  73253. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73254. upAxis.normalize();
  73255. }
  73256. }
  73257. var checkYaw = false;
  73258. var checkPitch = false;
  73259. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73260. checkYaw = true;
  73261. }
  73262. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73263. checkPitch = true;
  73264. }
  73265. if (checkYaw || checkPitch) {
  73266. var spaceMat = BoneLookController._tmpMats[2];
  73267. var spaceMatInv = BoneLookController._tmpMats[3];
  73268. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73269. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73270. }
  73271. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73272. spaceMat.copyFrom(mesh.getWorldMatrix());
  73273. }
  73274. else {
  73275. var forwardAxis = BoneLookController._tmpVecs[2];
  73276. forwardAxis.copyFrom(this._fowardAxis);
  73277. if (this._transformYawPitch) {
  73278. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73279. }
  73280. if (parentBone) {
  73281. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73282. }
  73283. else {
  73284. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73285. }
  73286. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73287. rightAxis.normalize();
  73288. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73289. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73290. }
  73291. spaceMat.invertToRef(spaceMatInv);
  73292. var xzlen = null;
  73293. if (checkPitch) {
  73294. var localTarget = BoneLookController._tmpVecs[3];
  73295. target.subtractToRef(bonePos, localTarget);
  73296. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73297. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73298. var pitch = Math.atan2(localTarget.y, xzlen);
  73299. var newPitch = pitch;
  73300. if (pitch > this._maxPitch) {
  73301. localTarget.y = this._maxPitchTan * xzlen;
  73302. newPitch = this._maxPitch;
  73303. }
  73304. else if (pitch < this._minPitch) {
  73305. localTarget.y = this._minPitchTan * xzlen;
  73306. newPitch = this._minPitch;
  73307. }
  73308. if (pitch != newPitch) {
  73309. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73310. localTarget.addInPlace(bonePos);
  73311. target = localTarget;
  73312. }
  73313. }
  73314. if (checkYaw) {
  73315. var localTarget = BoneLookController._tmpVecs[4];
  73316. target.subtractToRef(bonePos, localTarget);
  73317. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73318. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73319. var newYaw = yaw;
  73320. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73321. if (xzlen == null) {
  73322. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73323. }
  73324. if (this._yawRange > Math.PI) {
  73325. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73326. localTarget.z = this._maxYawCos * xzlen;
  73327. localTarget.x = this._maxYawSin * xzlen;
  73328. newYaw = this._maxYaw;
  73329. }
  73330. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73331. localTarget.z = this._minYawCos * xzlen;
  73332. localTarget.x = this._minYawSin * xzlen;
  73333. newYaw = this._minYaw;
  73334. }
  73335. }
  73336. else {
  73337. if (yaw > this._maxYaw) {
  73338. localTarget.z = this._maxYawCos * xzlen;
  73339. localTarget.x = this._maxYawSin * xzlen;
  73340. newYaw = this._maxYaw;
  73341. }
  73342. else if (yaw < this._minYaw) {
  73343. localTarget.z = this._minYawCos * xzlen;
  73344. localTarget.x = this._minYawSin * xzlen;
  73345. newYaw = this._minYaw;
  73346. }
  73347. }
  73348. }
  73349. if (this._slerping && this._yawRange > Math.PI) {
  73350. //are we going to be crossing into the min/max region?
  73351. var boneFwd = BoneLookController._tmpVecs[8];
  73352. boneFwd.copyFrom(BABYLON.Axis.Z);
  73353. if (this._transformYawPitch) {
  73354. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73355. }
  73356. var boneRotMat = BoneLookController._tmpMats[4];
  73357. this._boneQuat.toRotationMatrix(boneRotMat);
  73358. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73359. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73360. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73361. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73362. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73363. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73364. if (angBtwTar > angBtwMidYaw) {
  73365. if (xzlen == null) {
  73366. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73367. }
  73368. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73369. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73370. if (angBtwMin < angBtwMax) {
  73371. newYaw = boneYaw + Math.PI * .75;
  73372. localTarget.z = Math.cos(newYaw) * xzlen;
  73373. localTarget.x = Math.sin(newYaw) * xzlen;
  73374. }
  73375. else {
  73376. newYaw = boneYaw - Math.PI * .75;
  73377. localTarget.z = Math.cos(newYaw) * xzlen;
  73378. localTarget.x = Math.sin(newYaw) * xzlen;
  73379. }
  73380. }
  73381. }
  73382. if (yaw != newYaw) {
  73383. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73384. localTarget.addInPlace(bonePos);
  73385. target = localTarget;
  73386. }
  73387. }
  73388. }
  73389. var zaxis = BoneLookController._tmpVecs[5];
  73390. var xaxis = BoneLookController._tmpVecs[6];
  73391. var yaxis = BoneLookController._tmpVecs[7];
  73392. var _tmpQuat = BoneLookController._tmpQuat;
  73393. target.subtractToRef(bonePos, zaxis);
  73394. zaxis.normalize();
  73395. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73396. xaxis.normalize();
  73397. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73398. yaxis.normalize();
  73399. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73400. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  73401. return;
  73402. }
  73403. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  73404. return;
  73405. }
  73406. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  73407. return;
  73408. }
  73409. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  73410. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  73411. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  73412. }
  73413. if (this.slerpAmount < 1) {
  73414. if (!this._slerping) {
  73415. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  73416. }
  73417. if (this._transformYawPitch) {
  73418. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73419. }
  73420. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  73421. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  73422. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  73423. this._slerping = true;
  73424. }
  73425. else {
  73426. if (this._transformYawPitch) {
  73427. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73428. }
  73429. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  73430. this._slerping = false;
  73431. }
  73432. };
  73433. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  73434. var angDiff = ang2 - ang1;
  73435. angDiff %= Math.PI * 2;
  73436. if (angDiff > Math.PI) {
  73437. angDiff -= Math.PI * 2;
  73438. }
  73439. else if (angDiff < -Math.PI) {
  73440. angDiff += Math.PI * 2;
  73441. }
  73442. return angDiff;
  73443. };
  73444. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  73445. ang1 %= (2 * Math.PI);
  73446. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73447. ang2 %= (2 * Math.PI);
  73448. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73449. var ab = 0;
  73450. if (ang1 < ang2) {
  73451. ab = ang2 - ang1;
  73452. }
  73453. else {
  73454. ab = ang1 - ang2;
  73455. }
  73456. if (ab > Math.PI) {
  73457. ab = Math.PI * 2 - ab;
  73458. }
  73459. return ab;
  73460. };
  73461. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  73462. ang %= (2 * Math.PI);
  73463. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  73464. ang1 %= (2 * Math.PI);
  73465. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73466. ang2 %= (2 * Math.PI);
  73467. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73468. if (ang1 < ang2) {
  73469. if (ang > ang1 && ang < ang2) {
  73470. return true;
  73471. }
  73472. }
  73473. else {
  73474. if (ang > ang2 && ang < ang1) {
  73475. return true;
  73476. }
  73477. }
  73478. return false;
  73479. };
  73480. 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()];
  73481. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  73482. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73483. return BoneLookController;
  73484. }());
  73485. BABYLON.BoneLookController = BoneLookController;
  73486. })(BABYLON || (BABYLON = {}));
  73487. //# sourceMappingURL=babylon.boneLookController.js.map
  73488. var BABYLON;
  73489. (function (BABYLON) {
  73490. var Skeleton = /** @class */ (function () {
  73491. function Skeleton(name, id, scene) {
  73492. this.name = name;
  73493. this.id = id;
  73494. this.bones = new Array();
  73495. this.needInitialSkinMatrix = false;
  73496. this._isDirty = true;
  73497. this._meshesWithPoseMatrix = new Array();
  73498. this._identity = BABYLON.Matrix.Identity();
  73499. this._ranges = {};
  73500. this._lastAbsoluteTransformsUpdateId = -1;
  73501. /**
  73502. * Specifies if the skeleton should be serialized.
  73503. */
  73504. this.doNotSerialize = false;
  73505. // Events
  73506. /**
  73507. * An event triggered before computing the skeleton's matrices
  73508. * @type {BABYLON.Observable}
  73509. */
  73510. this.onBeforeComputeObservable = new BABYLON.Observable();
  73511. this.bones = [];
  73512. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73513. scene.skeletons.push(this);
  73514. //make sure it will recalculate the matrix next time prepare is called.
  73515. this._isDirty = true;
  73516. }
  73517. // Members
  73518. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73519. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73520. return mesh._bonesTransformMatrices;
  73521. }
  73522. if (!this._transformMatrices) {
  73523. this.prepare();
  73524. }
  73525. return this._transformMatrices;
  73526. };
  73527. Skeleton.prototype.getScene = function () {
  73528. return this._scene;
  73529. };
  73530. // Methods
  73531. /**
  73532. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73533. */
  73534. Skeleton.prototype.toString = function (fullDetails) {
  73535. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73536. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73537. if (fullDetails) {
  73538. ret += ", Ranges: {";
  73539. var first = true;
  73540. for (var name_1 in this._ranges) {
  73541. if (first) {
  73542. ret += ", ";
  73543. first = false;
  73544. }
  73545. ret += name_1;
  73546. }
  73547. ret += "}";
  73548. }
  73549. return ret;
  73550. };
  73551. /**
  73552. * Get bone's index searching by name
  73553. * @param {string} name is bone's name to search for
  73554. * @return {number} Indice of the bone. Returns -1 if not found
  73555. */
  73556. Skeleton.prototype.getBoneIndexByName = function (name) {
  73557. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73558. if (this.bones[boneIndex].name === name) {
  73559. return boneIndex;
  73560. }
  73561. }
  73562. return -1;
  73563. };
  73564. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73565. // check name not already in use
  73566. if (!this._ranges[name]) {
  73567. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73568. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73569. if (this.bones[i].animations[0]) {
  73570. this.bones[i].animations[0].createRange(name, from, to);
  73571. }
  73572. }
  73573. }
  73574. };
  73575. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73576. if (deleteFrames === void 0) { deleteFrames = true; }
  73577. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73578. if (this.bones[i].animations[0]) {
  73579. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73580. }
  73581. }
  73582. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73583. };
  73584. Skeleton.prototype.getAnimationRange = function (name) {
  73585. return this._ranges[name];
  73586. };
  73587. /**
  73588. * Returns as an Array, all AnimationRanges defined on this skeleton
  73589. */
  73590. Skeleton.prototype.getAnimationRanges = function () {
  73591. var animationRanges = [];
  73592. var name;
  73593. var i = 0;
  73594. for (name in this._ranges) {
  73595. animationRanges[i] = this._ranges[name];
  73596. i++;
  73597. }
  73598. return animationRanges;
  73599. };
  73600. /**
  73601. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  73602. */
  73603. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  73604. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73605. if (this._ranges[name] || !source.getAnimationRange(name)) {
  73606. return false;
  73607. }
  73608. var ret = true;
  73609. var frameOffset = this._getHighestAnimationFrame() + 1;
  73610. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  73611. var boneDict = {};
  73612. var sourceBones = source.bones;
  73613. var nBones;
  73614. var i;
  73615. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  73616. boneDict[sourceBones[i].name] = sourceBones[i];
  73617. }
  73618. if (this.bones.length !== sourceBones.length) {
  73619. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  73620. ret = false;
  73621. }
  73622. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  73623. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73624. var boneName = this.bones[i].name;
  73625. var sourceBone = boneDict[boneName];
  73626. if (sourceBone) {
  73627. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73628. }
  73629. else {
  73630. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73631. ret = false;
  73632. }
  73633. }
  73634. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73635. var range = source.getAnimationRange(name);
  73636. if (range) {
  73637. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73638. }
  73639. return ret;
  73640. };
  73641. Skeleton.prototype.returnToRest = function () {
  73642. for (var index = 0; index < this.bones.length; index++) {
  73643. this.bones[index].returnToRest();
  73644. }
  73645. };
  73646. Skeleton.prototype._getHighestAnimationFrame = function () {
  73647. var ret = 0;
  73648. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73649. if (this.bones[i].animations[0]) {
  73650. var highest = this.bones[i].animations[0].getHighestFrame();
  73651. if (ret < highest) {
  73652. ret = highest;
  73653. }
  73654. }
  73655. }
  73656. return ret;
  73657. };
  73658. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73659. var range = this.getAnimationRange(name);
  73660. if (!range) {
  73661. return null;
  73662. }
  73663. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73664. };
  73665. Skeleton.prototype._markAsDirty = function () {
  73666. this._isDirty = true;
  73667. };
  73668. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73669. this._meshesWithPoseMatrix.push(mesh);
  73670. };
  73671. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73672. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73673. if (index > -1) {
  73674. this._meshesWithPoseMatrix.splice(index, 1);
  73675. }
  73676. };
  73677. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73678. this.onBeforeComputeObservable.notifyObservers(this);
  73679. for (var index = 0; index < this.bones.length; index++) {
  73680. var bone = this.bones[index];
  73681. var parentBone = bone.getParent();
  73682. if (parentBone) {
  73683. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73684. }
  73685. else {
  73686. if (initialSkinMatrix) {
  73687. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73688. }
  73689. else {
  73690. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73691. }
  73692. }
  73693. if (bone._index !== -1) {
  73694. var mappedIndex = bone._index === null ? index : bone._index;
  73695. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73696. }
  73697. }
  73698. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73699. };
  73700. Skeleton.prototype.prepare = function () {
  73701. if (!this._isDirty) {
  73702. return;
  73703. }
  73704. if (this.needInitialSkinMatrix) {
  73705. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73706. var mesh = this._meshesWithPoseMatrix[index];
  73707. var poseMatrix = mesh.getPoseMatrix();
  73708. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73709. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73710. }
  73711. if (this._synchronizedWithMesh !== mesh) {
  73712. this._synchronizedWithMesh = mesh;
  73713. // Prepare bones
  73714. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73715. var bone = this.bones[boneIndex];
  73716. if (!bone.getParent()) {
  73717. var matrix = bone.getBaseMatrix();
  73718. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73719. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73720. }
  73721. }
  73722. }
  73723. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73724. }
  73725. }
  73726. else {
  73727. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73728. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73729. }
  73730. this._computeTransformMatrices(this._transformMatrices, null);
  73731. }
  73732. this._isDirty = false;
  73733. this._scene._activeBones.addCount(this.bones.length, false);
  73734. };
  73735. Skeleton.prototype.getAnimatables = function () {
  73736. if (!this._animatables || this._animatables.length !== this.bones.length) {
  73737. this._animatables = [];
  73738. for (var index = 0; index < this.bones.length; index++) {
  73739. this._animatables.push(this.bones[index]);
  73740. }
  73741. }
  73742. return this._animatables;
  73743. };
  73744. Skeleton.prototype.clone = function (name, id) {
  73745. var result = new Skeleton(name, id || name, this._scene);
  73746. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73747. for (var index = 0; index < this.bones.length; index++) {
  73748. var source = this.bones[index];
  73749. var parentBone = null;
  73750. var parent_1 = source.getParent();
  73751. if (parent_1) {
  73752. var parentIndex = this.bones.indexOf(parent_1);
  73753. parentBone = result.bones[parentIndex];
  73754. }
  73755. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73756. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73757. }
  73758. if (this._ranges) {
  73759. result._ranges = {};
  73760. for (var rangeName in this._ranges) {
  73761. var range = this._ranges[rangeName];
  73762. if (range) {
  73763. result._ranges[rangeName] = range.clone();
  73764. }
  73765. }
  73766. }
  73767. this._isDirty = true;
  73768. return result;
  73769. };
  73770. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73771. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73772. this.bones.forEach(function (bone) {
  73773. bone.animations.forEach(function (animation) {
  73774. animation.enableBlending = true;
  73775. animation.blendingSpeed = blendingSpeed;
  73776. });
  73777. });
  73778. };
  73779. Skeleton.prototype.dispose = function () {
  73780. this._meshesWithPoseMatrix = [];
  73781. // Animations
  73782. this.getScene().stopAnimation(this);
  73783. // Remove from scene
  73784. this.getScene().removeSkeleton(this);
  73785. };
  73786. Skeleton.prototype.serialize = function () {
  73787. var serializationObject = {};
  73788. serializationObject.name = this.name;
  73789. serializationObject.id = this.id;
  73790. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73791. serializationObject.bones = [];
  73792. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73793. for (var index = 0; index < this.bones.length; index++) {
  73794. var bone = this.bones[index];
  73795. var parent_2 = bone.getParent();
  73796. var serializedBone = {
  73797. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  73798. name: bone.name,
  73799. matrix: bone.getBaseMatrix().toArray(),
  73800. rest: bone.getRestPose().toArray()
  73801. };
  73802. serializationObject.bones.push(serializedBone);
  73803. if (bone.length) {
  73804. serializedBone.length = bone.length;
  73805. }
  73806. if (bone.animations && bone.animations.length > 0) {
  73807. serializedBone.animation = bone.animations[0].serialize();
  73808. }
  73809. serializationObject.ranges = [];
  73810. for (var name in this._ranges) {
  73811. var source = this._ranges[name];
  73812. if (!source) {
  73813. continue;
  73814. }
  73815. var range = {};
  73816. range.name = name;
  73817. range.from = source.from;
  73818. range.to = source.to;
  73819. serializationObject.ranges.push(range);
  73820. }
  73821. }
  73822. return serializationObject;
  73823. };
  73824. Skeleton.Parse = function (parsedSkeleton, scene) {
  73825. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  73826. if (parsedSkeleton.dimensionsAtRest) {
  73827. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  73828. }
  73829. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  73830. var index;
  73831. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  73832. var parsedBone = parsedSkeleton.bones[index];
  73833. var parentBone = null;
  73834. if (parsedBone.parentBoneIndex > -1) {
  73835. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  73836. }
  73837. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  73838. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  73839. if (parsedBone.length) {
  73840. bone.length = parsedBone.length;
  73841. }
  73842. if (parsedBone.animation) {
  73843. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  73844. }
  73845. }
  73846. // placed after bones, so createAnimationRange can cascade down
  73847. if (parsedSkeleton.ranges) {
  73848. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  73849. var data = parsedSkeleton.ranges[index];
  73850. skeleton.createAnimationRange(data.name, data.from, data.to);
  73851. }
  73852. }
  73853. return skeleton;
  73854. };
  73855. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  73856. if (forceUpdate === void 0) { forceUpdate = false; }
  73857. var renderId = this._scene.getRenderId();
  73858. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  73859. this.bones[0].computeAbsoluteTransforms();
  73860. this._lastAbsoluteTransformsUpdateId = renderId;
  73861. }
  73862. };
  73863. Skeleton.prototype.getPoseMatrix = function () {
  73864. var poseMatrix = null;
  73865. if (this._meshesWithPoseMatrix.length > 0) {
  73866. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  73867. }
  73868. return poseMatrix;
  73869. };
  73870. Skeleton.prototype.sortBones = function () {
  73871. var bones = new Array();
  73872. var visited = new Array(this.bones.length);
  73873. for (var index = 0; index < this.bones.length; index++) {
  73874. this._sortBones(index, bones, visited);
  73875. }
  73876. this.bones = bones;
  73877. };
  73878. Skeleton.prototype._sortBones = function (index, bones, visited) {
  73879. if (visited[index]) {
  73880. return;
  73881. }
  73882. visited[index] = true;
  73883. var bone = this.bones[index];
  73884. if (bone._index === undefined) {
  73885. bone._index = index;
  73886. }
  73887. var parentBone = bone.getParent();
  73888. if (parentBone) {
  73889. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  73890. }
  73891. bones.push(bone);
  73892. };
  73893. return Skeleton;
  73894. }());
  73895. BABYLON.Skeleton = Skeleton;
  73896. })(BABYLON || (BABYLON = {}));
  73897. //# sourceMappingURL=babylon.skeleton.js.map
  73898. var BABYLON;
  73899. (function (BABYLON) {
  73900. var SphericalPolynomial = /** @class */ (function () {
  73901. function SphericalPolynomial() {
  73902. this.x = BABYLON.Vector3.Zero();
  73903. this.y = BABYLON.Vector3.Zero();
  73904. this.z = BABYLON.Vector3.Zero();
  73905. this.xx = BABYLON.Vector3.Zero();
  73906. this.yy = BABYLON.Vector3.Zero();
  73907. this.zz = BABYLON.Vector3.Zero();
  73908. this.xy = BABYLON.Vector3.Zero();
  73909. this.yz = BABYLON.Vector3.Zero();
  73910. this.zx = BABYLON.Vector3.Zero();
  73911. }
  73912. SphericalPolynomial.prototype.addAmbient = function (color) {
  73913. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73914. this.xx = this.xx.add(colorVector);
  73915. this.yy = this.yy.add(colorVector);
  73916. this.zz = this.zz.add(colorVector);
  73917. };
  73918. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73919. var result = new SphericalPolynomial();
  73920. result.x = harmonics.L11.scale(1.02333);
  73921. result.y = harmonics.L1_1.scale(1.02333);
  73922. result.z = harmonics.L10.scale(1.02333);
  73923. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73924. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73925. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73926. result.yz = harmonics.L2_1.scale(0.858086);
  73927. result.zx = harmonics.L21.scale(0.858086);
  73928. result.xy = harmonics.L2_2.scale(0.858086);
  73929. result.scale(1.0 / Math.PI);
  73930. return result;
  73931. };
  73932. SphericalPolynomial.prototype.scale = function (scale) {
  73933. this.x = this.x.scale(scale);
  73934. this.y = this.y.scale(scale);
  73935. this.z = this.z.scale(scale);
  73936. this.xx = this.xx.scale(scale);
  73937. this.yy = this.yy.scale(scale);
  73938. this.zz = this.zz.scale(scale);
  73939. this.yz = this.yz.scale(scale);
  73940. this.zx = this.zx.scale(scale);
  73941. this.xy = this.xy.scale(scale);
  73942. };
  73943. return SphericalPolynomial;
  73944. }());
  73945. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73946. var SphericalHarmonics = /** @class */ (function () {
  73947. function SphericalHarmonics() {
  73948. this.L00 = BABYLON.Vector3.Zero();
  73949. this.L1_1 = BABYLON.Vector3.Zero();
  73950. this.L10 = BABYLON.Vector3.Zero();
  73951. this.L11 = BABYLON.Vector3.Zero();
  73952. this.L2_2 = BABYLON.Vector3.Zero();
  73953. this.L2_1 = BABYLON.Vector3.Zero();
  73954. this.L20 = BABYLON.Vector3.Zero();
  73955. this.L21 = BABYLON.Vector3.Zero();
  73956. this.L22 = BABYLON.Vector3.Zero();
  73957. }
  73958. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73959. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73960. var c = colorVector.scale(deltaSolidAngle);
  73961. this.L00 = this.L00.add(c.scale(0.282095));
  73962. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73963. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73964. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73965. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73966. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73967. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73968. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73969. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73970. };
  73971. SphericalHarmonics.prototype.scale = function (scale) {
  73972. this.L00 = this.L00.scale(scale);
  73973. this.L1_1 = this.L1_1.scale(scale);
  73974. this.L10 = this.L10.scale(scale);
  73975. this.L11 = this.L11.scale(scale);
  73976. this.L2_2 = this.L2_2.scale(scale);
  73977. this.L2_1 = this.L2_1.scale(scale);
  73978. this.L20 = this.L20.scale(scale);
  73979. this.L21 = this.L21.scale(scale);
  73980. this.L22 = this.L22.scale(scale);
  73981. };
  73982. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73983. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73984. //
  73985. // E_lm = A_l * L_lm
  73986. //
  73987. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73988. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73989. // the scaling factors are given in equation 9.
  73990. // Constant (Band 0)
  73991. this.L00 = this.L00.scale(3.141593);
  73992. // Linear (Band 1)
  73993. this.L1_1 = this.L1_1.scale(2.094395);
  73994. this.L10 = this.L10.scale(2.094395);
  73995. this.L11 = this.L11.scale(2.094395);
  73996. // Quadratic (Band 2)
  73997. this.L2_2 = this.L2_2.scale(0.785398);
  73998. this.L2_1 = this.L2_1.scale(0.785398);
  73999. this.L20 = this.L20.scale(0.785398);
  74000. this.L21 = this.L21.scale(0.785398);
  74001. this.L22 = this.L22.scale(0.785398);
  74002. };
  74003. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74004. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74005. // L = (1/pi) * E * rho
  74006. //
  74007. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74008. this.scale(1.0 / Math.PI);
  74009. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74010. // (The pixel shader must apply albedo after texture fetches, etc).
  74011. };
  74012. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74013. var result = new SphericalHarmonics();
  74014. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74015. result.L1_1 = polynomial.y.scale(0.977204);
  74016. result.L10 = polynomial.z.scale(0.977204);
  74017. result.L11 = polynomial.x.scale(0.977204);
  74018. result.L2_2 = polynomial.xy.scale(1.16538);
  74019. result.L2_1 = polynomial.yz.scale(1.16538);
  74020. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74021. result.L21 = polynomial.zx.scale(1.16538);
  74022. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74023. result.scale(Math.PI);
  74024. return result;
  74025. };
  74026. return SphericalHarmonics;
  74027. }());
  74028. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74029. })(BABYLON || (BABYLON = {}));
  74030. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74031. var BABYLON;
  74032. (function (BABYLON) {
  74033. var FileFaceOrientation = /** @class */ (function () {
  74034. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74035. this.name = name;
  74036. this.worldAxisForNormal = worldAxisForNormal;
  74037. this.worldAxisForFileX = worldAxisForFileX;
  74038. this.worldAxisForFileY = worldAxisForFileY;
  74039. }
  74040. return FileFaceOrientation;
  74041. }());
  74042. ;
  74043. /**
  74044. * Helper class dealing with the extraction of spherical polynomial dataArray
  74045. * from a cube map.
  74046. */
  74047. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74048. function CubeMapToSphericalPolynomialTools() {
  74049. }
  74050. /**
  74051. * Converts a texture to the according Spherical Polynomial data.
  74052. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74053. *
  74054. * @param texture The texture to extract the information from.
  74055. * @return The Spherical Polynomial data.
  74056. */
  74057. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74058. if (!texture.isCube) {
  74059. // Only supports cube Textures currently.
  74060. return null;
  74061. }
  74062. var size = texture.getSize().width;
  74063. var right = texture.readPixels(0);
  74064. var left = texture.readPixels(1);
  74065. var up;
  74066. var down;
  74067. if (texture.isRenderTarget) {
  74068. up = texture.readPixels(3);
  74069. down = texture.readPixels(2);
  74070. }
  74071. else {
  74072. up = texture.readPixels(2);
  74073. down = texture.readPixels(3);
  74074. }
  74075. var front = texture.readPixels(4);
  74076. var back = texture.readPixels(5);
  74077. var gammaSpace = texture.gammaSpace;
  74078. // Always read as RGBA.
  74079. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74080. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74081. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74082. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74083. }
  74084. var cubeInfo = {
  74085. size: size,
  74086. right: right,
  74087. left: left,
  74088. up: up,
  74089. down: down,
  74090. front: front,
  74091. back: back,
  74092. format: format,
  74093. type: type,
  74094. gammaSpace: gammaSpace,
  74095. };
  74096. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74097. };
  74098. /**
  74099. * Converts a cubemap to the according Spherical Polynomial data.
  74100. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74101. *
  74102. * @param cubeInfo The Cube map to extract the information from.
  74103. * @return The Spherical Polynomial data.
  74104. */
  74105. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74106. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74107. var totalSolidAngle = 0.0;
  74108. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74109. var du = 2.0 / cubeInfo.size;
  74110. var dv = du;
  74111. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74112. var minUV = du * 0.5 - 1.0;
  74113. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74114. var fileFace = this.FileFaces[faceIndex];
  74115. var dataArray = cubeInfo[fileFace.name];
  74116. var v = minUV;
  74117. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74118. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74119. // Because SP is still linear, so summation is fine in that basis.
  74120. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74121. for (var y = 0; y < cubeInfo.size; y++) {
  74122. var u = minUV;
  74123. for (var x = 0; x < cubeInfo.size; x++) {
  74124. // World direction (not normalised)
  74125. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74126. worldDirection.normalize();
  74127. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74128. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74129. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74130. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74131. // Handle Integer types.
  74132. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74133. r /= 255;
  74134. g /= 255;
  74135. b /= 255;
  74136. }
  74137. // Handle Gamma space textures.
  74138. if (cubeInfo.gammaSpace) {
  74139. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74140. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74141. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74142. }
  74143. var color = new BABYLON.Color3(r, g, b);
  74144. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74145. totalSolidAngle += deltaSolidAngle;
  74146. u += du;
  74147. }
  74148. v += dv;
  74149. }
  74150. }
  74151. // Solid angle for entire sphere is 4*pi
  74152. var sphereSolidAngle = 4.0 * Math.PI;
  74153. // Adjust the solid angle to allow for how many faces we processed.
  74154. var facesProcessed = 6.0;
  74155. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74156. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74157. // This is needed because the numerical integration over the cube uses a
  74158. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74159. // and also to compensate for accumulative error due to float precision in the summation.
  74160. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74161. sphericalHarmonics.scale(correctionFactor);
  74162. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74163. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74164. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74165. };
  74166. CubeMapToSphericalPolynomialTools.FileFaces = [
  74167. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74168. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74169. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74170. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74171. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74172. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74173. ];
  74174. return CubeMapToSphericalPolynomialTools;
  74175. }());
  74176. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74177. })(BABYLON || (BABYLON = {}));
  74178. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74179. var BABYLON;
  74180. (function (BABYLON) {
  74181. /**
  74182. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74183. */
  74184. var PanoramaToCubeMapTools = /** @class */ (function () {
  74185. function PanoramaToCubeMapTools() {
  74186. }
  74187. /**
  74188. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74189. *
  74190. * @param float32Array The source data.
  74191. * @param inputWidth The width of the input panorama.
  74192. * @param inputhHeight The height of the input panorama.
  74193. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74194. * @return The cubemap data
  74195. */
  74196. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74197. if (!float32Array) {
  74198. throw "ConvertPanoramaToCubemap: input cannot be null";
  74199. }
  74200. if (float32Array.length != inputWidth * inputHeight * 3) {
  74201. throw "ConvertPanoramaToCubemap: input size is wrong";
  74202. }
  74203. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74204. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74205. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74206. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74207. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74208. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74209. return {
  74210. front: textureFront,
  74211. back: textureBack,
  74212. left: textureLeft,
  74213. right: textureRight,
  74214. up: textureUp,
  74215. down: textureDown,
  74216. size: size,
  74217. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74218. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74219. gammaSpace: false,
  74220. };
  74221. };
  74222. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74223. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74224. var textureArray = new Float32Array(buffer);
  74225. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74226. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74227. var dy = 1 / texSize;
  74228. var fy = 0;
  74229. for (var y = 0; y < texSize; y++) {
  74230. var xv1 = faceData[0];
  74231. var xv2 = faceData[2];
  74232. for (var x = 0; x < texSize; x++) {
  74233. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74234. v.normalize();
  74235. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74236. // 3 channels per pixels
  74237. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74238. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74239. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74240. xv1 = xv1.add(rotDX1);
  74241. xv2 = xv2.add(rotDX2);
  74242. }
  74243. fy += dy;
  74244. }
  74245. return textureArray;
  74246. };
  74247. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74248. var theta = Math.atan2(vDir.z, vDir.x);
  74249. var phi = Math.acos(vDir.y);
  74250. while (theta < -Math.PI)
  74251. theta += 2 * Math.PI;
  74252. while (theta > Math.PI)
  74253. theta -= 2 * Math.PI;
  74254. var dx = theta / Math.PI;
  74255. var dy = phi / Math.PI;
  74256. // recenter.
  74257. dx = dx * 0.5 + 0.5;
  74258. var px = Math.round(dx * inputWidth);
  74259. if (px < 0)
  74260. px = 0;
  74261. else if (px >= inputWidth)
  74262. px = inputWidth - 1;
  74263. var py = Math.round(dy * inputHeight);
  74264. if (py < 0)
  74265. py = 0;
  74266. else if (py >= inputHeight)
  74267. py = inputHeight - 1;
  74268. var inputY = (inputHeight - py - 1);
  74269. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74270. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74271. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74272. return {
  74273. r: r,
  74274. g: g,
  74275. b: b
  74276. };
  74277. };
  74278. PanoramaToCubeMapTools.FACE_FRONT = [
  74279. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74280. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74281. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74282. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74283. ];
  74284. PanoramaToCubeMapTools.FACE_BACK = [
  74285. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74286. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74287. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74288. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74289. ];
  74290. PanoramaToCubeMapTools.FACE_RIGHT = [
  74291. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74292. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74293. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74294. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74295. ];
  74296. PanoramaToCubeMapTools.FACE_LEFT = [
  74297. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74298. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74299. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74300. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74301. ];
  74302. PanoramaToCubeMapTools.FACE_DOWN = [
  74303. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74304. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74305. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74306. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74307. ];
  74308. PanoramaToCubeMapTools.FACE_UP = [
  74309. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74310. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74311. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74312. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74313. ];
  74314. return PanoramaToCubeMapTools;
  74315. }());
  74316. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74317. })(BABYLON || (BABYLON = {}));
  74318. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74319. var BABYLON;
  74320. (function (BABYLON) {
  74321. ;
  74322. /**
  74323. * This groups tools to convert HDR texture to native colors array.
  74324. */
  74325. var HDRTools = /** @class */ (function () {
  74326. function HDRTools() {
  74327. }
  74328. HDRTools.Ldexp = function (mantissa, exponent) {
  74329. if (exponent > 1023) {
  74330. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74331. }
  74332. if (exponent < -1074) {
  74333. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74334. }
  74335. return mantissa * Math.pow(2, exponent);
  74336. };
  74337. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74338. if (exponent > 0) {
  74339. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74340. float32array[index + 0] = red * exponent;
  74341. float32array[index + 1] = green * exponent;
  74342. float32array[index + 2] = blue * exponent;
  74343. }
  74344. else {
  74345. float32array[index + 0] = 0;
  74346. float32array[index + 1] = 0;
  74347. float32array[index + 2] = 0;
  74348. }
  74349. };
  74350. HDRTools.readStringLine = function (uint8array, startIndex) {
  74351. var line = "";
  74352. var character = "";
  74353. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74354. character = String.fromCharCode(uint8array[i]);
  74355. if (character == "\n") {
  74356. break;
  74357. }
  74358. line += character;
  74359. }
  74360. return line;
  74361. };
  74362. /**
  74363. * Reads header information from an RGBE texture stored in a native array.
  74364. * More information on this format are available here:
  74365. * https://en.wikipedia.org/wiki/RGBE_image_format
  74366. *
  74367. * @param uint8array The binary file stored in native array.
  74368. * @return The header information.
  74369. */
  74370. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74371. var height = 0;
  74372. var width = 0;
  74373. var line = this.readStringLine(uint8array, 0);
  74374. if (line[0] != '#' || line[1] != '?') {
  74375. throw "Bad HDR Format.";
  74376. }
  74377. var endOfHeader = false;
  74378. var findFormat = false;
  74379. var lineIndex = 0;
  74380. do {
  74381. lineIndex += (line.length + 1);
  74382. line = this.readStringLine(uint8array, lineIndex);
  74383. if (line == "FORMAT=32-bit_rle_rgbe") {
  74384. findFormat = true;
  74385. }
  74386. else if (line.length == 0) {
  74387. endOfHeader = true;
  74388. }
  74389. } while (!endOfHeader);
  74390. if (!findFormat) {
  74391. throw "HDR Bad header format, unsupported FORMAT";
  74392. }
  74393. lineIndex += (line.length + 1);
  74394. line = this.readStringLine(uint8array, lineIndex);
  74395. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  74396. var match = sizeRegexp.exec(line);
  74397. // TODO. Support +Y and -X if needed.
  74398. if (!match || match.length < 3) {
  74399. throw "HDR Bad header format, no size";
  74400. }
  74401. width = parseInt(match[2]);
  74402. height = parseInt(match[1]);
  74403. if (width < 8 || width > 0x7fff) {
  74404. throw "HDR Bad header format, unsupported size";
  74405. }
  74406. lineIndex += (line.length + 1);
  74407. return {
  74408. height: height,
  74409. width: width,
  74410. dataPosition: lineIndex
  74411. };
  74412. };
  74413. /**
  74414. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  74415. * This RGBE texture needs to store the information as a panorama.
  74416. *
  74417. * More information on this format are available here:
  74418. * https://en.wikipedia.org/wiki/RGBE_image_format
  74419. *
  74420. * @param buffer The binary file stored in an array buffer.
  74421. * @param size The expected size of the extracted cubemap.
  74422. * @return The Cube Map information.
  74423. */
  74424. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  74425. var uint8array = new Uint8Array(buffer);
  74426. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  74427. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74428. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  74429. return cubeMapData;
  74430. };
  74431. /**
  74432. * Returns the pixels data extracted from an RGBE texture.
  74433. * This pixels will be stored left to right up to down in the R G B order in one array.
  74434. *
  74435. * More information on this format are available here:
  74436. * https://en.wikipedia.org/wiki/RGBE_image_format
  74437. *
  74438. * @param uint8array The binary file stored in an array buffer.
  74439. * @param hdrInfo The header information of the file.
  74440. * @return The pixels data in RGB right to left up to down order.
  74441. */
  74442. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  74443. // Keep for multi format supports.
  74444. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74445. };
  74446. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  74447. var num_scanlines = hdrInfo.height;
  74448. var scanline_width = hdrInfo.width;
  74449. var a, b, c, d, count;
  74450. var dataIndex = hdrInfo.dataPosition;
  74451. var index = 0, endIndex = 0, i = 0;
  74452. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  74453. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  74454. // 3 channels of 4 bytes per pixel in float.
  74455. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  74456. var resultArray = new Float32Array(resultBuffer);
  74457. // read in each successive scanline
  74458. while (num_scanlines > 0) {
  74459. a = uint8array[dataIndex++];
  74460. b = uint8array[dataIndex++];
  74461. c = uint8array[dataIndex++];
  74462. d = uint8array[dataIndex++];
  74463. if (a != 2 || b != 2 || (c & 0x80)) {
  74464. // this file is not run length encoded
  74465. throw "HDR Bad header format, not RLE";
  74466. }
  74467. if (((c << 8) | d) != scanline_width) {
  74468. throw "HDR Bad header format, wrong scan line width";
  74469. }
  74470. index = 0;
  74471. // read each of the four channels for the scanline into the buffer
  74472. for (i = 0; i < 4; i++) {
  74473. endIndex = (i + 1) * scanline_width;
  74474. while (index < endIndex) {
  74475. a = uint8array[dataIndex++];
  74476. b = uint8array[dataIndex++];
  74477. if (a > 128) {
  74478. // a run of the same value
  74479. count = a - 128;
  74480. if ((count == 0) || (count > endIndex - index)) {
  74481. throw "HDR Bad Format, bad scanline data (run)";
  74482. }
  74483. while (count-- > 0) {
  74484. scanLineArray[index++] = b;
  74485. }
  74486. }
  74487. else {
  74488. // a non-run
  74489. count = a;
  74490. if ((count == 0) || (count > endIndex - index)) {
  74491. throw "HDR Bad Format, bad scanline data (non-run)";
  74492. }
  74493. scanLineArray[index++] = b;
  74494. if (--count > 0) {
  74495. for (var j = 0; j < count; j++) {
  74496. scanLineArray[index++] = uint8array[dataIndex++];
  74497. }
  74498. }
  74499. }
  74500. }
  74501. }
  74502. // now convert data from buffer into floats
  74503. for (i = 0; i < scanline_width; i++) {
  74504. a = scanLineArray[i];
  74505. b = scanLineArray[i + scanline_width];
  74506. c = scanLineArray[i + 2 * scanline_width];
  74507. d = scanLineArray[i + 3 * scanline_width];
  74508. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74509. }
  74510. num_scanlines--;
  74511. }
  74512. return resultArray;
  74513. };
  74514. return HDRTools;
  74515. }());
  74516. BABYLON.HDRTools = HDRTools;
  74517. })(BABYLON || (BABYLON = {}));
  74518. //# sourceMappingURL=babylon.hdr.js.map
  74519. var BABYLON;
  74520. (function (BABYLON) {
  74521. /**
  74522. * This represents a texture coming from an HDR input.
  74523. *
  74524. * The only supported format is currently panorama picture stored in RGBE format.
  74525. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74526. */
  74527. var HDRCubeTexture = /** @class */ (function (_super) {
  74528. __extends(HDRCubeTexture, _super);
  74529. /**
  74530. * Instantiates an HDRTexture from the following parameters.
  74531. *
  74532. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74533. * @param scene The scene the texture will be used in
  74534. * @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.
  74535. * @param noMipmap Forces to not generate the mipmap if true
  74536. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74537. * @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)
  74538. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74539. */
  74540. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74541. if (noMipmap === void 0) { noMipmap = false; }
  74542. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74543. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74544. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74545. if (onLoad === void 0) { onLoad = null; }
  74546. if (onError === void 0) { onError = null; }
  74547. var _this = _super.call(this, scene) || this;
  74548. _this._useInGammaSpace = false;
  74549. _this._generateHarmonics = true;
  74550. _this._isBABYLONPreprocessed = false;
  74551. _this._onLoad = null;
  74552. _this._onError = null;
  74553. /**
  74554. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74555. */
  74556. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74557. /**
  74558. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74559. * This is usefull at run time to apply the good shader.
  74560. */
  74561. _this.isPMREM = false;
  74562. _this._isBlocking = true;
  74563. /**
  74564. * Gets or sets the center of the bounding box associated with the cube texture
  74565. * It must define where the camera used to render the texture was set
  74566. */
  74567. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74568. if (!url) {
  74569. return _this;
  74570. }
  74571. _this.name = url;
  74572. _this.url = url;
  74573. _this.hasAlpha = false;
  74574. _this.isCube = true;
  74575. _this._textureMatrix = BABYLON.Matrix.Identity();
  74576. _this._onLoad = onLoad;
  74577. _this._onError = onError;
  74578. _this.gammaSpace = false;
  74579. var caps = scene.getEngine().getCaps();
  74580. if (size) {
  74581. _this._isBABYLONPreprocessed = false;
  74582. _this._noMipmap = noMipmap;
  74583. _this._size = size;
  74584. _this._useInGammaSpace = useInGammaSpace;
  74585. _this._usePMREMGenerator = usePMREMGenerator &&
  74586. caps.textureLOD &&
  74587. caps.textureFloat &&
  74588. !_this._useInGammaSpace;
  74589. }
  74590. else {
  74591. _this._isBABYLONPreprocessed = true;
  74592. _this._noMipmap = false;
  74593. _this._useInGammaSpace = false;
  74594. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  74595. !_this._useInGammaSpace;
  74596. }
  74597. _this.isPMREM = _this._usePMREMGenerator;
  74598. _this._texture = _this._getFromCache(url, _this._noMipmap);
  74599. if (!_this._texture) {
  74600. if (!scene.useDelayedTextureLoading) {
  74601. _this.loadTexture();
  74602. }
  74603. else {
  74604. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  74605. }
  74606. }
  74607. return _this;
  74608. }
  74609. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  74610. /**
  74611. * Gets wether or not the texture is blocking during loading.
  74612. */
  74613. get: function () {
  74614. return this._isBlocking;
  74615. },
  74616. /**
  74617. * Sets wether or not the texture is blocking during loading.
  74618. */
  74619. set: function (value) {
  74620. this._isBlocking = value;
  74621. },
  74622. enumerable: true,
  74623. configurable: true
  74624. });
  74625. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74626. get: function () {
  74627. return this._boundingBoxSize;
  74628. },
  74629. /**
  74630. * Gets or sets the size of the bounding box associated with the cube texture
  74631. * When defined, the cubemap will switch to local mode
  74632. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74633. * @example https://www.babylonjs-playground.com/#RNASML
  74634. */
  74635. set: function (value) {
  74636. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74637. return;
  74638. }
  74639. this._boundingBoxSize = value;
  74640. var scene = this.getScene();
  74641. if (scene) {
  74642. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74643. }
  74644. },
  74645. enumerable: true,
  74646. configurable: true
  74647. });
  74648. /**
  74649. * Occurs when the file is a preprocessed .babylon.hdr file.
  74650. */
  74651. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74652. var _this = this;
  74653. var mipLevels = 0;
  74654. var floatArrayView = null;
  74655. var scene = this.getScene();
  74656. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74657. var mips = new Array();
  74658. if (!floatArrayView) {
  74659. return mips;
  74660. }
  74661. var startIndex = 30;
  74662. for (var level = 0; level < mipLevels; level++) {
  74663. mips.push([]);
  74664. // Fill each pixel of the mip level.
  74665. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74666. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74667. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74668. mips[level].push(faceData);
  74669. startIndex += faceSize;
  74670. }
  74671. }
  74672. return mips;
  74673. } : null;
  74674. var callback = function (buffer) {
  74675. var scene = _this.getScene();
  74676. if (!scene) {
  74677. return null;
  74678. }
  74679. // Create Native Array Views
  74680. var intArrayView = new Int32Array(buffer);
  74681. floatArrayView = new Float32Array(buffer);
  74682. // Fill header.
  74683. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74684. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74685. // Update Texture Information.
  74686. if (!_this._texture) {
  74687. return null;
  74688. }
  74689. _this._texture.updateSize(_this._size, _this._size);
  74690. // Fill polynomial information.
  74691. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74692. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74693. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74694. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74695. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74696. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74697. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74698. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74699. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74700. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74701. _this.sphericalPolynomial = sphericalPolynomial;
  74702. // Fill pixel data.
  74703. mipLevels = intArrayView[29]; // Number of mip levels.
  74704. var startIndex = 30;
  74705. var data = [];
  74706. var faceSize = Math.pow(_this._size, 2) * 3;
  74707. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74708. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74709. startIndex += faceSize;
  74710. }
  74711. var results = [];
  74712. var byteArray = null;
  74713. // Push each faces.
  74714. for (var k = 0; k < 6; k++) {
  74715. var dataFace = null;
  74716. // To be deprecated.
  74717. if (version === 1) {
  74718. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74719. dataFace = data[j];
  74720. }
  74721. // If special cases.
  74722. if (!mipmapGenerator && dataFace) {
  74723. if (!scene.getEngine().getCaps().textureFloat) {
  74724. // 3 channels of 1 bytes per pixel in bytes.
  74725. var byteBuffer = new ArrayBuffer(faceSize);
  74726. byteArray = new Uint8Array(byteBuffer);
  74727. }
  74728. for (var i = 0; i < _this._size * _this._size; i++) {
  74729. // Put in gamma space if requested.
  74730. if (_this._useInGammaSpace) {
  74731. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74732. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74733. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74734. }
  74735. // Convert to int texture for fallback.
  74736. if (byteArray) {
  74737. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74738. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74739. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74740. // May use luminance instead if the result is not accurate.
  74741. var max = Math.max(Math.max(r, g), b);
  74742. if (max > 255) {
  74743. var scale = 255 / max;
  74744. r *= scale;
  74745. g *= scale;
  74746. b *= scale;
  74747. }
  74748. byteArray[(i * 3) + 0] = r;
  74749. byteArray[(i * 3) + 1] = g;
  74750. byteArray[(i * 3) + 2] = b;
  74751. }
  74752. }
  74753. }
  74754. // Fill the array accordingly.
  74755. if (byteArray) {
  74756. results.push(byteArray);
  74757. }
  74758. else {
  74759. results.push(dataFace);
  74760. }
  74761. }
  74762. return results;
  74763. };
  74764. if (scene) {
  74765. 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);
  74766. }
  74767. };
  74768. /**
  74769. * Occurs when the file is raw .hdr file.
  74770. */
  74771. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74772. var _this = this;
  74773. var callback = function (buffer) {
  74774. var scene = _this.getScene();
  74775. if (!scene) {
  74776. return null;
  74777. }
  74778. // Extract the raw linear data.
  74779. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74780. // Generate harmonics if needed.
  74781. if (_this._generateHarmonics) {
  74782. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74783. _this.sphericalPolynomial = sphericalPolynomial;
  74784. }
  74785. var results = [];
  74786. var byteArray = null;
  74787. // Push each faces.
  74788. for (var j = 0; j < 6; j++) {
  74789. // Create uintarray fallback.
  74790. if (!scene.getEngine().getCaps().textureFloat) {
  74791. // 3 channels of 1 bytes per pixel in bytes.
  74792. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  74793. byteArray = new Uint8Array(byteBuffer);
  74794. }
  74795. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  74796. // If special cases.
  74797. if (_this._useInGammaSpace || byteArray) {
  74798. for (var i = 0; i < _this._size * _this._size; i++) {
  74799. // Put in gamma space if requested.
  74800. if (_this._useInGammaSpace) {
  74801. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74802. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74803. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74804. }
  74805. // Convert to int texture for fallback.
  74806. if (byteArray) {
  74807. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74808. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74809. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74810. // May use luminance instead if the result is not accurate.
  74811. var max = Math.max(Math.max(r, g), b);
  74812. if (max > 255) {
  74813. var scale = 255 / max;
  74814. r *= scale;
  74815. g *= scale;
  74816. b *= scale;
  74817. }
  74818. byteArray[(i * 3) + 0] = r;
  74819. byteArray[(i * 3) + 1] = g;
  74820. byteArray[(i * 3) + 2] = b;
  74821. }
  74822. }
  74823. }
  74824. if (byteArray) {
  74825. results.push(byteArray);
  74826. }
  74827. else {
  74828. results.push(dataFace);
  74829. }
  74830. }
  74831. return results;
  74832. };
  74833. var mipmapGenerator = null;
  74834. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  74835. // if (!this._noMipmap &&
  74836. // this._usePMREMGenerator) {
  74837. // mipmapGenerator = (data: ArrayBufferView[]) => {
  74838. // // Custom setup of the generator matching with the PBR shader values.
  74839. // var generator = new BABYLON.PMREMGenerator(data,
  74840. // this._size,
  74841. // this._size,
  74842. // 0,
  74843. // 3,
  74844. // this.getScene().getEngine().getCaps().textureFloat,
  74845. // 2048,
  74846. // 0.25,
  74847. // false,
  74848. // true);
  74849. // return generator.filterCubeMap();
  74850. // };
  74851. // }
  74852. var scene = this.getScene();
  74853. if (scene) {
  74854. 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);
  74855. }
  74856. };
  74857. /**
  74858. * Starts the loading process of the texture.
  74859. */
  74860. HDRCubeTexture.prototype.loadTexture = function () {
  74861. if (this._isBABYLONPreprocessed) {
  74862. this.loadBabylonTexture();
  74863. }
  74864. else {
  74865. this.loadHDRTexture();
  74866. }
  74867. };
  74868. HDRCubeTexture.prototype.clone = function () {
  74869. var scene = this.getScene();
  74870. if (!scene) {
  74871. return this;
  74872. }
  74873. var size = (this._isBABYLONPreprocessed ? null : this._size);
  74874. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  74875. // Base texture
  74876. newTexture.level = this.level;
  74877. newTexture.wrapU = this.wrapU;
  74878. newTexture.wrapV = this.wrapV;
  74879. newTexture.coordinatesIndex = this.coordinatesIndex;
  74880. newTexture.coordinatesMode = this.coordinatesMode;
  74881. return newTexture;
  74882. };
  74883. // Methods
  74884. HDRCubeTexture.prototype.delayLoad = function () {
  74885. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  74886. return;
  74887. }
  74888. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  74889. this._texture = this._getFromCache(this.url, this._noMipmap);
  74890. if (!this._texture) {
  74891. this.loadTexture();
  74892. }
  74893. };
  74894. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  74895. return this._textureMatrix;
  74896. };
  74897. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  74898. this._textureMatrix = value;
  74899. };
  74900. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  74901. var texture = null;
  74902. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74903. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74904. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74905. texture.name = parsedTexture.name;
  74906. texture.hasAlpha = parsedTexture.hasAlpha;
  74907. texture.level = parsedTexture.level;
  74908. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74909. texture.isBlocking = parsedTexture.isBlocking;
  74910. }
  74911. if (texture) {
  74912. if (parsedTexture.boundingBoxPosition) {
  74913. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74914. }
  74915. if (parsedTexture.boundingBoxSize) {
  74916. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74917. }
  74918. }
  74919. return texture;
  74920. };
  74921. HDRCubeTexture.prototype.serialize = function () {
  74922. if (!this.name) {
  74923. return null;
  74924. }
  74925. var serializationObject = {};
  74926. serializationObject.name = this.name;
  74927. serializationObject.hasAlpha = this.hasAlpha;
  74928. serializationObject.isCube = true;
  74929. serializationObject.level = this.level;
  74930. serializationObject.size = this._size;
  74931. serializationObject.coordinatesMode = this.coordinatesMode;
  74932. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74933. serializationObject.generateHarmonics = this._generateHarmonics;
  74934. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74935. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74936. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74937. serializationObject.noMipmap = this._noMipmap;
  74938. serializationObject.isBlocking = this._isBlocking;
  74939. return serializationObject;
  74940. };
  74941. /**
  74942. * Saves as a file the data contained in the texture in a binary format.
  74943. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74944. * as the spherical used in the lighting.
  74945. * @param url The HDR file url.
  74946. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74947. * @param onError Method called if any error happens during download.
  74948. * @return The packed binary data.
  74949. */
  74950. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74951. if (onError === void 0) { onError = null; }
  74952. var callback = function (buffer) {
  74953. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74954. // Returns a URL you can use as a href.
  74955. var objUrl = window.URL.createObjectURL(data);
  74956. // Simulates a link to it and click to dowload.
  74957. var a = document.createElement("a");
  74958. document.body.appendChild(a);
  74959. a.style.display = "none";
  74960. a.href = objUrl;
  74961. a.download = "envmap.babylon.hdr";
  74962. a.click();
  74963. };
  74964. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74965. };
  74966. /**
  74967. * Serializes the data contained in the texture in a binary format.
  74968. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74969. * as the spherical used in the lighting.
  74970. * @param url The HDR file url.
  74971. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74972. * @param onError Method called if any error happens during download.
  74973. * @return The packed binary data.
  74974. */
  74975. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74976. if (onError === void 0) { onError = null; }
  74977. // Needs the url tho create the texture.
  74978. if (!url) {
  74979. return;
  74980. }
  74981. // Check Power of two size.
  74982. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74983. return;
  74984. }
  74985. // Coming Back in 3.x.
  74986. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74987. };
  74988. HDRCubeTexture._facesMapping = [
  74989. "right",
  74990. "left",
  74991. "up",
  74992. "down",
  74993. "front",
  74994. "back"
  74995. ];
  74996. return HDRCubeTexture;
  74997. }(BABYLON.BaseTexture));
  74998. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74999. })(BABYLON || (BABYLON = {}));
  75000. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75001. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75002. // Huge respect for a such great lib.
  75003. // Earcut license:
  75004. // Copyright (c) 2016, Mapbox
  75005. //
  75006. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75007. // with or without fee is hereby granted, provided that the above copyright notice
  75008. // and this permission notice appear in all copies.
  75009. //
  75010. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75011. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75012. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75013. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75014. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75015. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75016. // THIS SOFTWARE.
  75017. var Earcut;
  75018. (function (Earcut) {
  75019. /**
  75020. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75021. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75022. * @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).
  75023. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75024. */
  75025. function earcut(data, holeIndices, dim) {
  75026. dim = dim || 2;
  75027. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75028. if (!outerNode)
  75029. return triangles;
  75030. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75031. if (hasHoles)
  75032. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75033. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75034. if (data.length > 80 * dim) {
  75035. minX = maxX = data[0];
  75036. minY = maxY = data[1];
  75037. for (var i = dim; i < outerLen; i += dim) {
  75038. x = data[i];
  75039. y = data[i + 1];
  75040. if (x < minX)
  75041. minX = x;
  75042. if (y < minY)
  75043. minY = y;
  75044. if (x > maxX)
  75045. maxX = x;
  75046. if (y > maxY)
  75047. maxY = y;
  75048. }
  75049. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75050. size = Math.max(maxX - minX, maxY - minY);
  75051. }
  75052. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75053. return triangles;
  75054. }
  75055. Earcut.earcut = earcut;
  75056. var Node = /** @class */ (function () {
  75057. function Node(i, x, y) {
  75058. this.i = i;
  75059. this.x = x;
  75060. this.y = y;
  75061. this.prev = null;
  75062. this.next = null;
  75063. this.z = null;
  75064. this.prevZ = null;
  75065. this.nextZ = null;
  75066. this.steiner = false;
  75067. }
  75068. return Node;
  75069. }());
  75070. // create a circular doubly linked list from polygon points in the specified winding order
  75071. function linkedList(data, start, end, dim, clockwise) {
  75072. var i, last = null;
  75073. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75074. for (i = start; i < end; i += dim)
  75075. last = insertNode(i, data[i], data[i + 1], last);
  75076. }
  75077. else {
  75078. for (i = end - dim; i >= start; i -= dim)
  75079. last = insertNode(i, data[i], data[i + 1], last);
  75080. }
  75081. if (last && equals(last, last.next)) {
  75082. removeNode(last);
  75083. last = last.next;
  75084. }
  75085. return last;
  75086. }
  75087. // eliminate colinear or duplicate points
  75088. function filterPoints(start, end) {
  75089. if (!start)
  75090. return start;
  75091. if (!end)
  75092. end = start;
  75093. var p = start, again;
  75094. do {
  75095. again = false;
  75096. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75097. removeNode(p);
  75098. p = end = p.prev;
  75099. if (p === p.next)
  75100. return undefined;
  75101. again = true;
  75102. }
  75103. else {
  75104. p = p.next;
  75105. }
  75106. } while (again || p !== end);
  75107. return end;
  75108. }
  75109. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75110. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75111. if (!ear)
  75112. return;
  75113. // interlink polygon nodes in z-order
  75114. if (!pass && size)
  75115. indexCurve(ear, minX, minY, size);
  75116. var stop = ear, prev, next;
  75117. // iterate through ears, slicing them one by one
  75118. while (ear.prev !== ear.next) {
  75119. prev = ear.prev;
  75120. next = ear.next;
  75121. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75122. // cut off the triangle
  75123. triangles.push(prev.i / dim);
  75124. triangles.push(ear.i / dim);
  75125. triangles.push(next.i / dim);
  75126. removeNode(ear);
  75127. // skipping the next vertice leads to less sliver triangles
  75128. ear = next.next;
  75129. stop = next.next;
  75130. continue;
  75131. }
  75132. ear = next;
  75133. // if we looped through the whole remaining polygon and can't find any more ears
  75134. if (ear === stop) {
  75135. // try filtering points and slicing again
  75136. if (!pass) {
  75137. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75138. // if this didn't work, try curing all small self-intersections locally
  75139. }
  75140. else if (pass === 1) {
  75141. ear = cureLocalIntersections(ear, triangles, dim);
  75142. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75143. // as a last resort, try splitting the remaining polygon into two
  75144. }
  75145. else if (pass === 2) {
  75146. splitEarcut(ear, triangles, dim, minX, minY, size);
  75147. }
  75148. break;
  75149. }
  75150. }
  75151. }
  75152. // check whether a polygon node forms a valid ear with adjacent nodes
  75153. function isEar(ear) {
  75154. var a = ear.prev, b = ear, c = ear.next;
  75155. if (area(a, b, c) >= 0)
  75156. return false; // reflex, can't be an ear
  75157. // now make sure we don't have other points inside the potential ear
  75158. var p = ear.next.next;
  75159. while (p !== ear.prev) {
  75160. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75161. area(p.prev, p, p.next) >= 0)
  75162. return false;
  75163. p = p.next;
  75164. }
  75165. return true;
  75166. }
  75167. function isEarHashed(ear, minX, minY, size) {
  75168. var a = ear.prev, b = ear, c = ear.next;
  75169. if (area(a, b, c) >= 0)
  75170. return false; // reflex, can't be an ear
  75171. // triangle bbox; min & max are calculated like this for speed
  75172. 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);
  75173. // z-order range for the current triangle bbox;
  75174. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75175. // first look for points inside the triangle in increasing z-order
  75176. var p = ear.nextZ;
  75177. while (p && p.z <= maxZ) {
  75178. if (p !== ear.prev &&
  75179. p !== ear.next &&
  75180. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75181. area(p.prev, p, p.next) >= 0)
  75182. return false;
  75183. p = p.nextZ;
  75184. }
  75185. // then look for points in decreasing z-order
  75186. p = ear.prevZ;
  75187. while (p && p.z >= minZ) {
  75188. if (p !== ear.prev &&
  75189. p !== ear.next &&
  75190. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75191. area(p.prev, p, p.next) >= 0)
  75192. return false;
  75193. p = p.prevZ;
  75194. }
  75195. return true;
  75196. }
  75197. // go through all polygon nodes and cure small local self-intersections
  75198. function cureLocalIntersections(start, triangles, dim) {
  75199. var p = start;
  75200. do {
  75201. var a = p.prev, b = p.next.next;
  75202. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75203. triangles.push(a.i / dim);
  75204. triangles.push(p.i / dim);
  75205. triangles.push(b.i / dim);
  75206. // remove two nodes involved
  75207. removeNode(p);
  75208. removeNode(p.next);
  75209. p = start = b;
  75210. }
  75211. p = p.next;
  75212. } while (p !== start);
  75213. return p;
  75214. }
  75215. // try splitting polygon into two and triangulate them independently
  75216. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75217. // look for a valid diagonal that divides the polygon into two
  75218. var a = start;
  75219. do {
  75220. var b = a.next.next;
  75221. while (b !== a.prev) {
  75222. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75223. // split the polygon in two by the diagonal
  75224. var c = splitPolygon(a, b);
  75225. // filter colinear points around the cuts
  75226. a = filterPoints(a, a.next);
  75227. c = filterPoints(c, c.next);
  75228. // run earcut on each half
  75229. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75230. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75231. return;
  75232. }
  75233. b = b.next;
  75234. }
  75235. a = a.next;
  75236. } while (a !== start);
  75237. }
  75238. // link every hole into the outer loop, producing a single-ring polygon without holes
  75239. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75240. var queue = [], i, len, start, end, list;
  75241. for (i = 0, len = holeIndices.length; i < len; i++) {
  75242. start = holeIndices[i] * dim;
  75243. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75244. list = linkedList(data, start, end, dim, false);
  75245. if (list === list.next)
  75246. list.steiner = true;
  75247. queue.push(getLeftmost(list));
  75248. }
  75249. queue.sort(compareX);
  75250. // process holes from left to right
  75251. for (i = 0; i < queue.length; i++) {
  75252. eliminateHole(queue[i], outerNode);
  75253. outerNode = filterPoints(outerNode, outerNode.next);
  75254. }
  75255. return outerNode;
  75256. }
  75257. function compareX(a, b) {
  75258. return a.x - b.x;
  75259. }
  75260. // find a bridge between vertices that connects hole with an outer ring and and link it
  75261. function eliminateHole(hole, outerNode) {
  75262. outerNode = findHoleBridge(hole, outerNode);
  75263. if (outerNode) {
  75264. var b = splitPolygon(outerNode, hole);
  75265. filterPoints(b, b.next);
  75266. }
  75267. }
  75268. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75269. function findHoleBridge(hole, outerNode) {
  75270. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75271. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75272. // segment's endpoint with lesser x will be potential connection point
  75273. do {
  75274. if (hy <= p.y && hy >= p.next.y) {
  75275. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75276. if (x <= hx && x > qx) {
  75277. qx = x;
  75278. if (x === hx) {
  75279. if (hy === p.y)
  75280. return p;
  75281. if (hy === p.next.y)
  75282. return p.next;
  75283. }
  75284. m = p.x < p.next.x ? p : p.next;
  75285. }
  75286. }
  75287. p = p.next;
  75288. } while (p !== outerNode);
  75289. if (!m)
  75290. return null;
  75291. if (hx === qx)
  75292. return m.prev; // hole touches outer segment; pick lower endpoint
  75293. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75294. // if there are no points found, we have a valid connection;
  75295. // otherwise choose the point of the minimum angle with the ray as connection point
  75296. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75297. p = m.next;
  75298. while (p !== stop) {
  75299. if (hx >= p.x &&
  75300. p.x >= mx &&
  75301. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75302. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75303. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75304. m = p;
  75305. tanMin = tan;
  75306. }
  75307. }
  75308. p = p.next;
  75309. }
  75310. return m;
  75311. }
  75312. // interlink polygon nodes in z-order
  75313. function indexCurve(start, minX, minY, size) {
  75314. var p = start;
  75315. do {
  75316. if (p.z === null)
  75317. p.z = zOrder(p.x, p.y, minX, minY, size);
  75318. p.prevZ = p.prev;
  75319. p.nextZ = p.next;
  75320. p = p.next;
  75321. } while (p !== start);
  75322. p.prevZ.nextZ = null;
  75323. p.prevZ = null;
  75324. sortLinked(p);
  75325. }
  75326. // Simon Tatham's linked list merge sort algorithm
  75327. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75328. function sortLinked(list) {
  75329. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75330. do {
  75331. p = list;
  75332. list = null;
  75333. tail = null;
  75334. numMerges = 0;
  75335. while (p) {
  75336. numMerges++;
  75337. q = p;
  75338. pSize = 0;
  75339. for (i = 0; i < inSize; i++) {
  75340. pSize++;
  75341. q = q.nextZ;
  75342. if (!q)
  75343. break;
  75344. }
  75345. qSize = inSize;
  75346. while (pSize > 0 || (qSize > 0 && q)) {
  75347. if (pSize === 0) {
  75348. e = q;
  75349. q = q.nextZ;
  75350. qSize--;
  75351. }
  75352. else if (qSize === 0 || !q) {
  75353. e = p;
  75354. p = p.nextZ;
  75355. pSize--;
  75356. }
  75357. else if (p.z <= q.z) {
  75358. e = p;
  75359. p = p.nextZ;
  75360. pSize--;
  75361. }
  75362. else {
  75363. e = q;
  75364. q = q.nextZ;
  75365. qSize--;
  75366. }
  75367. if (tail)
  75368. tail.nextZ = e;
  75369. else
  75370. list = e;
  75371. e.prevZ = tail;
  75372. tail = e;
  75373. }
  75374. p = q;
  75375. }
  75376. tail.nextZ = null;
  75377. inSize *= 2;
  75378. } while (numMerges > 1);
  75379. return list;
  75380. }
  75381. // z-order of a point given coords and size of the data bounding box
  75382. function zOrder(x, y, minX, minY, size) {
  75383. // coords are transformed into non-negative 15-bit integer range
  75384. x = 32767 * (x - minX) / size;
  75385. y = 32767 * (y - minY) / size;
  75386. x = (x | (x << 8)) & 0x00FF00FF;
  75387. x = (x | (x << 4)) & 0x0F0F0F0F;
  75388. x = (x | (x << 2)) & 0x33333333;
  75389. x = (x | (x << 1)) & 0x55555555;
  75390. y = (y | (y << 8)) & 0x00FF00FF;
  75391. y = (y | (y << 4)) & 0x0F0F0F0F;
  75392. y = (y | (y << 2)) & 0x33333333;
  75393. y = (y | (y << 1)) & 0x55555555;
  75394. return x | (y << 1);
  75395. }
  75396. // find the leftmost node of a polygon ring
  75397. function getLeftmost(start) {
  75398. var p = start, leftmost = start;
  75399. do {
  75400. if (p.x < leftmost.x)
  75401. leftmost = p;
  75402. p = p.next;
  75403. } while (p !== start);
  75404. return leftmost;
  75405. }
  75406. // check if a point lies within a convex triangle
  75407. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  75408. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  75409. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  75410. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  75411. }
  75412. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  75413. function isValidDiagonal(a, b) {
  75414. return a.next.i !== b.i &&
  75415. a.prev.i !== b.i &&
  75416. !intersectsPolygon(a, b) &&
  75417. locallyInside(a, b) &&
  75418. locallyInside(b, a) &&
  75419. middleInside(a, b);
  75420. }
  75421. // signed area of a triangle
  75422. function area(p, q, r) {
  75423. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  75424. }
  75425. // check if two points are equal
  75426. function equals(p1, p2) {
  75427. return p1.x === p2.x && p1.y === p2.y;
  75428. }
  75429. // check if two segments intersect
  75430. function intersects(p1, q1, p2, q2) {
  75431. if ((equals(p1, q1) && equals(p2, q2)) ||
  75432. (equals(p1, q2) && equals(p2, q1)))
  75433. return true;
  75434. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  75435. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  75436. }
  75437. // check if a polygon diagonal intersects any polygon segments
  75438. function intersectsPolygon(a, b) {
  75439. var p = a;
  75440. do {
  75441. if (p.i !== a.i &&
  75442. p.next.i !== a.i &&
  75443. p.i !== b.i &&
  75444. p.next.i !== b.i &&
  75445. intersects(p, p.next, a, b))
  75446. return true;
  75447. p = p.next;
  75448. } while (p !== a);
  75449. return false;
  75450. }
  75451. // check if a polygon diagonal is locally inside the polygon
  75452. function locallyInside(a, b) {
  75453. return area(a.prev, a, a.next) < 0
  75454. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  75455. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  75456. }
  75457. // check if the middle point of a polygon diagonal is inside the polygon
  75458. function middleInside(a, b) {
  75459. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  75460. do {
  75461. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  75462. inside = !inside;
  75463. p = p.next;
  75464. } while (p !== a);
  75465. return inside;
  75466. }
  75467. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  75468. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  75469. function splitPolygon(a, b) {
  75470. 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;
  75471. a.next = b;
  75472. b.prev = a;
  75473. a2.next = an;
  75474. an.prev = a2;
  75475. b2.next = a2;
  75476. a2.prev = b2;
  75477. bp.next = b2;
  75478. b2.prev = bp;
  75479. return b2;
  75480. }
  75481. // create a node and optionally link it with previous one (in a circular doubly linked list)
  75482. function insertNode(i, x, y, last) {
  75483. var p = new Node(i, x, y);
  75484. if (!last) {
  75485. p.prev = p;
  75486. p.next = p;
  75487. }
  75488. else {
  75489. p.next = last.next;
  75490. p.prev = last;
  75491. last.next.prev = p;
  75492. last.next = p;
  75493. }
  75494. return p;
  75495. }
  75496. function removeNode(p) {
  75497. p.next.prev = p.prev;
  75498. p.prev.next = p.next;
  75499. if (p.prevZ)
  75500. p.prevZ.nextZ = p.nextZ;
  75501. if (p.nextZ)
  75502. p.nextZ.prevZ = p.prevZ;
  75503. }
  75504. /**
  75505. * return a percentage difference between the polygon area and its triangulation area;
  75506. * used to verify correctness of triangulation
  75507. */
  75508. function deviation(data, holeIndices, dim, triangles) {
  75509. var hasHoles = holeIndices && holeIndices.length;
  75510. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75511. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75512. if (hasHoles) {
  75513. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75514. var start = holeIndices[i] * dim;
  75515. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75516. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75517. }
  75518. }
  75519. var trianglesArea = 0;
  75520. for (i = 0; i < triangles.length; i += 3) {
  75521. var a = triangles[i] * dim;
  75522. var b = triangles[i + 1] * dim;
  75523. var c = triangles[i + 2] * dim;
  75524. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75525. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75526. }
  75527. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75528. }
  75529. Earcut.deviation = deviation;
  75530. ;
  75531. function signedArea(data, start, end, dim) {
  75532. var sum = 0;
  75533. for (var i = start, j = end - dim; i < end; i += dim) {
  75534. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75535. j = i;
  75536. }
  75537. return sum;
  75538. }
  75539. /**
  75540. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75541. */
  75542. function flatten(data) {
  75543. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75544. for (var i = 0; i < data.length; i++) {
  75545. for (var j = 0; j < data[i].length; j++) {
  75546. for (var d = 0; d < dim; d++)
  75547. result.vertices.push(data[i][j][d]);
  75548. }
  75549. if (i > 0) {
  75550. holeIndex += data[i - 1].length;
  75551. result.holes.push(holeIndex);
  75552. }
  75553. }
  75554. return result;
  75555. }
  75556. Earcut.flatten = flatten;
  75557. ;
  75558. })(Earcut || (Earcut = {}));
  75559. //# sourceMappingURL=babylon.earcut.js.map
  75560. var BABYLON;
  75561. (function (BABYLON) {
  75562. var IndexedVector2 = /** @class */ (function (_super) {
  75563. __extends(IndexedVector2, _super);
  75564. function IndexedVector2(original, index) {
  75565. var _this = _super.call(this, original.x, original.y) || this;
  75566. _this.index = index;
  75567. return _this;
  75568. }
  75569. return IndexedVector2;
  75570. }(BABYLON.Vector2));
  75571. var PolygonPoints = /** @class */ (function () {
  75572. function PolygonPoints() {
  75573. this.elements = new Array();
  75574. }
  75575. PolygonPoints.prototype.add = function (originalPoints) {
  75576. var _this = this;
  75577. var result = new Array();
  75578. originalPoints.forEach(function (point) {
  75579. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75580. var newPoint = new IndexedVector2(point, _this.elements.length);
  75581. result.push(newPoint);
  75582. _this.elements.push(newPoint);
  75583. }
  75584. });
  75585. return result;
  75586. };
  75587. PolygonPoints.prototype.computeBounds = function () {
  75588. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75589. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75590. this.elements.forEach(function (point) {
  75591. // x
  75592. if (point.x < lmin.x) {
  75593. lmin.x = point.x;
  75594. }
  75595. else if (point.x > lmax.x) {
  75596. lmax.x = point.x;
  75597. }
  75598. // y
  75599. if (point.y < lmin.y) {
  75600. lmin.y = point.y;
  75601. }
  75602. else if (point.y > lmax.y) {
  75603. lmax.y = point.y;
  75604. }
  75605. });
  75606. return {
  75607. min: lmin,
  75608. max: lmax,
  75609. width: lmax.x - lmin.x,
  75610. height: lmax.y - lmin.y
  75611. };
  75612. };
  75613. return PolygonPoints;
  75614. }());
  75615. var Polygon = /** @class */ (function () {
  75616. function Polygon() {
  75617. }
  75618. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75619. return [
  75620. new BABYLON.Vector2(xmin, ymin),
  75621. new BABYLON.Vector2(xmax, ymin),
  75622. new BABYLON.Vector2(xmax, ymax),
  75623. new BABYLON.Vector2(xmin, ymax)
  75624. ];
  75625. };
  75626. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75627. if (cx === void 0) { cx = 0; }
  75628. if (cy === void 0) { cy = 0; }
  75629. if (numberOfSides === void 0) { numberOfSides = 32; }
  75630. var result = new Array();
  75631. var angle = 0;
  75632. var increment = (Math.PI * 2) / numberOfSides;
  75633. for (var i = 0; i < numberOfSides; i++) {
  75634. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75635. angle -= increment;
  75636. }
  75637. return result;
  75638. };
  75639. Polygon.Parse = function (input) {
  75640. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75641. var i, result = [];
  75642. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75643. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75644. }
  75645. return result;
  75646. };
  75647. Polygon.StartingAt = function (x, y) {
  75648. return BABYLON.Path2.StartingAt(x, y);
  75649. };
  75650. return Polygon;
  75651. }());
  75652. BABYLON.Polygon = Polygon;
  75653. var PolygonMeshBuilder = /** @class */ (function () {
  75654. function PolygonMeshBuilder(name, contours, scene) {
  75655. this._points = new PolygonPoints();
  75656. this._outlinepoints = new PolygonPoints();
  75657. this._holes = new Array();
  75658. this._epoints = new Array();
  75659. this._eholes = new Array();
  75660. this._name = name;
  75661. this._scene = scene;
  75662. var points;
  75663. if (contours instanceof BABYLON.Path2) {
  75664. points = contours.getPoints();
  75665. }
  75666. else {
  75667. points = contours;
  75668. }
  75669. this._addToepoint(points);
  75670. this._points.add(points);
  75671. this._outlinepoints.add(points);
  75672. }
  75673. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75674. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75675. var p = points_1[_i];
  75676. this._epoints.push(p.x, p.y);
  75677. }
  75678. };
  75679. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75680. this._points.add(hole);
  75681. var holepoints = new PolygonPoints();
  75682. holepoints.add(hole);
  75683. this._holes.push(holepoints);
  75684. this._eholes.push(this._epoints.length / 2);
  75685. this._addToepoint(hole);
  75686. return this;
  75687. };
  75688. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75689. var _this = this;
  75690. if (updatable === void 0) { updatable = false; }
  75691. if (depth === void 0) { depth = 0; }
  75692. var result = new BABYLON.Mesh(this._name, this._scene);
  75693. var normals = new Array();
  75694. var positions = new Array();
  75695. var uvs = new Array();
  75696. var bounds = this._points.computeBounds();
  75697. this._points.elements.forEach(function (p) {
  75698. normals.push(0, 1.0, 0);
  75699. positions.push(p.x, 0, p.y);
  75700. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75701. });
  75702. var indices = new Array();
  75703. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75704. for (var i = 0; i < res.length; i++) {
  75705. indices.push(res[i]);
  75706. }
  75707. if (depth > 0) {
  75708. var positionscount = (positions.length / 3); //get the current pointcount
  75709. this._points.elements.forEach(function (p) {
  75710. normals.push(0, -1.0, 0);
  75711. positions.push(p.x, -depth, p.y);
  75712. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75713. });
  75714. var totalCount = indices.length;
  75715. for (var i = 0; i < totalCount; i += 3) {
  75716. var i0 = indices[i + 0];
  75717. var i1 = indices[i + 1];
  75718. var i2 = indices[i + 2];
  75719. indices.push(i2 + positionscount);
  75720. indices.push(i1 + positionscount);
  75721. indices.push(i0 + positionscount);
  75722. }
  75723. //Add the sides
  75724. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75725. this._holes.forEach(function (hole) {
  75726. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75727. });
  75728. }
  75729. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75730. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75731. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75732. result.setIndices(indices);
  75733. return result;
  75734. };
  75735. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75736. var StartIndex = positions.length / 3;
  75737. var ulength = 0;
  75738. for (var i = 0; i < points.elements.length; i++) {
  75739. var p = points.elements[i];
  75740. var p1;
  75741. if ((i + 1) > points.elements.length - 1) {
  75742. p1 = points.elements[0];
  75743. }
  75744. else {
  75745. p1 = points.elements[i + 1];
  75746. }
  75747. positions.push(p.x, 0, p.y);
  75748. positions.push(p.x, -depth, p.y);
  75749. positions.push(p1.x, 0, p1.y);
  75750. positions.push(p1.x, -depth, p1.y);
  75751. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75752. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75753. var v3 = v2.subtract(v1);
  75754. var v4 = new BABYLON.Vector3(0, 1, 0);
  75755. var vn = BABYLON.Vector3.Cross(v3, v4);
  75756. vn = vn.normalize();
  75757. uvs.push(ulength / bounds.width, 0);
  75758. uvs.push(ulength / bounds.width, 1);
  75759. ulength += v3.length();
  75760. uvs.push((ulength / bounds.width), 0);
  75761. uvs.push((ulength / bounds.width), 1);
  75762. if (!flip) {
  75763. normals.push(-vn.x, -vn.y, -vn.z);
  75764. normals.push(-vn.x, -vn.y, -vn.z);
  75765. normals.push(-vn.x, -vn.y, -vn.z);
  75766. normals.push(-vn.x, -vn.y, -vn.z);
  75767. indices.push(StartIndex);
  75768. indices.push(StartIndex + 1);
  75769. indices.push(StartIndex + 2);
  75770. indices.push(StartIndex + 1);
  75771. indices.push(StartIndex + 3);
  75772. indices.push(StartIndex + 2);
  75773. }
  75774. else {
  75775. normals.push(vn.x, vn.y, vn.z);
  75776. normals.push(vn.x, vn.y, vn.z);
  75777. normals.push(vn.x, vn.y, vn.z);
  75778. normals.push(vn.x, vn.y, vn.z);
  75779. indices.push(StartIndex);
  75780. indices.push(StartIndex + 2);
  75781. indices.push(StartIndex + 1);
  75782. indices.push(StartIndex + 1);
  75783. indices.push(StartIndex + 2);
  75784. indices.push(StartIndex + 3);
  75785. }
  75786. StartIndex += 4;
  75787. }
  75788. ;
  75789. };
  75790. return PolygonMeshBuilder;
  75791. }());
  75792. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75793. })(BABYLON || (BABYLON = {}));
  75794. //# sourceMappingURL=babylon.polygonMesh.js.map
  75795. var BABYLON;
  75796. (function (BABYLON) {
  75797. // Unique ID when we import meshes from Babylon to CSG
  75798. var currentCSGMeshId = 0;
  75799. // # class Vertex
  75800. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75801. // one to provide additional features like texture coordinates and vertex
  75802. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75803. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75804. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75805. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75806. // is not used anywhere else.
  75807. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75808. var Vertex = /** @class */ (function () {
  75809. function Vertex(pos, normal, uv) {
  75810. this.pos = pos;
  75811. this.normal = normal;
  75812. this.uv = uv;
  75813. }
  75814. Vertex.prototype.clone = function () {
  75815. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  75816. };
  75817. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  75818. // orientation of a polygon is flipped.
  75819. Vertex.prototype.flip = function () {
  75820. this.normal = this.normal.scale(-1);
  75821. };
  75822. // Create a new vertex between this vertex and `other` by linearly
  75823. // interpolating all properties using a parameter of `t`. Subclasses should
  75824. // override this to interpolate additional properties.
  75825. Vertex.prototype.interpolate = function (other, t) {
  75826. 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));
  75827. };
  75828. return Vertex;
  75829. }());
  75830. // # class Plane
  75831. // Represents a plane in 3D space.
  75832. var Plane = /** @class */ (function () {
  75833. function Plane(normal, w) {
  75834. this.normal = normal;
  75835. this.w = w;
  75836. }
  75837. Plane.FromPoints = function (a, b, c) {
  75838. var v0 = c.subtract(a);
  75839. var v1 = b.subtract(a);
  75840. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  75841. return null;
  75842. }
  75843. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  75844. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  75845. };
  75846. Plane.prototype.clone = function () {
  75847. return new Plane(this.normal.clone(), this.w);
  75848. };
  75849. Plane.prototype.flip = function () {
  75850. this.normal.scaleInPlace(-1);
  75851. this.w = -this.w;
  75852. };
  75853. // Split `polygon` by this plane if needed, then put the polygon or polygon
  75854. // fragments in the appropriate lists. Coplanar polygons go into either
  75855. // `coplanarFront` or `coplanarBack` depending on their orientation with
  75856. // respect to this plane. Polygons in front or in back of this plane go into
  75857. // either `front` or `back`.
  75858. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  75859. var COPLANAR = 0;
  75860. var FRONT = 1;
  75861. var BACK = 2;
  75862. var SPANNING = 3;
  75863. // Classify each point as well as the entire polygon into one of the above
  75864. // four classes.
  75865. var polygonType = 0;
  75866. var types = [];
  75867. var i;
  75868. var t;
  75869. for (i = 0; i < polygon.vertices.length; i++) {
  75870. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  75871. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75872. polygonType |= type;
  75873. types.push(type);
  75874. }
  75875. // Put the polygon in the correct list, splitting it when necessary.
  75876. switch (polygonType) {
  75877. case COPLANAR:
  75878. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  75879. break;
  75880. case FRONT:
  75881. front.push(polygon);
  75882. break;
  75883. case BACK:
  75884. back.push(polygon);
  75885. break;
  75886. case SPANNING:
  75887. var f = [], b = [];
  75888. for (i = 0; i < polygon.vertices.length; i++) {
  75889. var j = (i + 1) % polygon.vertices.length;
  75890. var ti = types[i], tj = types[j];
  75891. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  75892. if (ti !== BACK)
  75893. f.push(vi);
  75894. if (ti !== FRONT)
  75895. b.push(ti !== BACK ? vi.clone() : vi);
  75896. if ((ti | tj) === SPANNING) {
  75897. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  75898. var v = vi.interpolate(vj, t);
  75899. f.push(v);
  75900. b.push(v.clone());
  75901. }
  75902. }
  75903. var poly;
  75904. if (f.length >= 3) {
  75905. poly = new Polygon(f, polygon.shared);
  75906. if (poly.plane)
  75907. front.push(poly);
  75908. }
  75909. if (b.length >= 3) {
  75910. poly = new Polygon(b, polygon.shared);
  75911. if (poly.plane)
  75912. back.push(poly);
  75913. }
  75914. break;
  75915. }
  75916. };
  75917. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75918. // point is on the plane.
  75919. Plane.EPSILON = 1e-5;
  75920. return Plane;
  75921. }());
  75922. // # class Polygon
  75923. // Represents a convex polygon. The vertices used to initialize a polygon must
  75924. // be coplanar and form a convex loop.
  75925. //
  75926. // Each convex polygon has a `shared` property, which is shared between all
  75927. // polygons that are clones of each other or were split from the same polygon.
  75928. // This can be used to define per-polygon properties (such as surface color).
  75929. var Polygon = /** @class */ (function () {
  75930. function Polygon(vertices, shared) {
  75931. this.vertices = vertices;
  75932. this.shared = shared;
  75933. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75934. }
  75935. Polygon.prototype.clone = function () {
  75936. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75937. return new Polygon(vertices, this.shared);
  75938. };
  75939. Polygon.prototype.flip = function () {
  75940. this.vertices.reverse().map(function (v) { v.flip(); });
  75941. this.plane.flip();
  75942. };
  75943. return Polygon;
  75944. }());
  75945. // # class Node
  75946. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75947. // by picking a polygon to split along. That polygon (and all other coplanar
  75948. // polygons) are added directly to that node and the other polygons are added to
  75949. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75950. // no distinction between internal and leaf nodes.
  75951. var Node = /** @class */ (function () {
  75952. function Node(polygons) {
  75953. this.plane = null;
  75954. this.front = null;
  75955. this.back = null;
  75956. this.polygons = new Array();
  75957. if (polygons) {
  75958. this.build(polygons);
  75959. }
  75960. }
  75961. Node.prototype.clone = function () {
  75962. var node = new Node();
  75963. node.plane = this.plane && this.plane.clone();
  75964. node.front = this.front && this.front.clone();
  75965. node.back = this.back && this.back.clone();
  75966. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75967. return node;
  75968. };
  75969. // Convert solid space to empty space and empty space to solid space.
  75970. Node.prototype.invert = function () {
  75971. for (var i = 0; i < this.polygons.length; i++) {
  75972. this.polygons[i].flip();
  75973. }
  75974. if (this.plane) {
  75975. this.plane.flip();
  75976. }
  75977. if (this.front) {
  75978. this.front.invert();
  75979. }
  75980. if (this.back) {
  75981. this.back.invert();
  75982. }
  75983. var temp = this.front;
  75984. this.front = this.back;
  75985. this.back = temp;
  75986. };
  75987. // Recursively remove all polygons in `polygons` that are inside this BSP
  75988. // tree.
  75989. Node.prototype.clipPolygons = function (polygons) {
  75990. if (!this.plane)
  75991. return polygons.slice();
  75992. var front = new Array(), back = new Array();
  75993. for (var i = 0; i < polygons.length; i++) {
  75994. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75995. }
  75996. if (this.front) {
  75997. front = this.front.clipPolygons(front);
  75998. }
  75999. if (this.back) {
  76000. back = this.back.clipPolygons(back);
  76001. }
  76002. else {
  76003. back = [];
  76004. }
  76005. return front.concat(back);
  76006. };
  76007. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76008. // `bsp`.
  76009. Node.prototype.clipTo = function (bsp) {
  76010. this.polygons = bsp.clipPolygons(this.polygons);
  76011. if (this.front)
  76012. this.front.clipTo(bsp);
  76013. if (this.back)
  76014. this.back.clipTo(bsp);
  76015. };
  76016. // Return a list of all polygons in this BSP tree.
  76017. Node.prototype.allPolygons = function () {
  76018. var polygons = this.polygons.slice();
  76019. if (this.front)
  76020. polygons = polygons.concat(this.front.allPolygons());
  76021. if (this.back)
  76022. polygons = polygons.concat(this.back.allPolygons());
  76023. return polygons;
  76024. };
  76025. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76026. // new polygons are filtered down to the bottom of the tree and become new
  76027. // nodes there. Each set of polygons is partitioned using the first polygon
  76028. // (no heuristic is used to pick a good split).
  76029. Node.prototype.build = function (polygons) {
  76030. if (!polygons.length)
  76031. return;
  76032. if (!this.plane)
  76033. this.plane = polygons[0].plane.clone();
  76034. var front = new Array(), back = new Array();
  76035. for (var i = 0; i < polygons.length; i++) {
  76036. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76037. }
  76038. if (front.length) {
  76039. if (!this.front)
  76040. this.front = new Node();
  76041. this.front.build(front);
  76042. }
  76043. if (back.length) {
  76044. if (!this.back)
  76045. this.back = new Node();
  76046. this.back.build(back);
  76047. }
  76048. };
  76049. return Node;
  76050. }());
  76051. var CSG = /** @class */ (function () {
  76052. function CSG() {
  76053. this.polygons = new Array();
  76054. }
  76055. // Convert BABYLON.Mesh to BABYLON.CSG
  76056. CSG.FromMesh = function (mesh) {
  76057. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76058. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76059. if (mesh instanceof BABYLON.Mesh) {
  76060. mesh.computeWorldMatrix(true);
  76061. matrix = mesh.getWorldMatrix();
  76062. meshPosition = mesh.position.clone();
  76063. meshRotation = mesh.rotation.clone();
  76064. if (mesh.rotationQuaternion) {
  76065. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76066. }
  76067. meshScaling = mesh.scaling.clone();
  76068. }
  76069. else {
  76070. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76071. }
  76072. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76073. var subMeshes = mesh.subMeshes;
  76074. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76075. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76076. vertices = [];
  76077. for (var j = 0; j < 3; j++) {
  76078. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76079. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76080. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76081. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76082. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76083. vertex = new Vertex(position, normal, uv);
  76084. vertices.push(vertex);
  76085. }
  76086. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76087. // To handle the case of degenerated triangle
  76088. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76089. if (polygon.plane)
  76090. polygons.push(polygon);
  76091. }
  76092. }
  76093. var csg = CSG.FromPolygons(polygons);
  76094. csg.matrix = matrix;
  76095. csg.position = meshPosition;
  76096. csg.rotation = meshRotation;
  76097. csg.scaling = meshScaling;
  76098. csg.rotationQuaternion = meshRotationQuaternion;
  76099. currentCSGMeshId++;
  76100. return csg;
  76101. };
  76102. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76103. CSG.FromPolygons = function (polygons) {
  76104. var csg = new CSG();
  76105. csg.polygons = polygons;
  76106. return csg;
  76107. };
  76108. CSG.prototype.clone = function () {
  76109. var csg = new CSG();
  76110. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76111. csg.copyTransformAttributes(this);
  76112. return csg;
  76113. };
  76114. CSG.prototype.union = function (csg) {
  76115. var a = new Node(this.clone().polygons);
  76116. var b = new Node(csg.clone().polygons);
  76117. a.clipTo(b);
  76118. b.clipTo(a);
  76119. b.invert();
  76120. b.clipTo(a);
  76121. b.invert();
  76122. a.build(b.allPolygons());
  76123. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76124. };
  76125. CSG.prototype.unionInPlace = function (csg) {
  76126. var a = new Node(this.polygons);
  76127. var b = new Node(csg.polygons);
  76128. a.clipTo(b);
  76129. b.clipTo(a);
  76130. b.invert();
  76131. b.clipTo(a);
  76132. b.invert();
  76133. a.build(b.allPolygons());
  76134. this.polygons = a.allPolygons();
  76135. };
  76136. CSG.prototype.subtract = function (csg) {
  76137. var a = new Node(this.clone().polygons);
  76138. var b = new Node(csg.clone().polygons);
  76139. a.invert();
  76140. a.clipTo(b);
  76141. b.clipTo(a);
  76142. b.invert();
  76143. b.clipTo(a);
  76144. b.invert();
  76145. a.build(b.allPolygons());
  76146. a.invert();
  76147. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76148. };
  76149. CSG.prototype.subtractInPlace = function (csg) {
  76150. var a = new Node(this.polygons);
  76151. var b = new Node(csg.polygons);
  76152. a.invert();
  76153. a.clipTo(b);
  76154. b.clipTo(a);
  76155. b.invert();
  76156. b.clipTo(a);
  76157. b.invert();
  76158. a.build(b.allPolygons());
  76159. a.invert();
  76160. this.polygons = a.allPolygons();
  76161. };
  76162. CSG.prototype.intersect = function (csg) {
  76163. var a = new Node(this.clone().polygons);
  76164. var b = new Node(csg.clone().polygons);
  76165. a.invert();
  76166. b.clipTo(a);
  76167. b.invert();
  76168. a.clipTo(b);
  76169. b.clipTo(a);
  76170. a.build(b.allPolygons());
  76171. a.invert();
  76172. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76173. };
  76174. CSG.prototype.intersectInPlace = function (csg) {
  76175. var a = new Node(this.polygons);
  76176. var b = new Node(csg.polygons);
  76177. a.invert();
  76178. b.clipTo(a);
  76179. b.invert();
  76180. a.clipTo(b);
  76181. b.clipTo(a);
  76182. a.build(b.allPolygons());
  76183. a.invert();
  76184. this.polygons = a.allPolygons();
  76185. };
  76186. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76187. // not modified.
  76188. CSG.prototype.inverse = function () {
  76189. var csg = this.clone();
  76190. csg.inverseInPlace();
  76191. return csg;
  76192. };
  76193. CSG.prototype.inverseInPlace = function () {
  76194. this.polygons.map(function (p) { p.flip(); });
  76195. };
  76196. // This is used to keep meshes transformations so they can be restored
  76197. // when we build back a Babylon Mesh
  76198. // NB : All CSG operations are performed in world coordinates
  76199. CSG.prototype.copyTransformAttributes = function (csg) {
  76200. this.matrix = csg.matrix;
  76201. this.position = csg.position;
  76202. this.rotation = csg.rotation;
  76203. this.scaling = csg.scaling;
  76204. this.rotationQuaternion = csg.rotationQuaternion;
  76205. return this;
  76206. };
  76207. // Build Raw mesh from CSG
  76208. // Coordinates here are in world space
  76209. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76210. var matrix = this.matrix.clone();
  76211. matrix.invert();
  76212. 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;
  76213. if (keepSubMeshes) {
  76214. // Sort Polygons, since subMeshes are indices range
  76215. polygons.sort(function (a, b) {
  76216. if (a.shared.meshId === b.shared.meshId) {
  76217. return a.shared.subMeshId - b.shared.subMeshId;
  76218. }
  76219. else {
  76220. return a.shared.meshId - b.shared.meshId;
  76221. }
  76222. });
  76223. }
  76224. for (var i = 0, il = polygons.length; i < il; i++) {
  76225. polygon = polygons[i];
  76226. // Building SubMeshes
  76227. if (!subMesh_dict[polygon.shared.meshId]) {
  76228. subMesh_dict[polygon.shared.meshId] = {};
  76229. }
  76230. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76231. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76232. indexStart: +Infinity,
  76233. indexEnd: -Infinity,
  76234. materialIndex: polygon.shared.materialIndex
  76235. };
  76236. }
  76237. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76238. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76239. polygonIndices[0] = 0;
  76240. polygonIndices[1] = j - 1;
  76241. polygonIndices[2] = j;
  76242. for (var k = 0; k < 3; k++) {
  76243. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76244. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76245. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76246. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76247. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76248. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76249. // Check if 2 points can be merged
  76250. if (!(typeof vertex_idx !== 'undefined' &&
  76251. normals[vertex_idx * 3] === localNormal.x &&
  76252. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76253. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76254. uvs[vertex_idx * 2] === uv.x &&
  76255. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76256. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76257. uvs.push(uv.x, uv.y);
  76258. normals.push(normal.x, normal.y, normal.z);
  76259. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76260. }
  76261. indices.push(vertex_idx);
  76262. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76263. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76264. currentIndex++;
  76265. }
  76266. }
  76267. }
  76268. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76269. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76270. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76271. mesh.setIndices(indices, null);
  76272. if (keepSubMeshes) {
  76273. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76274. var materialIndexOffset = 0, materialMaxIndex;
  76275. mesh.subMeshes = new Array();
  76276. for (var m in subMesh_dict) {
  76277. materialMaxIndex = -1;
  76278. for (var sm in subMesh_dict[m]) {
  76279. subMesh_obj = subMesh_dict[m][sm];
  76280. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76281. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76282. }
  76283. materialIndexOffset += ++materialMaxIndex;
  76284. }
  76285. }
  76286. return mesh;
  76287. };
  76288. // Build Mesh from CSG taking material and transforms into account
  76289. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76290. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76291. mesh.material = material;
  76292. mesh.position.copyFrom(this.position);
  76293. mesh.rotation.copyFrom(this.rotation);
  76294. if (this.rotationQuaternion) {
  76295. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76296. }
  76297. mesh.scaling.copyFrom(this.scaling);
  76298. mesh.computeWorldMatrix(true);
  76299. return mesh;
  76300. };
  76301. return CSG;
  76302. }());
  76303. BABYLON.CSG = CSG;
  76304. })(BABYLON || (BABYLON = {}));
  76305. //# sourceMappingURL=babylon.csg.js.map
  76306. var BABYLON;
  76307. (function (BABYLON) {
  76308. var LensFlare = /** @class */ (function () {
  76309. function LensFlare(size, position, color, imgUrl, system) {
  76310. this.size = size;
  76311. this.position = position;
  76312. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76313. this.color = color || new BABYLON.Color3(1, 1, 1);
  76314. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76315. this._system = system;
  76316. system.lensFlares.push(this);
  76317. }
  76318. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76319. return new LensFlare(size, position, color, imgUrl, system);
  76320. };
  76321. LensFlare.prototype.dispose = function () {
  76322. if (this.texture) {
  76323. this.texture.dispose();
  76324. }
  76325. // Remove from scene
  76326. var index = this._system.lensFlares.indexOf(this);
  76327. this._system.lensFlares.splice(index, 1);
  76328. };
  76329. ;
  76330. return LensFlare;
  76331. }());
  76332. BABYLON.LensFlare = LensFlare;
  76333. })(BABYLON || (BABYLON = {}));
  76334. //# sourceMappingURL=babylon.lensFlare.js.map
  76335. var BABYLON;
  76336. (function (BABYLON) {
  76337. var LensFlareSystem = /** @class */ (function () {
  76338. function LensFlareSystem(name, emitter, scene) {
  76339. this.name = name;
  76340. this.lensFlares = new Array();
  76341. this.borderLimit = 300;
  76342. this.viewportBorder = 0;
  76343. this.layerMask = 0x0FFFFFFF;
  76344. this._vertexBuffers = {};
  76345. this._isEnabled = true;
  76346. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76347. this._emitter = emitter;
  76348. this.id = name;
  76349. scene.lensFlareSystems.push(this);
  76350. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76351. var engine = scene.getEngine();
  76352. // VBO
  76353. var vertices = [];
  76354. vertices.push(1, 1);
  76355. vertices.push(-1, 1);
  76356. vertices.push(-1, -1);
  76357. vertices.push(1, -1);
  76358. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76359. // Indices
  76360. var indices = [];
  76361. indices.push(0);
  76362. indices.push(1);
  76363. indices.push(2);
  76364. indices.push(0);
  76365. indices.push(2);
  76366. indices.push(3);
  76367. this._indexBuffer = engine.createIndexBuffer(indices);
  76368. // Effects
  76369. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76370. }
  76371. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76372. get: function () {
  76373. return this._isEnabled;
  76374. },
  76375. set: function (value) {
  76376. this._isEnabled = value;
  76377. },
  76378. enumerable: true,
  76379. configurable: true
  76380. });
  76381. LensFlareSystem.prototype.getScene = function () {
  76382. return this._scene;
  76383. };
  76384. LensFlareSystem.prototype.getEmitter = function () {
  76385. return this._emitter;
  76386. };
  76387. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76388. this._emitter = newEmitter;
  76389. };
  76390. LensFlareSystem.prototype.getEmitterPosition = function () {
  76391. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76392. };
  76393. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76394. var position = this.getEmitterPosition();
  76395. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76396. this._positionX = position.x;
  76397. this._positionY = position.y;
  76398. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76399. if (this.viewportBorder > 0) {
  76400. globalViewport.x -= this.viewportBorder;
  76401. globalViewport.y -= this.viewportBorder;
  76402. globalViewport.width += this.viewportBorder * 2;
  76403. globalViewport.height += this.viewportBorder * 2;
  76404. position.x += this.viewportBorder;
  76405. position.y += this.viewportBorder;
  76406. this._positionX += this.viewportBorder;
  76407. this._positionY += this.viewportBorder;
  76408. }
  76409. if (position.z > 0) {
  76410. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76411. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76412. return true;
  76413. }
  76414. return true;
  76415. }
  76416. return false;
  76417. };
  76418. LensFlareSystem.prototype._isVisible = function () {
  76419. if (!this._isEnabled || !this._scene.activeCamera) {
  76420. return false;
  76421. }
  76422. var emitterPosition = this.getEmitterPosition();
  76423. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76424. var distance = direction.length();
  76425. direction.normalize();
  76426. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76427. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76428. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76429. };
  76430. LensFlareSystem.prototype.render = function () {
  76431. if (!this._effect.isReady() || !this._scene.activeCamera)
  76432. return false;
  76433. var engine = this._scene.getEngine();
  76434. var viewport = this._scene.activeCamera.viewport;
  76435. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76436. // Position
  76437. if (!this.computeEffectivePosition(globalViewport)) {
  76438. return false;
  76439. }
  76440. // Visibility
  76441. if (!this._isVisible()) {
  76442. return false;
  76443. }
  76444. // Intensity
  76445. var awayX;
  76446. var awayY;
  76447. if (this._positionX < this.borderLimit + globalViewport.x) {
  76448. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76449. }
  76450. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76451. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76452. }
  76453. else {
  76454. awayX = 0;
  76455. }
  76456. if (this._positionY < this.borderLimit + globalViewport.y) {
  76457. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76458. }
  76459. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76460. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76461. }
  76462. else {
  76463. awayY = 0;
  76464. }
  76465. var away = (awayX > awayY) ? awayX : awayY;
  76466. away -= this.viewportBorder;
  76467. if (away > this.borderLimit) {
  76468. away = this.borderLimit;
  76469. }
  76470. var intensity = 1.0 - (away / this.borderLimit);
  76471. if (intensity < 0) {
  76472. return false;
  76473. }
  76474. if (intensity > 1.0) {
  76475. intensity = 1.0;
  76476. }
  76477. if (this.viewportBorder > 0) {
  76478. globalViewport.x += this.viewportBorder;
  76479. globalViewport.y += this.viewportBorder;
  76480. globalViewport.width -= this.viewportBorder * 2;
  76481. globalViewport.height -= this.viewportBorder * 2;
  76482. this._positionX -= this.viewportBorder;
  76483. this._positionY -= this.viewportBorder;
  76484. }
  76485. // Position
  76486. var centerX = globalViewport.x + globalViewport.width / 2;
  76487. var centerY = globalViewport.y + globalViewport.height / 2;
  76488. var distX = centerX - this._positionX;
  76489. var distY = centerY - this._positionY;
  76490. // Effects
  76491. engine.enableEffect(this._effect);
  76492. engine.setState(false);
  76493. engine.setDepthBuffer(false);
  76494. // VBOs
  76495. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76496. // Flares
  76497. for (var index = 0; index < this.lensFlares.length; index++) {
  76498. var flare = this.lensFlares[index];
  76499. engine.setAlphaMode(flare.alphaMode);
  76500. var x = centerX - (distX * flare.position);
  76501. var y = centerY - (distY * flare.position);
  76502. var cw = flare.size;
  76503. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76504. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76505. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76506. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76507. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76508. // Texture
  76509. this._effect.setTexture("textureSampler", flare.texture);
  76510. // Color
  76511. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76512. // Draw order
  76513. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76514. }
  76515. engine.setDepthBuffer(true);
  76516. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76517. return true;
  76518. };
  76519. LensFlareSystem.prototype.dispose = function () {
  76520. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76521. if (vertexBuffer) {
  76522. vertexBuffer.dispose();
  76523. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76524. }
  76525. if (this._indexBuffer) {
  76526. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76527. this._indexBuffer = null;
  76528. }
  76529. while (this.lensFlares.length) {
  76530. this.lensFlares[0].dispose();
  76531. }
  76532. // Remove from scene
  76533. var index = this._scene.lensFlareSystems.indexOf(this);
  76534. this._scene.lensFlareSystems.splice(index, 1);
  76535. };
  76536. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76537. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76538. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76539. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76540. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76541. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76542. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76543. var parsedFlare = parsedLensFlareSystem.flares[index];
  76544. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76545. }
  76546. return lensFlareSystem;
  76547. };
  76548. LensFlareSystem.prototype.serialize = function () {
  76549. var serializationObject = {};
  76550. serializationObject.id = this.id;
  76551. serializationObject.name = this.name;
  76552. serializationObject.emitterId = this.getEmitter().id;
  76553. serializationObject.borderLimit = this.borderLimit;
  76554. serializationObject.flares = [];
  76555. for (var index = 0; index < this.lensFlares.length; index++) {
  76556. var flare = this.lensFlares[index];
  76557. serializationObject.flares.push({
  76558. size: flare.size,
  76559. position: flare.position,
  76560. color: flare.color.asArray(),
  76561. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76562. });
  76563. }
  76564. return serializationObject;
  76565. };
  76566. return LensFlareSystem;
  76567. }());
  76568. BABYLON.LensFlareSystem = LensFlareSystem;
  76569. })(BABYLON || (BABYLON = {}));
  76570. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76571. var BABYLON;
  76572. (function (BABYLON) {
  76573. /**
  76574. * This is a holder class for the physics joint created by the physics plugin.
  76575. * It holds a set of functions to control the underlying joint.
  76576. */
  76577. var PhysicsJoint = /** @class */ (function () {
  76578. function PhysicsJoint(type, jointData) {
  76579. this.type = type;
  76580. this.jointData = jointData;
  76581. jointData.nativeParams = jointData.nativeParams || {};
  76582. }
  76583. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76584. get: function () {
  76585. return this._physicsJoint;
  76586. },
  76587. set: function (newJoint) {
  76588. if (this._physicsJoint) {
  76589. //remove from the wolrd
  76590. }
  76591. this._physicsJoint = newJoint;
  76592. },
  76593. enumerable: true,
  76594. configurable: true
  76595. });
  76596. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76597. set: function (physicsPlugin) {
  76598. this._physicsPlugin = physicsPlugin;
  76599. },
  76600. enumerable: true,
  76601. configurable: true
  76602. });
  76603. /**
  76604. * Execute a function that is physics-plugin specific.
  76605. * @param {Function} func the function that will be executed.
  76606. * It accepts two parameters: the physics world and the physics joint.
  76607. */
  76608. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76609. func(this._physicsPlugin.world, this._physicsJoint);
  76610. };
  76611. //TODO check if the native joints are the same
  76612. //Joint Types
  76613. PhysicsJoint.DistanceJoint = 0;
  76614. PhysicsJoint.HingeJoint = 1;
  76615. PhysicsJoint.BallAndSocketJoint = 2;
  76616. PhysicsJoint.WheelJoint = 3;
  76617. PhysicsJoint.SliderJoint = 4;
  76618. //OIMO
  76619. PhysicsJoint.PrismaticJoint = 5;
  76620. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76621. PhysicsJoint.UniversalJoint = 6;
  76622. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76623. //Cannon
  76624. //Similar to a Ball-Joint. Different in params
  76625. PhysicsJoint.PointToPointJoint = 8;
  76626. //Cannon only at the moment
  76627. PhysicsJoint.SpringJoint = 9;
  76628. PhysicsJoint.LockJoint = 10;
  76629. return PhysicsJoint;
  76630. }());
  76631. BABYLON.PhysicsJoint = PhysicsJoint;
  76632. /**
  76633. * A class representing a physics distance joint.
  76634. */
  76635. var DistanceJoint = /** @class */ (function (_super) {
  76636. __extends(DistanceJoint, _super);
  76637. function DistanceJoint(jointData) {
  76638. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76639. }
  76640. /**
  76641. * Update the predefined distance.
  76642. */
  76643. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76644. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76645. };
  76646. return DistanceJoint;
  76647. }(PhysicsJoint));
  76648. BABYLON.DistanceJoint = DistanceJoint;
  76649. var MotorEnabledJoint = /** @class */ (function (_super) {
  76650. __extends(MotorEnabledJoint, _super);
  76651. function MotorEnabledJoint(type, jointData) {
  76652. return _super.call(this, type, jointData) || this;
  76653. }
  76654. /**
  76655. * Set the motor values.
  76656. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76657. * @param {number} force the force to apply
  76658. * @param {number} maxForce max force for this motor.
  76659. */
  76660. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76661. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76662. };
  76663. /**
  76664. * Set the motor's limits.
  76665. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76666. */
  76667. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76668. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76669. };
  76670. return MotorEnabledJoint;
  76671. }(PhysicsJoint));
  76672. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76673. /**
  76674. * This class represents a single hinge physics joint
  76675. */
  76676. var HingeJoint = /** @class */ (function (_super) {
  76677. __extends(HingeJoint, _super);
  76678. function HingeJoint(jointData) {
  76679. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76680. }
  76681. /**
  76682. * Set the motor values.
  76683. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76684. * @param {number} force the force to apply
  76685. * @param {number} maxForce max force for this motor.
  76686. */
  76687. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76688. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76689. };
  76690. /**
  76691. * Set the motor's limits.
  76692. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76693. */
  76694. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76695. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76696. };
  76697. return HingeJoint;
  76698. }(MotorEnabledJoint));
  76699. BABYLON.HingeJoint = HingeJoint;
  76700. /**
  76701. * This class represents a dual hinge physics joint (same as wheel joint)
  76702. */
  76703. var Hinge2Joint = /** @class */ (function (_super) {
  76704. __extends(Hinge2Joint, _super);
  76705. function Hinge2Joint(jointData) {
  76706. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76707. }
  76708. /**
  76709. * Set the motor values.
  76710. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76711. * @param {number} force the force to apply
  76712. * @param {number} maxForce max force for this motor.
  76713. * @param {motorIndex} the motor's index, 0 or 1.
  76714. */
  76715. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76716. if (motorIndex === void 0) { motorIndex = 0; }
  76717. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76718. };
  76719. /**
  76720. * Set the motor limits.
  76721. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76722. * @param {number} upperLimit the upper limit
  76723. * @param {number} lowerLimit lower limit
  76724. * @param {motorIndex} the motor's index, 0 or 1.
  76725. */
  76726. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76727. if (motorIndex === void 0) { motorIndex = 0; }
  76728. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76729. };
  76730. return Hinge2Joint;
  76731. }(MotorEnabledJoint));
  76732. BABYLON.Hinge2Joint = Hinge2Joint;
  76733. })(BABYLON || (BABYLON = {}));
  76734. //# sourceMappingURL=babylon.physicsJoint.js.map
  76735. var BABYLON;
  76736. (function (BABYLON) {
  76737. var PhysicsImpostor = /** @class */ (function () {
  76738. function PhysicsImpostor(object, type, _options, _scene) {
  76739. if (_options === void 0) { _options = { mass: 0 }; }
  76740. var _this = this;
  76741. this.object = object;
  76742. this.type = type;
  76743. this._options = _options;
  76744. this._scene = _scene;
  76745. this._bodyUpdateRequired = false;
  76746. this._onBeforePhysicsStepCallbacks = new Array();
  76747. this._onAfterPhysicsStepCallbacks = new Array();
  76748. this._onPhysicsCollideCallbacks = [];
  76749. this._deltaPosition = BABYLON.Vector3.Zero();
  76750. this._isDisposed = false;
  76751. //temp variables for parent rotation calculations
  76752. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  76753. this._tmpQuat = new BABYLON.Quaternion();
  76754. this._tmpQuat2 = new BABYLON.Quaternion();
  76755. /**
  76756. * this function is executed by the physics engine.
  76757. */
  76758. this.beforeStep = function () {
  76759. if (!_this._physicsEngine) {
  76760. return;
  76761. }
  76762. _this.object.translate(_this._deltaPosition, -1);
  76763. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76764. _this.object.computeWorldMatrix(false);
  76765. if (_this.object.parent && _this.object.rotationQuaternion) {
  76766. _this.getParentsRotation();
  76767. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76768. }
  76769. else {
  76770. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76771. }
  76772. if (!_this._options.disableBidirectionalTransformation) {
  76773. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76774. }
  76775. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76776. func(_this);
  76777. });
  76778. };
  76779. /**
  76780. * this function is executed by the physics engine.
  76781. */
  76782. this.afterStep = function () {
  76783. if (!_this._physicsEngine) {
  76784. return;
  76785. }
  76786. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76787. func(_this);
  76788. });
  76789. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76790. // object has now its world rotation. needs to be converted to local.
  76791. if (_this.object.parent && _this.object.rotationQuaternion) {
  76792. _this.getParentsRotation();
  76793. _this._tmpQuat.conjugateInPlace();
  76794. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76795. }
  76796. // take the position set and make it the absolute position of this object.
  76797. _this.object.setAbsolutePosition(_this.object.position);
  76798. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76799. _this.object.translate(_this._deltaPosition, 1);
  76800. };
  76801. /**
  76802. * Legacy collision detection event support
  76803. */
  76804. this.onCollideEvent = null;
  76805. //event and body object due to cannon's event-based architecture.
  76806. this.onCollide = function (e) {
  76807. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76808. return;
  76809. }
  76810. if (!_this._physicsEngine) {
  76811. return;
  76812. }
  76813. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  76814. if (otherImpostor) {
  76815. // Legacy collision detection event support
  76816. if (_this.onCollideEvent) {
  76817. _this.onCollideEvent(_this, otherImpostor);
  76818. }
  76819. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  76820. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  76821. }).forEach(function (obj) {
  76822. obj.callback(_this, otherImpostor);
  76823. });
  76824. }
  76825. };
  76826. //sanity check!
  76827. if (!this.object) {
  76828. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  76829. return;
  76830. }
  76831. //legacy support for old syntax.
  76832. if (!this._scene && object.getScene) {
  76833. this._scene = object.getScene();
  76834. }
  76835. if (!this._scene) {
  76836. return;
  76837. }
  76838. this._physicsEngine = this._scene.getPhysicsEngine();
  76839. if (!this._physicsEngine) {
  76840. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  76841. }
  76842. else {
  76843. //set the object's quaternion, if not set
  76844. if (!this.object.rotationQuaternion) {
  76845. if (this.object.rotation) {
  76846. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  76847. }
  76848. else {
  76849. this.object.rotationQuaternion = new BABYLON.Quaternion();
  76850. }
  76851. }
  76852. //default options params
  76853. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  76854. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  76855. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  76856. this._joints = [];
  76857. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  76858. if (!this.object.parent || this._options.ignoreParent) {
  76859. this._init();
  76860. }
  76861. else if (this.object.parent.physicsImpostor) {
  76862. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  76863. }
  76864. }
  76865. }
  76866. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  76867. get: function () {
  76868. return this._isDisposed;
  76869. },
  76870. enumerable: true,
  76871. configurable: true
  76872. });
  76873. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  76874. get: function () {
  76875. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  76876. },
  76877. set: function (value) {
  76878. this.setMass(value);
  76879. },
  76880. enumerable: true,
  76881. configurable: true
  76882. });
  76883. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  76884. get: function () {
  76885. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  76886. },
  76887. set: function (value) {
  76888. if (!this._physicsEngine) {
  76889. return;
  76890. }
  76891. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  76892. },
  76893. enumerable: true,
  76894. configurable: true
  76895. });
  76896. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  76897. get: function () {
  76898. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  76899. },
  76900. set: function (value) {
  76901. if (!this._physicsEngine) {
  76902. return;
  76903. }
  76904. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76905. },
  76906. enumerable: true,
  76907. configurable: true
  76908. });
  76909. /**
  76910. * This function will completly initialize this impostor.
  76911. * It will create a new body - but only if this mesh has no parent.
  76912. * If it has, this impostor will not be used other than to define the impostor
  76913. * of the child mesh.
  76914. */
  76915. PhysicsImpostor.prototype._init = function () {
  76916. if (!this._physicsEngine) {
  76917. return;
  76918. }
  76919. this._physicsEngine.removeImpostor(this);
  76920. this.physicsBody = null;
  76921. this._parent = this._parent || this._getPhysicsParent();
  76922. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76923. this._physicsEngine.addImpostor(this);
  76924. }
  76925. };
  76926. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76927. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76928. var parentMesh = this.object.parent;
  76929. return parentMesh.physicsImpostor;
  76930. }
  76931. return null;
  76932. };
  76933. /**
  76934. * Should a new body be generated.
  76935. */
  76936. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76937. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76938. };
  76939. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76940. this.forceUpdate();
  76941. };
  76942. /**
  76943. * Force a regeneration of this or the parent's impostor's body.
  76944. * Use under cautious - This will remove all joints already implemented.
  76945. */
  76946. PhysicsImpostor.prototype.forceUpdate = function () {
  76947. this._init();
  76948. if (this.parent && !this._options.ignoreParent) {
  76949. this.parent.forceUpdate();
  76950. }
  76951. };
  76952. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76953. /*public get mesh(): AbstractMesh {
  76954. return this._mesh;
  76955. }*/
  76956. /**
  76957. * Gets the body that holds this impostor. Either its own, or its parent.
  76958. */
  76959. get: function () {
  76960. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76961. },
  76962. /**
  76963. * Set the physics body. Used mainly by the physics engine/plugin
  76964. */
  76965. set: function (physicsBody) {
  76966. if (this._physicsBody && this._physicsEngine) {
  76967. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76968. }
  76969. this._physicsBody = physicsBody;
  76970. this.resetUpdateFlags();
  76971. },
  76972. enumerable: true,
  76973. configurable: true
  76974. });
  76975. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76976. get: function () {
  76977. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76978. },
  76979. set: function (value) {
  76980. this._parent = value;
  76981. },
  76982. enumerable: true,
  76983. configurable: true
  76984. });
  76985. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76986. this._bodyUpdateRequired = false;
  76987. };
  76988. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76989. if (this.object.getBoundingInfo) {
  76990. var q = this.object.rotationQuaternion;
  76991. //reset rotation
  76992. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76993. //calculate the world matrix with no rotation
  76994. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76995. var boundingInfo = this.object.getBoundingInfo();
  76996. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76997. //bring back the rotation
  76998. this.object.rotationQuaternion = q;
  76999. //calculate the world matrix with the new rotation
  77000. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77001. return size;
  77002. }
  77003. else {
  77004. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77005. }
  77006. };
  77007. PhysicsImpostor.prototype.getObjectCenter = function () {
  77008. if (this.object.getBoundingInfo) {
  77009. var boundingInfo = this.object.getBoundingInfo();
  77010. return boundingInfo.boundingBox.centerWorld;
  77011. }
  77012. else {
  77013. return this.object.position;
  77014. }
  77015. };
  77016. /**
  77017. * Get a specific parametes from the options parameter.
  77018. */
  77019. PhysicsImpostor.prototype.getParam = function (paramName) {
  77020. return this._options[paramName];
  77021. };
  77022. /**
  77023. * Sets a specific parameter in the options given to the physics plugin
  77024. */
  77025. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77026. this._options[paramName] = value;
  77027. this._bodyUpdateRequired = true;
  77028. };
  77029. /**
  77030. * Specifically change the body's mass option. Won't recreate the physics body object
  77031. */
  77032. PhysicsImpostor.prototype.setMass = function (mass) {
  77033. if (this.getParam("mass") !== mass) {
  77034. this.setParam("mass", mass);
  77035. }
  77036. if (this._physicsEngine) {
  77037. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77038. }
  77039. };
  77040. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77041. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77042. };
  77043. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77044. if (this._physicsEngine) {
  77045. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77046. }
  77047. };
  77048. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77049. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77050. };
  77051. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77052. if (this._physicsEngine) {
  77053. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77054. }
  77055. };
  77056. /**
  77057. * Execute a function with the physics plugin native code.
  77058. * Provide a function the will have two variables - the world object and the physics body object.
  77059. */
  77060. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77061. if (this._physicsEngine) {
  77062. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77063. }
  77064. };
  77065. /**
  77066. * Register a function that will be executed before the physics world is stepping forward.
  77067. */
  77068. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77069. this._onBeforePhysicsStepCallbacks.push(func);
  77070. };
  77071. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77072. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77073. if (index > -1) {
  77074. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77075. }
  77076. else {
  77077. BABYLON.Tools.Warn("Function to remove was not found");
  77078. }
  77079. };
  77080. /**
  77081. * Register a function that will be executed after the physics step
  77082. */
  77083. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77084. this._onAfterPhysicsStepCallbacks.push(func);
  77085. };
  77086. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77087. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77088. if (index > -1) {
  77089. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77090. }
  77091. else {
  77092. BABYLON.Tools.Warn("Function to remove was not found");
  77093. }
  77094. };
  77095. /**
  77096. * register a function that will be executed when this impostor collides against a different body.
  77097. */
  77098. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77099. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77100. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77101. };
  77102. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77103. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77104. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77105. if (index > -1) {
  77106. this._onPhysicsCollideCallbacks.splice(index, 1);
  77107. }
  77108. else {
  77109. BABYLON.Tools.Warn("Function to remove was not found");
  77110. }
  77111. };
  77112. PhysicsImpostor.prototype.getParentsRotation = function () {
  77113. var parent = this.object.parent;
  77114. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77115. while (parent) {
  77116. if (parent.rotationQuaternion) {
  77117. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77118. }
  77119. else {
  77120. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77121. }
  77122. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77123. parent = parent.parent;
  77124. }
  77125. return this._tmpQuat;
  77126. };
  77127. /**
  77128. * Apply a force
  77129. */
  77130. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77131. if (this._physicsEngine) {
  77132. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77133. }
  77134. return this;
  77135. };
  77136. /**
  77137. * Apply an impulse
  77138. */
  77139. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77140. if (this._physicsEngine) {
  77141. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77142. }
  77143. return this;
  77144. };
  77145. /**
  77146. * A help function to create a joint.
  77147. */
  77148. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77149. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77150. this.addJoint(otherImpostor, joint);
  77151. return this;
  77152. };
  77153. /**
  77154. * Add a joint to this impostor with a different impostor.
  77155. */
  77156. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77157. this._joints.push({
  77158. otherImpostor: otherImpostor,
  77159. joint: joint
  77160. });
  77161. if (this._physicsEngine) {
  77162. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77163. }
  77164. return this;
  77165. };
  77166. /**
  77167. * Will keep this body still, in a sleep mode.
  77168. */
  77169. PhysicsImpostor.prototype.sleep = function () {
  77170. if (this._physicsEngine) {
  77171. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77172. }
  77173. return this;
  77174. };
  77175. /**
  77176. * Wake the body up.
  77177. */
  77178. PhysicsImpostor.prototype.wakeUp = function () {
  77179. if (this._physicsEngine) {
  77180. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77181. }
  77182. return this;
  77183. };
  77184. PhysicsImpostor.prototype.clone = function (newObject) {
  77185. if (!newObject)
  77186. return null;
  77187. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77188. };
  77189. PhysicsImpostor.prototype.dispose = function () {
  77190. var _this = this;
  77191. //no dispose if no physics engine is available.
  77192. if (!this._physicsEngine) {
  77193. return;
  77194. }
  77195. this._joints.forEach(function (j) {
  77196. if (_this._physicsEngine) {
  77197. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77198. }
  77199. });
  77200. //dispose the physics body
  77201. this._physicsEngine.removeImpostor(this);
  77202. if (this.parent) {
  77203. this.parent.forceUpdate();
  77204. }
  77205. else {
  77206. /*this._object.getChildMeshes().forEach(function(mesh) {
  77207. if (mesh.physicsImpostor) {
  77208. if (disposeChildren) {
  77209. mesh.physicsImpostor.dispose();
  77210. mesh.physicsImpostor = null;
  77211. }
  77212. }
  77213. })*/
  77214. }
  77215. this._isDisposed = true;
  77216. };
  77217. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77218. this._deltaPosition.copyFrom(position);
  77219. };
  77220. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77221. if (!this._deltaRotation) {
  77222. this._deltaRotation = new BABYLON.Quaternion();
  77223. }
  77224. this._deltaRotation.copyFrom(rotation);
  77225. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77226. };
  77227. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77228. if (this._physicsEngine) {
  77229. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77230. }
  77231. return this;
  77232. };
  77233. PhysicsImpostor.prototype.getRadius = function () {
  77234. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77235. };
  77236. /**
  77237. * Sync a bone with this impostor
  77238. * @param bone The bone to sync to the impostor.
  77239. * @param boneMesh The mesh that the bone is influencing.
  77240. * @param jointPivot The pivot of the joint / bone in local space.
  77241. * @param distToJoint Optional distance from the impostor to the joint.
  77242. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77243. */
  77244. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77245. var tempVec = PhysicsImpostor._tmpVecs[0];
  77246. var mesh = this.object;
  77247. if (mesh.rotationQuaternion) {
  77248. if (adjustRotation) {
  77249. var tempQuat = PhysicsImpostor._tmpQuat;
  77250. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77251. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77252. }
  77253. else {
  77254. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77255. }
  77256. }
  77257. tempVec.x = 0;
  77258. tempVec.y = 0;
  77259. tempVec.z = 0;
  77260. if (jointPivot) {
  77261. tempVec.x = jointPivot.x;
  77262. tempVec.y = jointPivot.y;
  77263. tempVec.z = jointPivot.z;
  77264. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77265. if (distToJoint === undefined || distToJoint === null) {
  77266. distToJoint = jointPivot.length();
  77267. }
  77268. tempVec.x *= distToJoint;
  77269. tempVec.y *= distToJoint;
  77270. tempVec.z *= distToJoint;
  77271. }
  77272. if (bone.getParent()) {
  77273. tempVec.addInPlace(mesh.getAbsolutePosition());
  77274. bone.setAbsolutePosition(tempVec, boneMesh);
  77275. }
  77276. else {
  77277. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77278. boneMesh.position.x -= tempVec.x;
  77279. boneMesh.position.y -= tempVec.y;
  77280. boneMesh.position.z -= tempVec.z;
  77281. }
  77282. };
  77283. /**
  77284. * Sync impostor to a bone
  77285. * @param bone The bone that the impostor will be synced to.
  77286. * @param boneMesh The mesh that the bone is influencing.
  77287. * @param jointPivot The pivot of the joint / bone in local space.
  77288. * @param distToJoint Optional distance from the impostor to the joint.
  77289. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77290. * @param boneAxis Optional vector3 axis the bone is aligned with
  77291. */
  77292. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77293. var mesh = this.object;
  77294. if (mesh.rotationQuaternion) {
  77295. if (adjustRotation) {
  77296. var tempQuat = PhysicsImpostor._tmpQuat;
  77297. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77298. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77299. }
  77300. else {
  77301. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77302. }
  77303. }
  77304. var pos = PhysicsImpostor._tmpVecs[0];
  77305. var boneDir = PhysicsImpostor._tmpVecs[1];
  77306. if (!boneAxis) {
  77307. boneAxis = PhysicsImpostor._tmpVecs[2];
  77308. boneAxis.x = 0;
  77309. boneAxis.y = 1;
  77310. boneAxis.z = 0;
  77311. }
  77312. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77313. bone.getAbsolutePositionToRef(boneMesh, pos);
  77314. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77315. distToJoint = jointPivot.length();
  77316. }
  77317. if (distToJoint !== undefined && distToJoint !== null) {
  77318. pos.x += boneDir.x * distToJoint;
  77319. pos.y += boneDir.y * distToJoint;
  77320. pos.z += boneDir.z * distToJoint;
  77321. }
  77322. mesh.setAbsolutePosition(pos);
  77323. };
  77324. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77325. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77326. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77327. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77328. //Impostor types
  77329. PhysicsImpostor.NoImpostor = 0;
  77330. PhysicsImpostor.SphereImpostor = 1;
  77331. PhysicsImpostor.BoxImpostor = 2;
  77332. PhysicsImpostor.PlaneImpostor = 3;
  77333. PhysicsImpostor.MeshImpostor = 4;
  77334. PhysicsImpostor.CylinderImpostor = 7;
  77335. PhysicsImpostor.ParticleImpostor = 8;
  77336. PhysicsImpostor.HeightmapImpostor = 9;
  77337. return PhysicsImpostor;
  77338. }());
  77339. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77340. })(BABYLON || (BABYLON = {}));
  77341. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77342. var BABYLON;
  77343. (function (BABYLON) {
  77344. var PhysicsEngine = /** @class */ (function () {
  77345. function PhysicsEngine(gravity, _physicsPlugin) {
  77346. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77347. this._physicsPlugin = _physicsPlugin;
  77348. //new methods and parameters
  77349. this._impostors = [];
  77350. this._joints = [];
  77351. if (!this._physicsPlugin.isSupported()) {
  77352. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77353. + "Please make sure it is included.");
  77354. }
  77355. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77356. this.setGravity(gravity);
  77357. this.setTimeStep();
  77358. }
  77359. PhysicsEngine.prototype.setGravity = function (gravity) {
  77360. this.gravity = gravity;
  77361. this._physicsPlugin.setGravity(this.gravity);
  77362. };
  77363. /**
  77364. * Set the time step of the physics engine.
  77365. * default is 1/60.
  77366. * To slow it down, enter 1/600 for example.
  77367. * To speed it up, 1/30
  77368. * @param {number} newTimeStep the new timestep to apply to this world.
  77369. */
  77370. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77371. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77372. this._physicsPlugin.setTimeStep(newTimeStep);
  77373. };
  77374. /**
  77375. * Get the time step of the physics engine.
  77376. */
  77377. PhysicsEngine.prototype.getTimeStep = function () {
  77378. return this._physicsPlugin.getTimeStep();
  77379. };
  77380. PhysicsEngine.prototype.dispose = function () {
  77381. this._impostors.forEach(function (impostor) {
  77382. impostor.dispose();
  77383. });
  77384. this._physicsPlugin.dispose();
  77385. };
  77386. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77387. return this._physicsPlugin.name;
  77388. };
  77389. /**
  77390. * Adding a new impostor for the impostor tracking.
  77391. * This will be done by the impostor itself.
  77392. * @param {PhysicsImpostor} impostor the impostor to add
  77393. */
  77394. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77395. impostor.uniqueId = this._impostors.push(impostor);
  77396. //if no parent, generate the body
  77397. if (!impostor.parent) {
  77398. this._physicsPlugin.generatePhysicsBody(impostor);
  77399. }
  77400. };
  77401. /**
  77402. * Remove an impostor from the engine.
  77403. * This impostor and its mesh will not longer be updated by the physics engine.
  77404. * @param {PhysicsImpostor} impostor the impostor to remove
  77405. */
  77406. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77407. var index = this._impostors.indexOf(impostor);
  77408. if (index > -1) {
  77409. var removed = this._impostors.splice(index, 1);
  77410. //Is it needed?
  77411. if (removed.length) {
  77412. //this will also remove it from the world.
  77413. removed[0].physicsBody = null;
  77414. }
  77415. }
  77416. };
  77417. /**
  77418. * Add a joint to the physics engine
  77419. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77420. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77421. * @param {PhysicsJoint} the joint that will connect both impostors.
  77422. */
  77423. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77424. var impostorJoint = {
  77425. mainImpostor: mainImpostor,
  77426. connectedImpostor: connectedImpostor,
  77427. joint: joint
  77428. };
  77429. joint.physicsPlugin = this._physicsPlugin;
  77430. this._joints.push(impostorJoint);
  77431. this._physicsPlugin.generateJoint(impostorJoint);
  77432. };
  77433. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77434. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77435. return (impostorJoint.connectedImpostor === connectedImpostor
  77436. && impostorJoint.joint === joint
  77437. && impostorJoint.mainImpostor === mainImpostor);
  77438. });
  77439. if (matchingJoints.length) {
  77440. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77441. //TODO remove it from the list as well
  77442. }
  77443. };
  77444. /**
  77445. * Called by the scene. no need to call it.
  77446. */
  77447. PhysicsEngine.prototype._step = function (delta) {
  77448. var _this = this;
  77449. //check if any mesh has no body / requires an update
  77450. this._impostors.forEach(function (impostor) {
  77451. if (impostor.isBodyInitRequired()) {
  77452. _this._physicsPlugin.generatePhysicsBody(impostor);
  77453. }
  77454. });
  77455. if (delta > 0.1) {
  77456. delta = 0.1;
  77457. }
  77458. else if (delta <= 0) {
  77459. delta = 1.0 / 60.0;
  77460. }
  77461. this._physicsPlugin.executeStep(delta, this._impostors);
  77462. };
  77463. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77464. return this._physicsPlugin;
  77465. };
  77466. PhysicsEngine.prototype.getImpostors = function () {
  77467. return this._impostors;
  77468. };
  77469. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77470. for (var i = 0; i < this._impostors.length; ++i) {
  77471. if (this._impostors[i].object === object) {
  77472. return this._impostors[i];
  77473. }
  77474. }
  77475. return null;
  77476. };
  77477. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77478. for (var i = 0; i < this._impostors.length; ++i) {
  77479. if (this._impostors[i].physicsBody === body) {
  77480. return this._impostors[i];
  77481. }
  77482. }
  77483. return null;
  77484. };
  77485. // Statics
  77486. PhysicsEngine.Epsilon = 0.001;
  77487. return PhysicsEngine;
  77488. }());
  77489. BABYLON.PhysicsEngine = PhysicsEngine;
  77490. })(BABYLON || (BABYLON = {}));
  77491. //# sourceMappingURL=babylon.physicsEngine.js.map
  77492. var BABYLON;
  77493. (function (BABYLON) {
  77494. var PhysicsHelper = /** @class */ (function () {
  77495. function PhysicsHelper(scene) {
  77496. this._scene = scene;
  77497. this._physicsEngine = this._scene.getPhysicsEngine();
  77498. if (!this._physicsEngine) {
  77499. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77500. }
  77501. }
  77502. /**
  77503. * @param {Vector3} origin the origin of the explosion
  77504. * @param {number} radius the explosion radius
  77505. * @param {number} strength the explosion strength
  77506. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77507. */
  77508. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77509. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77510. if (!this._physicsEngine) {
  77511. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77512. return null;
  77513. }
  77514. var impostors = this._physicsEngine.getImpostors();
  77515. if (impostors.length === 0) {
  77516. return null;
  77517. }
  77518. var event = new PhysicsRadialExplosionEvent(this._scene);
  77519. impostors.forEach(function (impostor) {
  77520. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77521. if (!impostorForceAndContactPoint) {
  77522. return;
  77523. }
  77524. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77525. });
  77526. event.dispose(false);
  77527. return event;
  77528. };
  77529. /**
  77530. * @param {Vector3} origin the origin of the explosion
  77531. * @param {number} radius the explosion radius
  77532. * @param {number} strength the explosion strength
  77533. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77534. */
  77535. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77536. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77537. if (!this._physicsEngine) {
  77538. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77539. return null;
  77540. }
  77541. var impostors = this._physicsEngine.getImpostors();
  77542. if (impostors.length === 0) {
  77543. return null;
  77544. }
  77545. var event = new PhysicsRadialExplosionEvent(this._scene);
  77546. impostors.forEach(function (impostor) {
  77547. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77548. if (!impostorForceAndContactPoint) {
  77549. return;
  77550. }
  77551. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77552. });
  77553. event.dispose(false);
  77554. return event;
  77555. };
  77556. /**
  77557. * @param {Vector3} origin the origin of the explosion
  77558. * @param {number} radius the explosion radius
  77559. * @param {number} strength the explosion strength
  77560. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77561. */
  77562. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77563. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77564. if (!this._physicsEngine) {
  77565. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77566. return null;
  77567. }
  77568. var impostors = this._physicsEngine.getImpostors();
  77569. if (impostors.length === 0) {
  77570. return null;
  77571. }
  77572. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77573. event.dispose(false);
  77574. return event;
  77575. };
  77576. /**
  77577. * @param {Vector3} origin the origin of the updraft
  77578. * @param {number} radius the radius of the updraft
  77579. * @param {number} strength the strength of the updraft
  77580. * @param {number} height the height of the updraft
  77581. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77582. */
  77583. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77584. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77585. if (!this._physicsEngine) {
  77586. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77587. return null;
  77588. }
  77589. if (this._physicsEngine.getImpostors().length === 0) {
  77590. return null;
  77591. }
  77592. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77593. event.dispose(false);
  77594. return event;
  77595. };
  77596. /**
  77597. * @param {Vector3} origin the of the vortex
  77598. * @param {number} radius the radius of the vortex
  77599. * @param {number} strength the strength of the vortex
  77600. * @param {number} height the height of the vortex
  77601. */
  77602. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77603. if (!this._physicsEngine) {
  77604. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77605. return null;
  77606. }
  77607. if (this._physicsEngine.getImpostors().length === 0) {
  77608. return null;
  77609. }
  77610. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77611. event.dispose(false);
  77612. return event;
  77613. };
  77614. return PhysicsHelper;
  77615. }());
  77616. BABYLON.PhysicsHelper = PhysicsHelper;
  77617. /***** Radial explosion *****/
  77618. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77619. function PhysicsRadialExplosionEvent(scene) {
  77620. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77621. this._rays = [];
  77622. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77623. this._scene = scene;
  77624. }
  77625. /**
  77626. * Returns the data related to the radial explosion event (sphere & rays).
  77627. * @returns {PhysicsRadialExplosionEventData}
  77628. */
  77629. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77630. this._dataFetched = true;
  77631. return {
  77632. sphere: this._sphere,
  77633. rays: this._rays,
  77634. };
  77635. };
  77636. /**
  77637. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77638. * @param impostor
  77639. * @param {Vector3} origin the origin of the explosion
  77640. * @param {number} radius the explosion radius
  77641. * @param {number} strength the explosion strength
  77642. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77643. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77644. */
  77645. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77646. if (impostor.mass === 0) {
  77647. return null;
  77648. }
  77649. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77650. return null;
  77651. }
  77652. if (impostor.object.getClassName() !== 'Mesh') {
  77653. return null;
  77654. }
  77655. var impostorObject = impostor.object;
  77656. var impostorObjectCenter = impostor.getObjectCenter();
  77657. var direction = impostorObjectCenter.subtract(origin);
  77658. var ray = new BABYLON.Ray(origin, direction, radius);
  77659. this._rays.push(ray);
  77660. var hit = ray.intersectsMesh(impostorObject);
  77661. var contactPoint = hit.pickedPoint;
  77662. if (!contactPoint) {
  77663. return null;
  77664. }
  77665. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77666. if (distanceFromOrigin > radius) {
  77667. return null;
  77668. }
  77669. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77670. ? strength
  77671. : strength * (1 - (distanceFromOrigin / radius));
  77672. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77673. return { force: force, contactPoint: contactPoint };
  77674. };
  77675. /**
  77676. * Disposes the sphere.
  77677. * @param {bolean} force
  77678. */
  77679. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77680. var _this = this;
  77681. if (force === void 0) { force = true; }
  77682. if (force) {
  77683. this._sphere.dispose();
  77684. }
  77685. else {
  77686. setTimeout(function () {
  77687. if (!_this._dataFetched) {
  77688. _this._sphere.dispose();
  77689. }
  77690. }, 0);
  77691. }
  77692. };
  77693. /*** Helpers ***/
  77694. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77695. if (!this._sphere) {
  77696. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77697. this._sphere.isVisible = false;
  77698. }
  77699. };
  77700. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77701. var impostorObject = impostor.object;
  77702. this._prepareSphere();
  77703. this._sphere.position = origin;
  77704. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77705. this._sphere._updateBoundingInfo();
  77706. this._sphere.computeWorldMatrix(true);
  77707. return this._sphere.intersectsMesh(impostorObject, true);
  77708. };
  77709. return PhysicsRadialExplosionEvent;
  77710. }());
  77711. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77712. /***** Gravitational Field *****/
  77713. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77714. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77715. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77716. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77717. this._physicsHelper = physicsHelper;
  77718. this._scene = scene;
  77719. this._origin = origin;
  77720. this._radius = radius;
  77721. this._strength = strength;
  77722. this._falloff = falloff;
  77723. this._tickCallback = this._tick.bind(this);
  77724. }
  77725. /**
  77726. * Returns the data related to the gravitational field event (sphere).
  77727. * @returns {PhysicsGravitationalFieldEventData}
  77728. */
  77729. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77730. this._dataFetched = true;
  77731. return {
  77732. sphere: this._sphere,
  77733. };
  77734. };
  77735. /**
  77736. * Enables the gravitational field.
  77737. */
  77738. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77739. this._tickCallback.call(this);
  77740. this._scene.registerBeforeRender(this._tickCallback);
  77741. };
  77742. /**
  77743. * Disables the gravitational field.
  77744. */
  77745. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77746. this._scene.unregisterBeforeRender(this._tickCallback);
  77747. };
  77748. /**
  77749. * Disposes the sphere.
  77750. * @param {bolean} force
  77751. */
  77752. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  77753. var _this = this;
  77754. if (force === void 0) { force = true; }
  77755. if (force) {
  77756. this._sphere.dispose();
  77757. }
  77758. else {
  77759. setTimeout(function () {
  77760. if (!_this._dataFetched) {
  77761. _this._sphere.dispose();
  77762. }
  77763. }, 0);
  77764. }
  77765. };
  77766. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77767. // Since the params won't change, we fetch the event only once
  77768. if (this._sphere) {
  77769. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77770. }
  77771. else {
  77772. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77773. if (radialExplosionEvent) {
  77774. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77775. }
  77776. }
  77777. };
  77778. return PhysicsGravitationalFieldEvent;
  77779. }());
  77780. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77781. /***** Updraft *****/
  77782. var PhysicsUpdraftEvent = /** @class */ (function () {
  77783. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77784. this._scene = _scene;
  77785. this._origin = _origin;
  77786. this._radius = _radius;
  77787. this._strength = _strength;
  77788. this._height = _height;
  77789. this._updraftMode = _updraftMode;
  77790. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77791. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77792. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77793. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77794. this._physicsEngine = this._scene.getPhysicsEngine();
  77795. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77796. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77797. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77798. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77799. }
  77800. this._tickCallback = this._tick.bind(this);
  77801. }
  77802. /**
  77803. * Returns the data related to the updraft event (cylinder).
  77804. * @returns {PhysicsUpdraftEventData}
  77805. */
  77806. PhysicsUpdraftEvent.prototype.getData = function () {
  77807. this._dataFetched = true;
  77808. return {
  77809. cylinder: this._cylinder,
  77810. };
  77811. };
  77812. /**
  77813. * Enables the updraft.
  77814. */
  77815. PhysicsUpdraftEvent.prototype.enable = function () {
  77816. this._tickCallback.call(this);
  77817. this._scene.registerBeforeRender(this._tickCallback);
  77818. };
  77819. /**
  77820. * Disables the cortex.
  77821. */
  77822. PhysicsUpdraftEvent.prototype.disable = function () {
  77823. this._scene.unregisterBeforeRender(this._tickCallback);
  77824. };
  77825. /**
  77826. * Disposes the sphere.
  77827. * @param {bolean} force
  77828. */
  77829. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  77830. var _this = this;
  77831. if (force === void 0) { force = true; }
  77832. if (force) {
  77833. this._cylinder.dispose();
  77834. }
  77835. else {
  77836. setTimeout(function () {
  77837. if (!_this._dataFetched) {
  77838. _this._cylinder.dispose();
  77839. }
  77840. }, 0);
  77841. }
  77842. };
  77843. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77844. if (impostor.mass === 0) {
  77845. return null;
  77846. }
  77847. if (!this._intersectsWithCylinder(impostor)) {
  77848. return null;
  77849. }
  77850. var impostorObjectCenter = impostor.getObjectCenter();
  77851. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77852. var direction = this._originDirection;
  77853. }
  77854. else {
  77855. var direction = impostorObjectCenter.subtract(this._originTop);
  77856. }
  77857. var multiplier = this._strength * -1;
  77858. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77859. return { force: force, contactPoint: impostorObjectCenter };
  77860. };
  77861. PhysicsUpdraftEvent.prototype._tick = function () {
  77862. var _this = this;
  77863. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77864. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77865. if (!impostorForceAndContactPoint) {
  77866. return;
  77867. }
  77868. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77869. });
  77870. };
  77871. /*** Helpers ***/
  77872. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  77873. if (!this._cylinder) {
  77874. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  77875. height: this._height,
  77876. diameter: this._radius * 2,
  77877. }, this._scene);
  77878. this._cylinder.isVisible = false;
  77879. }
  77880. };
  77881. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  77882. var impostorObject = impostor.object;
  77883. this._prepareCylinder();
  77884. this._cylinder.position = this._cylinderPosition;
  77885. return this._cylinder.intersectsMesh(impostorObject, true);
  77886. };
  77887. return PhysicsUpdraftEvent;
  77888. }());
  77889. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  77890. /***** Vortex *****/
  77891. var PhysicsVortexEvent = /** @class */ (function () {
  77892. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  77893. this._scene = _scene;
  77894. this._origin = _origin;
  77895. this._radius = _radius;
  77896. this._strength = _strength;
  77897. this._height = _height;
  77898. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77899. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  77900. this._updraftMultiplier = 0.02;
  77901. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77902. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77903. this._physicsEngine = this._scene.getPhysicsEngine();
  77904. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77905. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77906. this._tickCallback = this._tick.bind(this);
  77907. }
  77908. /**
  77909. * Returns the data related to the vortex event (cylinder).
  77910. * @returns {PhysicsVortexEventData}
  77911. */
  77912. PhysicsVortexEvent.prototype.getData = function () {
  77913. this._dataFetched = true;
  77914. return {
  77915. cylinder: this._cylinder,
  77916. };
  77917. };
  77918. /**
  77919. * Enables the vortex.
  77920. */
  77921. PhysicsVortexEvent.prototype.enable = function () {
  77922. this._tickCallback.call(this);
  77923. this._scene.registerBeforeRender(this._tickCallback);
  77924. };
  77925. /**
  77926. * Disables the cortex.
  77927. */
  77928. PhysicsVortexEvent.prototype.disable = function () {
  77929. this._scene.unregisterBeforeRender(this._tickCallback);
  77930. };
  77931. /**
  77932. * Disposes the sphere.
  77933. * @param {bolean} force
  77934. */
  77935. PhysicsVortexEvent.prototype.dispose = function (force) {
  77936. var _this = this;
  77937. if (force === void 0) { force = true; }
  77938. if (force) {
  77939. this._cylinder.dispose();
  77940. }
  77941. else {
  77942. setTimeout(function () {
  77943. if (!_this._dataFetched) {
  77944. _this._cylinder.dispose();
  77945. }
  77946. }, 0);
  77947. }
  77948. };
  77949. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77950. if (impostor.mass === 0) {
  77951. return null;
  77952. }
  77953. if (!this._intersectsWithCylinder(impostor)) {
  77954. return null;
  77955. }
  77956. if (impostor.object.getClassName() !== 'Mesh') {
  77957. return null;
  77958. }
  77959. var impostorObject = impostor.object;
  77960. var impostorObjectCenter = impostor.getObjectCenter();
  77961. 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)
  77962. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77963. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77964. var hit = ray.intersectsMesh(impostorObject);
  77965. var contactPoint = hit.pickedPoint;
  77966. if (!contactPoint) {
  77967. return null;
  77968. }
  77969. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77970. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77971. var directionToOrigin = contactPoint.normalize();
  77972. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77973. directionToOrigin = directionToOrigin.negate();
  77974. }
  77975. // TODO: find a more physically based solution
  77976. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77977. var forceX = directionToOrigin.x * this._strength / 8;
  77978. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77979. var forceZ = directionToOrigin.z * this._strength / 8;
  77980. }
  77981. else {
  77982. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77983. var forceY = this._originTop.y * this._updraftMultiplier;
  77984. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77985. }
  77986. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77987. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77988. return { force: force, contactPoint: impostorObjectCenter };
  77989. };
  77990. PhysicsVortexEvent.prototype._tick = function () {
  77991. var _this = this;
  77992. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77993. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77994. if (!impostorForceAndContactPoint) {
  77995. return;
  77996. }
  77997. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77998. });
  77999. };
  78000. /*** Helpers ***/
  78001. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78002. if (!this._cylinder) {
  78003. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78004. height: this._height,
  78005. diameter: this._radius * 2,
  78006. }, this._scene);
  78007. this._cylinder.isVisible = false;
  78008. }
  78009. };
  78010. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78011. var impostorObject = impostor.object;
  78012. this._prepareCylinder();
  78013. this._cylinder.position = this._cylinderPosition;
  78014. return this._cylinder.intersectsMesh(impostorObject, true);
  78015. };
  78016. return PhysicsVortexEvent;
  78017. }());
  78018. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78019. /***** Enums *****/
  78020. /**
  78021. * The strenght of the force in correspondence to the distance of the affected object
  78022. */
  78023. var PhysicsRadialImpulseFalloff;
  78024. (function (PhysicsRadialImpulseFalloff) {
  78025. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78026. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78027. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78028. /**
  78029. * The strenght of the force in correspondence to the distance of the affected object
  78030. */
  78031. var PhysicsUpdraftMode;
  78032. (function (PhysicsUpdraftMode) {
  78033. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78034. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78035. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78036. })(BABYLON || (BABYLON = {}));
  78037. //# sourceMappingURL=babylon.physicsHelper.js.map
  78038. var BABYLON;
  78039. (function (BABYLON) {
  78040. var CannonJSPlugin = /** @class */ (function () {
  78041. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78042. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78043. if (iterations === void 0) { iterations = 10; }
  78044. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78045. this.name = "CannonJSPlugin";
  78046. this._physicsMaterials = new Array();
  78047. this._fixedTimeStep = 1 / 60;
  78048. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78049. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  78050. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78051. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78052. this._tmpPosition = BABYLON.Vector3.Zero();
  78053. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78054. this._tmpUnityRotation = new BABYLON.Quaternion();
  78055. if (!this.isSupported()) {
  78056. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78057. return;
  78058. }
  78059. this._extendNamespace();
  78060. this.world = new this.BJSCANNON.World();
  78061. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78062. this.world.solver.iterations = iterations;
  78063. }
  78064. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78065. this.world.gravity.copy(gravity);
  78066. };
  78067. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78068. this._fixedTimeStep = timeStep;
  78069. };
  78070. CannonJSPlugin.prototype.getTimeStep = function () {
  78071. return this._fixedTimeStep;
  78072. };
  78073. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78074. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78075. };
  78076. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78077. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78078. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78079. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78080. };
  78081. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78082. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78083. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78084. impostor.physicsBody.applyForce(impulse, worldPoint);
  78085. };
  78086. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78087. //parent-child relationship. Does this impostor has a parent impostor?
  78088. if (impostor.parent) {
  78089. if (impostor.physicsBody) {
  78090. this.removePhysicsBody(impostor);
  78091. //TODO is that needed?
  78092. impostor.forceUpdate();
  78093. }
  78094. return;
  78095. }
  78096. //should a new body be created for this impostor?
  78097. if (impostor.isBodyInitRequired()) {
  78098. var shape = this._createShape(impostor);
  78099. //unregister events, if body is being changed
  78100. var oldBody = impostor.physicsBody;
  78101. if (oldBody) {
  78102. this.removePhysicsBody(impostor);
  78103. }
  78104. //create the body and material
  78105. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78106. var bodyCreationObject = {
  78107. mass: impostor.getParam("mass"),
  78108. material: material
  78109. };
  78110. // A simple extend, in case native options were used.
  78111. var nativeOptions = impostor.getParam("nativeOptions");
  78112. for (var key in nativeOptions) {
  78113. if (nativeOptions.hasOwnProperty(key)) {
  78114. bodyCreationObject[key] = nativeOptions[key];
  78115. }
  78116. }
  78117. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78118. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78119. this.world.addEventListener("preStep", impostor.beforeStep);
  78120. this.world.addEventListener("postStep", impostor.afterStep);
  78121. impostor.physicsBody.addShape(shape);
  78122. this.world.add(impostor.physicsBody);
  78123. //try to keep the body moving in the right direction by taking old properties.
  78124. //Should be tested!
  78125. if (oldBody) {
  78126. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78127. impostor.physicsBody[param].copy(oldBody[param]);
  78128. });
  78129. }
  78130. this._processChildMeshes(impostor);
  78131. }
  78132. //now update the body's transformation
  78133. this._updatePhysicsBodyTransformation(impostor);
  78134. };
  78135. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78136. var _this = this;
  78137. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78138. var currentRotation = mainImpostor.object.rotationQuaternion;
  78139. if (meshChildren.length) {
  78140. var processMesh = function (localPosition, mesh) {
  78141. if (!currentRotation || !mesh.rotationQuaternion) {
  78142. return;
  78143. }
  78144. var childImpostor = mesh.getPhysicsImpostor();
  78145. if (childImpostor) {
  78146. var parent = childImpostor.parent;
  78147. if (parent !== mainImpostor) {
  78148. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78149. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78150. if (childImpostor.physicsBody) {
  78151. _this.removePhysicsBody(childImpostor);
  78152. childImpostor.physicsBody = null;
  78153. }
  78154. childImpostor.parent = mainImpostor;
  78155. childImpostor.resetUpdateFlags();
  78156. 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));
  78157. //Add the mass of the children.
  78158. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78159. }
  78160. }
  78161. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78162. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78163. };
  78164. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78165. }
  78166. };
  78167. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78168. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78169. this.world.removeEventListener("preStep", impostor.beforeStep);
  78170. this.world.removeEventListener("postStep", impostor.afterStep);
  78171. this.world.remove(impostor.physicsBody);
  78172. };
  78173. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78174. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78175. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78176. if (!mainBody || !connectedBody) {
  78177. return;
  78178. }
  78179. var constraint;
  78180. var jointData = impostorJoint.joint.jointData;
  78181. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78182. var constraintData = {
  78183. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78184. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78185. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78186. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78187. maxForce: jointData.nativeParams.maxForce,
  78188. collideConnected: !!jointData.collision
  78189. };
  78190. switch (impostorJoint.joint.type) {
  78191. case BABYLON.PhysicsJoint.HingeJoint:
  78192. case BABYLON.PhysicsJoint.Hinge2Joint:
  78193. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78194. break;
  78195. case BABYLON.PhysicsJoint.DistanceJoint:
  78196. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78197. break;
  78198. case BABYLON.PhysicsJoint.SpringJoint:
  78199. var springData = jointData;
  78200. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78201. restLength: springData.length,
  78202. stiffness: springData.stiffness,
  78203. damping: springData.damping,
  78204. localAnchorA: constraintData.pivotA,
  78205. localAnchorB: constraintData.pivotB
  78206. });
  78207. break;
  78208. case BABYLON.PhysicsJoint.LockJoint:
  78209. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78210. break;
  78211. case BABYLON.PhysicsJoint.PointToPointJoint:
  78212. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78213. default:
  78214. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78215. break;
  78216. }
  78217. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78218. constraint.collideConnected = !!jointData.collision;
  78219. impostorJoint.joint.physicsJoint = constraint;
  78220. //don't add spring as constraint, as it is not one.
  78221. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78222. this.world.addConstraint(constraint);
  78223. }
  78224. else {
  78225. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78226. constraint.applyForce();
  78227. });
  78228. }
  78229. };
  78230. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78231. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78232. };
  78233. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78234. var index;
  78235. var mat;
  78236. for (index = 0; index < this._physicsMaterials.length; index++) {
  78237. mat = this._physicsMaterials[index];
  78238. if (mat.friction === friction && mat.restitution === restitution) {
  78239. return mat;
  78240. }
  78241. }
  78242. var currentMat = new this.BJSCANNON.Material(name);
  78243. currentMat.friction = friction;
  78244. currentMat.restitution = restitution;
  78245. this._physicsMaterials.push(currentMat);
  78246. return currentMat;
  78247. };
  78248. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78249. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78250. };
  78251. CannonJSPlugin.prototype._createShape = function (impostor) {
  78252. var object = impostor.object;
  78253. var returnValue;
  78254. var extendSize = impostor.getObjectExtendSize();
  78255. switch (impostor.type) {
  78256. case BABYLON.PhysicsImpostor.SphereImpostor:
  78257. var radiusX = extendSize.x;
  78258. var radiusY = extendSize.y;
  78259. var radiusZ = extendSize.z;
  78260. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78261. break;
  78262. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78263. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78264. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78265. break;
  78266. case BABYLON.PhysicsImpostor.BoxImpostor:
  78267. var box = extendSize.scale(0.5);
  78268. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78269. break;
  78270. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78271. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78272. returnValue = new this.BJSCANNON.Plane();
  78273. break;
  78274. case BABYLON.PhysicsImpostor.MeshImpostor:
  78275. // should transform the vertex data to world coordinates!!
  78276. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78277. var rawFaces = object.getIndices ? object.getIndices() : [];
  78278. if (!rawVerts)
  78279. return;
  78280. // get only scale! so the object could transform correctly.
  78281. var oldPosition = object.position.clone();
  78282. var oldRotation = object.rotation && object.rotation.clone();
  78283. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78284. object.position.copyFromFloats(0, 0, 0);
  78285. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78286. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78287. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78288. var transform = object.computeWorldMatrix(true);
  78289. // convert rawVerts to object space
  78290. var temp = new Array();
  78291. var index;
  78292. for (index = 0; index < rawVerts.length; index += 3) {
  78293. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78294. }
  78295. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78296. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78297. //now set back the transformation!
  78298. object.position.copyFrom(oldPosition);
  78299. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78300. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78301. break;
  78302. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78303. var oldPosition2 = object.position.clone();
  78304. var oldRotation2 = object.rotation && object.rotation.clone();
  78305. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78306. object.position.copyFromFloats(0, 0, 0);
  78307. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78308. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78309. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78310. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78311. returnValue = this._createHeightmap(object);
  78312. object.position.copyFrom(oldPosition2);
  78313. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78314. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78315. object.computeWorldMatrix(true);
  78316. break;
  78317. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78318. returnValue = new this.BJSCANNON.Particle();
  78319. break;
  78320. }
  78321. return returnValue;
  78322. };
  78323. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78324. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78325. var transform = object.computeWorldMatrix(true);
  78326. // convert rawVerts to object space
  78327. var temp = new Array();
  78328. var index;
  78329. for (index = 0; index < pos.length; index += 3) {
  78330. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78331. }
  78332. pos = temp;
  78333. var matrix = new Array();
  78334. //For now pointDepth will not be used and will be automatically calculated.
  78335. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78336. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78337. var boundingInfo = object.getBoundingInfo();
  78338. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78339. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78340. var elementSize = dim * 2 / arraySize;
  78341. for (var i = 0; i < pos.length; i = i + 3) {
  78342. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78343. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78344. var y = -pos[i + 2] + minY;
  78345. if (!matrix[x]) {
  78346. matrix[x] = [];
  78347. }
  78348. if (!matrix[x][z]) {
  78349. matrix[x][z] = y;
  78350. }
  78351. matrix[x][z] = Math.max(y, matrix[x][z]);
  78352. }
  78353. for (var x = 0; x <= arraySize; ++x) {
  78354. if (!matrix[x]) {
  78355. var loc = 1;
  78356. while (!matrix[(x + loc) % arraySize]) {
  78357. loc++;
  78358. }
  78359. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78360. //console.log("missing x", x);
  78361. }
  78362. for (var z = 0; z <= arraySize; ++z) {
  78363. if (!matrix[x][z]) {
  78364. var loc = 1;
  78365. var newValue;
  78366. while (newValue === undefined) {
  78367. newValue = matrix[x][(z + loc++) % arraySize];
  78368. }
  78369. matrix[x][z] = newValue;
  78370. }
  78371. }
  78372. }
  78373. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78374. elementSize: elementSize
  78375. });
  78376. //For future reference, needed for body transformation
  78377. shape.minY = minY;
  78378. return shape;
  78379. };
  78380. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78381. var object = impostor.object;
  78382. //make sure it is updated...
  78383. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78384. // The delta between the mesh position and the mesh bounding box center
  78385. var bInfo = object.getBoundingInfo();
  78386. if (!bInfo)
  78387. return;
  78388. var center = impostor.getObjectCenter();
  78389. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78390. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78391. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78392. this._tmpPosition.copyFrom(center);
  78393. var quaternion = object.rotationQuaternion;
  78394. if (!quaternion) {
  78395. return;
  78396. }
  78397. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78398. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78399. //-90 DEG in X, precalculated
  78400. quaternion = quaternion.multiply(this._minus90X);
  78401. //Invert! (Precalculated, 90 deg in X)
  78402. //No need to clone. this will never change.
  78403. impostor.setDeltaRotation(this._plus90X);
  78404. }
  78405. //If it is a heightfield, if should be centered.
  78406. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78407. var mesh = object;
  78408. var boundingInfo = mesh.getBoundingInfo();
  78409. //calculate the correct body position:
  78410. var rotationQuaternion = mesh.rotationQuaternion;
  78411. mesh.rotationQuaternion = this._tmpUnityRotation;
  78412. mesh.computeWorldMatrix(true);
  78413. //get original center with no rotation
  78414. var c = center.clone();
  78415. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78416. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78417. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78418. mesh.setPreTransformMatrix(p);
  78419. mesh.computeWorldMatrix(true);
  78420. //calculate the translation
  78421. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78422. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78423. //add it inverted to the delta
  78424. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78425. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78426. //rotation is back
  78427. mesh.rotationQuaternion = rotationQuaternion;
  78428. mesh.setPreTransformMatrix(oldPivot);
  78429. mesh.computeWorldMatrix(true);
  78430. }
  78431. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78432. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78433. //this._tmpPosition.copyFrom(object.position);
  78434. }
  78435. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78436. //Now update the impostor object
  78437. impostor.physicsBody.position.copy(this._tmpPosition);
  78438. impostor.physicsBody.quaternion.copy(quaternion);
  78439. };
  78440. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78441. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78442. if (impostor.object.rotationQuaternion) {
  78443. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78444. }
  78445. };
  78446. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78447. impostor.physicsBody.position.copy(newPosition);
  78448. impostor.physicsBody.quaternion.copy(newRotation);
  78449. };
  78450. CannonJSPlugin.prototype.isSupported = function () {
  78451. return this.BJSCANNON !== undefined;
  78452. };
  78453. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78454. impostor.physicsBody.velocity.copy(velocity);
  78455. };
  78456. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78457. impostor.physicsBody.angularVelocity.copy(velocity);
  78458. };
  78459. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78460. var v = impostor.physicsBody.velocity;
  78461. if (!v) {
  78462. return null;
  78463. }
  78464. return new BABYLON.Vector3(v.x, v.y, v.z);
  78465. };
  78466. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78467. var v = impostor.physicsBody.angularVelocity;
  78468. if (!v) {
  78469. return null;
  78470. }
  78471. return new BABYLON.Vector3(v.x, v.y, v.z);
  78472. };
  78473. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78474. impostor.physicsBody.mass = mass;
  78475. impostor.physicsBody.updateMassProperties();
  78476. };
  78477. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78478. return impostor.physicsBody.mass;
  78479. };
  78480. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78481. return impostor.physicsBody.material.friction;
  78482. };
  78483. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78484. impostor.physicsBody.material.friction = friction;
  78485. };
  78486. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78487. return impostor.physicsBody.material.restitution;
  78488. };
  78489. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78490. impostor.physicsBody.material.restitution = restitution;
  78491. };
  78492. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78493. impostor.physicsBody.sleep();
  78494. };
  78495. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78496. impostor.physicsBody.wakeUp();
  78497. };
  78498. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78499. joint.physicsJoint.distance = maxDistance;
  78500. };
  78501. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78502. // if (!motorIndex) {
  78503. // joint.physicsJoint.enableMotor();
  78504. // }
  78505. // }
  78506. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78507. // if (!motorIndex) {
  78508. // joint.physicsJoint.disableMotor();
  78509. // }
  78510. // }
  78511. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78512. if (!motorIndex) {
  78513. joint.physicsJoint.enableMotor();
  78514. joint.physicsJoint.setMotorSpeed(speed);
  78515. if (maxForce) {
  78516. this.setLimit(joint, maxForce);
  78517. }
  78518. }
  78519. };
  78520. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78521. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78522. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78523. };
  78524. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78525. var body = impostor.physicsBody;
  78526. mesh.position.x = body.position.x;
  78527. mesh.position.y = body.position.y;
  78528. mesh.position.z = body.position.z;
  78529. if (mesh.rotationQuaternion) {
  78530. mesh.rotationQuaternion.x = body.quaternion.x;
  78531. mesh.rotationQuaternion.y = body.quaternion.y;
  78532. mesh.rotationQuaternion.z = body.quaternion.z;
  78533. mesh.rotationQuaternion.w = body.quaternion.w;
  78534. }
  78535. };
  78536. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78537. var shape = impostor.physicsBody.shapes[0];
  78538. return shape.boundingSphereRadius;
  78539. };
  78540. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78541. var shape = impostor.physicsBody.shapes[0];
  78542. result.x = shape.halfExtents.x * 2;
  78543. result.y = shape.halfExtents.y * 2;
  78544. result.z = shape.halfExtents.z * 2;
  78545. };
  78546. CannonJSPlugin.prototype.dispose = function () {
  78547. };
  78548. CannonJSPlugin.prototype._extendNamespace = function () {
  78549. //this will force cannon to execute at least one step when using interpolation
  78550. var step_tmp1 = new this.BJSCANNON.Vec3();
  78551. var Engine = this.BJSCANNON;
  78552. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78553. maxSubSteps = maxSubSteps || 10;
  78554. timeSinceLastCalled = timeSinceLastCalled || 0;
  78555. if (timeSinceLastCalled === 0) {
  78556. this.internalStep(dt);
  78557. this.time += dt;
  78558. }
  78559. else {
  78560. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78561. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78562. var t0 = performance.now();
  78563. for (var i = 0; i !== internalSteps; i++) {
  78564. this.internalStep(dt);
  78565. if (performance.now() - t0 > dt * 1000) {
  78566. break;
  78567. }
  78568. }
  78569. this.time += timeSinceLastCalled;
  78570. var h = this.time % dt;
  78571. var h_div_dt = h / dt;
  78572. var interpvelo = step_tmp1;
  78573. var bodies = this.bodies;
  78574. for (var j = 0; j !== bodies.length; j++) {
  78575. var b = bodies[j];
  78576. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78577. b.position.vsub(b.previousPosition, interpvelo);
  78578. interpvelo.scale(h_div_dt, interpvelo);
  78579. b.position.vadd(interpvelo, b.interpolatedPosition);
  78580. }
  78581. else {
  78582. b.interpolatedPosition.copy(b.position);
  78583. b.interpolatedQuaternion.copy(b.quaternion);
  78584. }
  78585. }
  78586. }
  78587. };
  78588. };
  78589. return CannonJSPlugin;
  78590. }());
  78591. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78592. })(BABYLON || (BABYLON = {}));
  78593. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78594. var BABYLON;
  78595. (function (BABYLON) {
  78596. var OimoJSPlugin = /** @class */ (function () {
  78597. function OimoJSPlugin(iterations) {
  78598. this.name = "OimoJSPlugin";
  78599. this._tmpImpostorsArray = [];
  78600. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78601. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  78602. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  78603. this.world.worldscale(1);
  78604. this.world.clear();
  78605. //making sure no stats are calculated
  78606. this.world.isNoStat = true;
  78607. }
  78608. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78609. this.world.gravity.copy(gravity);
  78610. };
  78611. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78612. this.world.timeStep = timeStep;
  78613. };
  78614. OimoJSPlugin.prototype.getTimeStep = function () {
  78615. return this.world.timeStep;
  78616. };
  78617. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78618. var _this = this;
  78619. impostors.forEach(function (impostor) {
  78620. impostor.beforeStep();
  78621. });
  78622. this.world.step();
  78623. impostors.forEach(function (impostor) {
  78624. impostor.afterStep();
  78625. //update the ordered impostors array
  78626. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78627. });
  78628. //check for collisions
  78629. var contact = this.world.contacts;
  78630. while (contact !== null) {
  78631. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78632. contact = contact.next;
  78633. continue;
  78634. }
  78635. //is this body colliding with any other? get the impostor
  78636. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78637. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78638. if (!mainImpostor || !collidingImpostor) {
  78639. contact = contact.next;
  78640. continue;
  78641. }
  78642. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78643. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78644. contact = contact.next;
  78645. }
  78646. };
  78647. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78648. var mass = impostor.physicsBody.massInfo.mass;
  78649. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  78650. };
  78651. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78652. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78653. this.applyImpulse(impostor, force, contactPoint);
  78654. };
  78655. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78656. var _this = this;
  78657. //parent-child relationship. Does this impostor has a parent impostor?
  78658. if (impostor.parent) {
  78659. if (impostor.physicsBody) {
  78660. this.removePhysicsBody(impostor);
  78661. //TODO is that needed?
  78662. impostor.forceUpdate();
  78663. }
  78664. return;
  78665. }
  78666. if (impostor.isBodyInitRequired()) {
  78667. var bodyConfig = {
  78668. name: impostor.uniqueId,
  78669. //Oimo must have mass, also for static objects.
  78670. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78671. size: [],
  78672. type: [],
  78673. pos: [],
  78674. rot: [],
  78675. move: impostor.getParam("mass") !== 0,
  78676. //Supporting older versions of Oimo
  78677. world: this.world
  78678. };
  78679. var impostors = [impostor];
  78680. var addToArray = function (parent) {
  78681. if (!parent.getChildMeshes)
  78682. return;
  78683. parent.getChildMeshes().forEach(function (m) {
  78684. if (m.physicsImpostor) {
  78685. impostors.push(m.physicsImpostor);
  78686. //m.physicsImpostor._init();
  78687. }
  78688. });
  78689. };
  78690. addToArray(impostor.object);
  78691. var checkWithEpsilon_1 = function (value) {
  78692. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78693. };
  78694. impostors.forEach(function (i) {
  78695. if (!impostor.object.rotationQuaternion) {
  78696. return;
  78697. }
  78698. //get the correct bounding box
  78699. var oldQuaternion = i.object.rotationQuaternion;
  78700. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  78701. x: impostor.object.rotationQuaternion.x,
  78702. y: impostor.object.rotationQuaternion.y,
  78703. z: impostor.object.rotationQuaternion.z,
  78704. s: impostor.object.rotationQuaternion.w
  78705. });
  78706. var extendSize = i.getObjectExtendSize();
  78707. if (i === impostor) {
  78708. var center = impostor.getObjectCenter();
  78709. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78710. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78711. //Can also use Array.prototype.push.apply
  78712. bodyConfig.pos.push(center.x);
  78713. bodyConfig.pos.push(center.y);
  78714. bodyConfig.pos.push(center.z);
  78715. //tmp solution
  78716. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78717. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78718. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78719. }
  78720. else {
  78721. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78722. bodyConfig.pos.push(localPosition.x);
  78723. bodyConfig.pos.push(localPosition.y);
  78724. bodyConfig.pos.push(localPosition.z);
  78725. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78726. bodyConfig.rot.push(0);
  78727. bodyConfig.rot.push(0);
  78728. bodyConfig.rot.push(0);
  78729. }
  78730. // register mesh
  78731. switch (i.type) {
  78732. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78733. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  78734. case BABYLON.PhysicsImpostor.SphereImpostor:
  78735. var radiusX = extendSize.x;
  78736. var radiusY = extendSize.y;
  78737. var radiusZ = extendSize.z;
  78738. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78739. bodyConfig.type.push('sphere');
  78740. //due to the way oimo works with compounds, add 3 times
  78741. bodyConfig.size.push(size);
  78742. bodyConfig.size.push(size);
  78743. bodyConfig.size.push(size);
  78744. break;
  78745. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78746. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  78747. var sizeY = checkWithEpsilon_1(extendSize.y);
  78748. bodyConfig.type.push('cylinder');
  78749. bodyConfig.size.push(sizeX);
  78750. bodyConfig.size.push(sizeY);
  78751. //due to the way oimo works with compounds, add one more value.
  78752. bodyConfig.size.push(sizeY);
  78753. break;
  78754. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78755. case BABYLON.PhysicsImpostor.BoxImpostor:
  78756. default:
  78757. var sizeX = checkWithEpsilon_1(extendSize.x);
  78758. var sizeY = checkWithEpsilon_1(extendSize.y);
  78759. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78760. bodyConfig.type.push('box');
  78761. bodyConfig.size.push(sizeX);
  78762. bodyConfig.size.push(sizeY);
  78763. bodyConfig.size.push(sizeZ);
  78764. break;
  78765. }
  78766. //actually not needed, but hey...
  78767. i.object.rotationQuaternion = oldQuaternion;
  78768. });
  78769. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  78770. }
  78771. else {
  78772. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78773. }
  78774. impostor.setDeltaPosition(this._tmpPositionVector);
  78775. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78776. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78777. };
  78778. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78779. //impostor.physicsBody.dispose();
  78780. //Same as : (older oimo versions)
  78781. this.world.removeRigidBody(impostor.physicsBody);
  78782. };
  78783. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78784. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78785. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78786. if (!mainBody || !connectedBody) {
  78787. return;
  78788. }
  78789. var jointData = impostorJoint.joint.jointData;
  78790. var options = jointData.nativeParams || {};
  78791. var type;
  78792. var nativeJointData = {
  78793. body1: mainBody,
  78794. body2: connectedBody,
  78795. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78796. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78797. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78798. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78799. min: options.min,
  78800. max: options.max,
  78801. collision: options.collision || jointData.collision,
  78802. spring: options.spring,
  78803. //supporting older version of Oimo
  78804. world: this.world
  78805. };
  78806. switch (impostorJoint.joint.type) {
  78807. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78808. type = "jointBall";
  78809. break;
  78810. case BABYLON.PhysicsJoint.SpringJoint:
  78811. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  78812. var springData = jointData;
  78813. nativeJointData.min = springData.length || nativeJointData.min;
  78814. //Max should also be set, just make sure it is at least min
  78815. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  78816. case BABYLON.PhysicsJoint.DistanceJoint:
  78817. type = "jointDistance";
  78818. nativeJointData.max = jointData.maxDistance;
  78819. break;
  78820. case BABYLON.PhysicsJoint.PrismaticJoint:
  78821. type = "jointPrisme";
  78822. break;
  78823. case BABYLON.PhysicsJoint.SliderJoint:
  78824. type = "jointSlide";
  78825. break;
  78826. case BABYLON.PhysicsJoint.WheelJoint:
  78827. type = "jointWheel";
  78828. break;
  78829. case BABYLON.PhysicsJoint.HingeJoint:
  78830. default:
  78831. type = "jointHinge";
  78832. break;
  78833. }
  78834. nativeJointData.type = type;
  78835. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  78836. };
  78837. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78838. //Bug in Oimo prevents us from disposing a joint in the playground
  78839. //joint.joint.physicsJoint.dispose();
  78840. //So we will bruteforce it!
  78841. try {
  78842. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  78843. }
  78844. catch (e) {
  78845. BABYLON.Tools.Warn(e);
  78846. }
  78847. };
  78848. OimoJSPlugin.prototype.isSupported = function () {
  78849. return this.BJSOIMO !== undefined;
  78850. };
  78851. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78852. if (!impostor.physicsBody.sleeping) {
  78853. //TODO check that
  78854. if (impostor.physicsBody.shapes.next) {
  78855. var parentShape = this._getLastShape(impostor.physicsBody);
  78856. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  78857. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  78858. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  78859. }
  78860. else {
  78861. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  78862. }
  78863. if (impostor.object.rotationQuaternion) {
  78864. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  78865. impostor.object.rotationQuaternion.normalize();
  78866. }
  78867. }
  78868. };
  78869. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78870. var body = impostor.physicsBody;
  78871. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  78872. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  78873. body.syncShapes();
  78874. body.awake();
  78875. };
  78876. OimoJSPlugin.prototype._getLastShape = function (body) {
  78877. var lastShape = body.shapes;
  78878. while (lastShape.next) {
  78879. lastShape = lastShape.next;
  78880. }
  78881. return lastShape;
  78882. };
  78883. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78884. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  78885. };
  78886. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78887. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  78888. };
  78889. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78890. var v = impostor.physicsBody.linearVelocity;
  78891. if (!v) {
  78892. return null;
  78893. }
  78894. return new BABYLON.Vector3(v.x, v.y, v.z);
  78895. };
  78896. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78897. var v = impostor.physicsBody.angularVelocity;
  78898. if (!v) {
  78899. return null;
  78900. }
  78901. return new BABYLON.Vector3(v.x, v.y, v.z);
  78902. };
  78903. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78904. var staticBody = mass === 0;
  78905. //this will actually set the body's density and not its mass.
  78906. //But this is how oimo treats the mass variable.
  78907. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78908. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78909. };
  78910. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78911. return impostor.physicsBody.shapes.density;
  78912. };
  78913. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78914. return impostor.physicsBody.shapes.friction;
  78915. };
  78916. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78917. impostor.physicsBody.shapes.friction = friction;
  78918. };
  78919. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78920. return impostor.physicsBody.shapes.restitution;
  78921. };
  78922. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78923. impostor.physicsBody.shapes.restitution = restitution;
  78924. };
  78925. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78926. impostor.physicsBody.sleep();
  78927. };
  78928. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78929. impostor.physicsBody.awake();
  78930. };
  78931. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78932. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78933. if (minDistance !== void 0) {
  78934. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78935. }
  78936. };
  78937. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78938. //TODO separate rotational and transational motors.
  78939. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78940. if (motor) {
  78941. motor.setMotor(speed, maxForce);
  78942. }
  78943. };
  78944. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78945. //TODO separate rotational and transational motors.
  78946. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78947. if (motor) {
  78948. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78949. }
  78950. };
  78951. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78952. var body = impostor.physicsBody;
  78953. mesh.position.x = body.position.x;
  78954. mesh.position.y = body.position.y;
  78955. mesh.position.z = body.position.z;
  78956. if (mesh.rotationQuaternion) {
  78957. mesh.rotationQuaternion.x = body.orientation.x;
  78958. mesh.rotationQuaternion.y = body.orientation.y;
  78959. mesh.rotationQuaternion.z = body.orientation.z;
  78960. mesh.rotationQuaternion.w = body.orientation.s;
  78961. }
  78962. };
  78963. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78964. return impostor.physicsBody.shapes.radius;
  78965. };
  78966. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78967. var shape = impostor.physicsBody.shapes;
  78968. result.x = shape.halfWidth * 2;
  78969. result.y = shape.halfHeight * 2;
  78970. result.z = shape.halfDepth * 2;
  78971. };
  78972. OimoJSPlugin.prototype.dispose = function () {
  78973. this.world.clear();
  78974. };
  78975. return OimoJSPlugin;
  78976. }());
  78977. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78978. })(BABYLON || (BABYLON = {}));
  78979. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78980. var BABYLON;
  78981. (function (BABYLON) {
  78982. /*
  78983. * Based on jsTGALoader - Javascript loader for TGA file
  78984. * By Vincent Thibault
  78985. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78986. */
  78987. var TGATools = /** @class */ (function () {
  78988. function TGATools() {
  78989. }
  78990. TGATools.GetTGAHeader = function (data) {
  78991. var offset = 0;
  78992. var header = {
  78993. id_length: data[offset++],
  78994. colormap_type: data[offset++],
  78995. image_type: data[offset++],
  78996. colormap_index: data[offset++] | data[offset++] << 8,
  78997. colormap_length: data[offset++] | data[offset++] << 8,
  78998. colormap_size: data[offset++],
  78999. origin: [
  79000. data[offset++] | data[offset++] << 8,
  79001. data[offset++] | data[offset++] << 8
  79002. ],
  79003. width: data[offset++] | data[offset++] << 8,
  79004. height: data[offset++] | data[offset++] << 8,
  79005. pixel_size: data[offset++],
  79006. flags: data[offset++]
  79007. };
  79008. return header;
  79009. };
  79010. TGATools.UploadContent = function (gl, data) {
  79011. // Not enough data to contain header ?
  79012. if (data.length < 19) {
  79013. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79014. return;
  79015. }
  79016. // Read Header
  79017. var offset = 18;
  79018. var header = TGATools.GetTGAHeader(data);
  79019. // Assume it's a valid Targa file.
  79020. if (header.id_length + offset > data.length) {
  79021. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79022. return;
  79023. }
  79024. // Skip not needed data
  79025. offset += header.id_length;
  79026. var use_rle = false;
  79027. var use_pal = false;
  79028. var use_grey = false;
  79029. // Get some informations.
  79030. switch (header.image_type) {
  79031. case TGATools._TYPE_RLE_INDEXED:
  79032. use_rle = true;
  79033. case TGATools._TYPE_INDEXED:
  79034. use_pal = true;
  79035. break;
  79036. case TGATools._TYPE_RLE_RGB:
  79037. use_rle = true;
  79038. case TGATools._TYPE_RGB:
  79039. // use_rgb = true;
  79040. break;
  79041. case TGATools._TYPE_RLE_GREY:
  79042. use_rle = true;
  79043. case TGATools._TYPE_GREY:
  79044. use_grey = true;
  79045. break;
  79046. }
  79047. var pixel_data;
  79048. // var numAlphaBits = header.flags & 0xf;
  79049. var pixel_size = header.pixel_size >> 3;
  79050. var pixel_total = header.width * header.height * pixel_size;
  79051. // Read palettes
  79052. var palettes;
  79053. if (use_pal) {
  79054. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79055. }
  79056. // Read LRE
  79057. if (use_rle) {
  79058. pixel_data = new Uint8Array(pixel_total);
  79059. var c, count, i;
  79060. var localOffset = 0;
  79061. var pixels = new Uint8Array(pixel_size);
  79062. while (offset < pixel_total && localOffset < pixel_total) {
  79063. c = data[offset++];
  79064. count = (c & 0x7f) + 1;
  79065. // RLE pixels
  79066. if (c & 0x80) {
  79067. // Bind pixel tmp array
  79068. for (i = 0; i < pixel_size; ++i) {
  79069. pixels[i] = data[offset++];
  79070. }
  79071. // Copy pixel array
  79072. for (i = 0; i < count; ++i) {
  79073. pixel_data.set(pixels, localOffset + i * pixel_size);
  79074. }
  79075. localOffset += pixel_size * count;
  79076. }
  79077. else {
  79078. count *= pixel_size;
  79079. for (i = 0; i < count; ++i) {
  79080. pixel_data[localOffset + i] = data[offset++];
  79081. }
  79082. localOffset += count;
  79083. }
  79084. }
  79085. }
  79086. else {
  79087. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79088. }
  79089. // Load to texture
  79090. var x_start, y_start, x_step, y_step, y_end, x_end;
  79091. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79092. default:
  79093. case TGATools._ORIGIN_UL:
  79094. x_start = 0;
  79095. x_step = 1;
  79096. x_end = header.width;
  79097. y_start = 0;
  79098. y_step = 1;
  79099. y_end = header.height;
  79100. break;
  79101. case TGATools._ORIGIN_BL:
  79102. x_start = 0;
  79103. x_step = 1;
  79104. x_end = header.width;
  79105. y_start = header.height - 1;
  79106. y_step = -1;
  79107. y_end = -1;
  79108. break;
  79109. case TGATools._ORIGIN_UR:
  79110. x_start = header.width - 1;
  79111. x_step = -1;
  79112. x_end = -1;
  79113. y_start = 0;
  79114. y_step = 1;
  79115. y_end = header.height;
  79116. break;
  79117. case TGATools._ORIGIN_BR:
  79118. x_start = header.width - 1;
  79119. x_step = -1;
  79120. x_end = -1;
  79121. y_start = header.height - 1;
  79122. y_step = -1;
  79123. y_end = -1;
  79124. break;
  79125. }
  79126. // Load the specify method
  79127. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79128. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79129. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79130. };
  79131. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79132. var image = pixel_data, colormap = palettes;
  79133. var width = header.width, height = header.height;
  79134. var color, i = 0, x, y;
  79135. var imageData = new Uint8Array(width * height * 4);
  79136. for (y = y_start; y !== y_end; y += y_step) {
  79137. for (x = x_start; x !== x_end; x += x_step, i++) {
  79138. color = image[i];
  79139. imageData[(x + width * y) * 4 + 3] = 255;
  79140. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79141. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79142. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79143. }
  79144. }
  79145. return imageData;
  79146. };
  79147. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79148. var image = pixel_data;
  79149. var width = header.width, height = header.height;
  79150. var color, i = 0, x, y;
  79151. var imageData = new Uint8Array(width * height * 4);
  79152. for (y = y_start; y !== y_end; y += y_step) {
  79153. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79154. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79155. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79156. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79157. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79158. imageData[(x + width * y) * 4 + 0] = r;
  79159. imageData[(x + width * y) * 4 + 1] = g;
  79160. imageData[(x + width * y) * 4 + 2] = b;
  79161. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79162. }
  79163. }
  79164. return imageData;
  79165. };
  79166. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79167. var image = pixel_data;
  79168. var width = header.width, height = header.height;
  79169. var i = 0, x, y;
  79170. var imageData = new Uint8Array(width * height * 4);
  79171. for (y = y_start; y !== y_end; y += y_step) {
  79172. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79173. imageData[(x + width * y) * 4 + 3] = 255;
  79174. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79175. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79176. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79177. }
  79178. }
  79179. return imageData;
  79180. };
  79181. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79182. var image = pixel_data;
  79183. var width = header.width, height = header.height;
  79184. var i = 0, x, y;
  79185. var imageData = new Uint8Array(width * height * 4);
  79186. for (y = y_start; y !== y_end; y += y_step) {
  79187. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79188. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79189. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79190. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79191. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79192. }
  79193. }
  79194. return imageData;
  79195. };
  79196. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79197. var image = pixel_data;
  79198. var width = header.width, height = header.height;
  79199. var color, i = 0, x, y;
  79200. var imageData = new Uint8Array(width * height * 4);
  79201. for (y = y_start; y !== y_end; y += y_step) {
  79202. for (x = x_start; x !== x_end; x += x_step, i++) {
  79203. color = image[i];
  79204. imageData[(x + width * y) * 4 + 0] = color;
  79205. imageData[(x + width * y) * 4 + 1] = color;
  79206. imageData[(x + width * y) * 4 + 2] = color;
  79207. imageData[(x + width * y) * 4 + 3] = 255;
  79208. }
  79209. }
  79210. return imageData;
  79211. };
  79212. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79213. var image = pixel_data;
  79214. var width = header.width, height = header.height;
  79215. var i = 0, x, y;
  79216. var imageData = new Uint8Array(width * height * 4);
  79217. for (y = y_start; y !== y_end; y += y_step) {
  79218. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79219. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79220. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79221. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79222. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79223. }
  79224. }
  79225. return imageData;
  79226. };
  79227. //private static _TYPE_NO_DATA = 0;
  79228. TGATools._TYPE_INDEXED = 1;
  79229. TGATools._TYPE_RGB = 2;
  79230. TGATools._TYPE_GREY = 3;
  79231. TGATools._TYPE_RLE_INDEXED = 9;
  79232. TGATools._TYPE_RLE_RGB = 10;
  79233. TGATools._TYPE_RLE_GREY = 11;
  79234. TGATools._ORIGIN_MASK = 0x30;
  79235. TGATools._ORIGIN_SHIFT = 0x04;
  79236. TGATools._ORIGIN_BL = 0x00;
  79237. TGATools._ORIGIN_BR = 0x01;
  79238. TGATools._ORIGIN_UL = 0x02;
  79239. TGATools._ORIGIN_UR = 0x03;
  79240. return TGATools;
  79241. }());
  79242. BABYLON.TGATools = TGATools;
  79243. })(BABYLON || (BABYLON = {}));
  79244. //# sourceMappingURL=babylon.tga.js.map
  79245. var BABYLON;
  79246. (function (BABYLON) {
  79247. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79248. // All values and structures referenced from:
  79249. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79250. var DDS_MAGIC = 0x20534444;
  79251. var
  79252. //DDSD_CAPS = 0x1,
  79253. //DDSD_HEIGHT = 0x2,
  79254. //DDSD_WIDTH = 0x4,
  79255. //DDSD_PITCH = 0x8,
  79256. //DDSD_PIXELFORMAT = 0x1000,
  79257. DDSD_MIPMAPCOUNT = 0x20000;
  79258. //DDSD_LINEARSIZE = 0x80000,
  79259. //DDSD_DEPTH = 0x800000;
  79260. // var DDSCAPS_COMPLEX = 0x8,
  79261. // DDSCAPS_MIPMAP = 0x400000,
  79262. // DDSCAPS_TEXTURE = 0x1000;
  79263. var DDSCAPS2_CUBEMAP = 0x200;
  79264. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79265. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79266. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79267. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79268. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79269. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79270. // DDSCAPS2_VOLUME = 0x200000;
  79271. var
  79272. //DDPF_ALPHAPIXELS = 0x1,
  79273. //DDPF_ALPHA = 0x2,
  79274. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79275. //DDPF_YUV = 0x200,
  79276. DDPF_LUMINANCE = 0x20000;
  79277. function FourCCToInt32(value) {
  79278. return value.charCodeAt(0) +
  79279. (value.charCodeAt(1) << 8) +
  79280. (value.charCodeAt(2) << 16) +
  79281. (value.charCodeAt(3) << 24);
  79282. }
  79283. function Int32ToFourCC(value) {
  79284. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79285. }
  79286. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79287. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79288. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79289. var FOURCC_DX10 = FourCCToInt32("DX10");
  79290. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79291. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79292. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79293. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79294. var headerLengthInt = 31; // The header length in 32 bit ints
  79295. // Offsets into the header array
  79296. var off_magic = 0;
  79297. var off_size = 1;
  79298. var off_flags = 2;
  79299. var off_height = 3;
  79300. var off_width = 4;
  79301. var off_mipmapCount = 7;
  79302. var off_pfFlags = 20;
  79303. var off_pfFourCC = 21;
  79304. var off_RGBbpp = 22;
  79305. var off_RMask = 23;
  79306. var off_GMask = 24;
  79307. var off_BMask = 25;
  79308. var off_AMask = 26;
  79309. // var off_caps1 = 27;
  79310. var off_caps2 = 28;
  79311. // var off_caps3 = 29;
  79312. // var off_caps4 = 30;
  79313. var off_dxgiFormat = 32;
  79314. ;
  79315. var DDSTools = /** @class */ (function () {
  79316. function DDSTools() {
  79317. }
  79318. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79319. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79320. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79321. var mipmapCount = 1;
  79322. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79323. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79324. }
  79325. var fourCC = header[off_pfFourCC];
  79326. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79327. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79328. switch (fourCC) {
  79329. case FOURCC_D3DFMT_R16G16B16A16F:
  79330. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79331. break;
  79332. case FOURCC_D3DFMT_R32G32B32A32F:
  79333. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79334. break;
  79335. case FOURCC_DX10:
  79336. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79337. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79338. break;
  79339. }
  79340. }
  79341. return {
  79342. width: header[off_width],
  79343. height: header[off_height],
  79344. mipmapCount: mipmapCount,
  79345. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79346. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79347. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79348. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79349. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79350. dxgiFormat: dxgiFormat,
  79351. textureType: textureType
  79352. };
  79353. };
  79354. DDSTools._ToHalfFloat = function (value) {
  79355. if (!DDSTools._FloatView) {
  79356. DDSTools._FloatView = new Float32Array(1);
  79357. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79358. }
  79359. DDSTools._FloatView[0] = value;
  79360. var x = DDSTools._Int32View[0];
  79361. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79362. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79363. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79364. /* If zero, or denormal, or exponent underflows too much for a denormal
  79365. * half, return signed zero. */
  79366. if (e < 103) {
  79367. return bits;
  79368. }
  79369. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79370. if (e > 142) {
  79371. bits |= 0x7c00;
  79372. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79373. * not Inf, so make sure we set one mantissa bit too. */
  79374. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79375. return bits;
  79376. }
  79377. /* If exponent underflows but not too much, return a denormal */
  79378. if (e < 113) {
  79379. m |= 0x0800;
  79380. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79381. * to 1, which is OK. */
  79382. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79383. return bits;
  79384. }
  79385. bits |= ((e - 112) << 10) | (m >> 1);
  79386. bits += m & 1;
  79387. return bits;
  79388. };
  79389. DDSTools._FromHalfFloat = function (value) {
  79390. var s = (value & 0x8000) >> 15;
  79391. var e = (value & 0x7C00) >> 10;
  79392. var f = value & 0x03FF;
  79393. if (e === 0) {
  79394. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79395. }
  79396. else if (e == 0x1F) {
  79397. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79398. }
  79399. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79400. };
  79401. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79402. var destArray = new Float32Array(dataLength);
  79403. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79404. var index = 0;
  79405. for (var y = 0; y < height; y++) {
  79406. for (var x = 0; x < width; x++) {
  79407. var srcPos = (x + y * width) * 4;
  79408. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79409. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79410. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79411. if (DDSTools.StoreLODInAlphaChannel) {
  79412. destArray[index + 3] = lod;
  79413. }
  79414. else {
  79415. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79416. }
  79417. index += 4;
  79418. }
  79419. }
  79420. return destArray;
  79421. };
  79422. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79423. if (DDSTools.StoreLODInAlphaChannel) {
  79424. var destArray = new Uint16Array(dataLength);
  79425. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79426. var index = 0;
  79427. for (var y = 0; y < height; y++) {
  79428. for (var x = 0; x < width; x++) {
  79429. var srcPos = (x + y * width) * 4;
  79430. destArray[index] = srcData[srcPos];
  79431. destArray[index + 1] = srcData[srcPos + 1];
  79432. destArray[index + 2] = srcData[srcPos + 2];
  79433. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79434. index += 4;
  79435. }
  79436. }
  79437. return destArray;
  79438. }
  79439. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79440. };
  79441. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79442. if (DDSTools.StoreLODInAlphaChannel) {
  79443. var destArray = new Float32Array(dataLength);
  79444. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79445. var index = 0;
  79446. for (var y = 0; y < height; y++) {
  79447. for (var x = 0; x < width; x++) {
  79448. var srcPos = (x + y * width) * 4;
  79449. destArray[index] = srcData[srcPos];
  79450. destArray[index + 1] = srcData[srcPos + 1];
  79451. destArray[index + 2] = srcData[srcPos + 2];
  79452. destArray[index + 3] = lod;
  79453. index += 4;
  79454. }
  79455. }
  79456. return destArray;
  79457. }
  79458. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79459. };
  79460. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79461. var destArray = new Uint8Array(dataLength);
  79462. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79463. var index = 0;
  79464. for (var y = 0; y < height; y++) {
  79465. for (var x = 0; x < width; x++) {
  79466. var srcPos = (x + y * width) * 4;
  79467. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79468. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79469. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79470. if (DDSTools.StoreLODInAlphaChannel) {
  79471. destArray[index + 3] = lod;
  79472. }
  79473. else {
  79474. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79475. }
  79476. index += 4;
  79477. }
  79478. }
  79479. return destArray;
  79480. };
  79481. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79482. var destArray = new Uint8Array(dataLength);
  79483. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79484. var index = 0;
  79485. for (var y = 0; y < height; y++) {
  79486. for (var x = 0; x < width; x++) {
  79487. var srcPos = (x + y * width) * 4;
  79488. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79489. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79490. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79491. if (DDSTools.StoreLODInAlphaChannel) {
  79492. destArray[index + 3] = lod;
  79493. }
  79494. else {
  79495. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79496. }
  79497. index += 4;
  79498. }
  79499. }
  79500. return destArray;
  79501. };
  79502. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79503. var byteArray = new Uint8Array(dataLength);
  79504. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79505. var index = 0;
  79506. for (var y = 0; y < height; y++) {
  79507. for (var x = 0; x < width; x++) {
  79508. var srcPos = (x + y * width) * 4;
  79509. byteArray[index] = srcData[srcPos + rOffset];
  79510. byteArray[index + 1] = srcData[srcPos + gOffset];
  79511. byteArray[index + 2] = srcData[srcPos + bOffset];
  79512. byteArray[index + 3] = srcData[srcPos + aOffset];
  79513. index += 4;
  79514. }
  79515. }
  79516. return byteArray;
  79517. };
  79518. DDSTools._ExtractLongWordOrder = function (value) {
  79519. if (value === 0 || value === 255 || value === -16777216) {
  79520. return 0;
  79521. }
  79522. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79523. };
  79524. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79525. var byteArray = new Uint8Array(dataLength);
  79526. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79527. var index = 0;
  79528. for (var y = 0; y < height; y++) {
  79529. for (var x = 0; x < width; x++) {
  79530. var srcPos = (x + y * width) * 3;
  79531. byteArray[index] = srcData[srcPos + rOffset];
  79532. byteArray[index + 1] = srcData[srcPos + gOffset];
  79533. byteArray[index + 2] = srcData[srcPos + bOffset];
  79534. index += 3;
  79535. }
  79536. }
  79537. return byteArray;
  79538. };
  79539. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79540. var byteArray = new Uint8Array(dataLength);
  79541. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79542. var index = 0;
  79543. for (var y = 0; y < height; y++) {
  79544. for (var x = 0; x < width; x++) {
  79545. var srcPos = (x + y * width);
  79546. byteArray[index] = srcData[srcPos];
  79547. index++;
  79548. }
  79549. }
  79550. return byteArray;
  79551. };
  79552. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79553. if (lodIndex === void 0) { lodIndex = -1; }
  79554. var ext = engine.getCaps().s3tc;
  79555. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79556. var fourCC, width, height, dataLength = 0, dataOffset;
  79557. var byteArray, mipmapCount, mip;
  79558. var internalFormat = 0;
  79559. var format = 0;
  79560. var blockBytes = 1;
  79561. if (header[off_magic] !== DDS_MAGIC) {
  79562. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79563. return;
  79564. }
  79565. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79566. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79567. return;
  79568. }
  79569. if (info.isCompressed && !ext) {
  79570. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79571. return;
  79572. }
  79573. var bpp = header[off_RGBbpp];
  79574. dataOffset = header[off_size] + 4;
  79575. var computeFormats = false;
  79576. if (info.isFourCC) {
  79577. fourCC = header[off_pfFourCC];
  79578. switch (fourCC) {
  79579. case FOURCC_DXT1:
  79580. blockBytes = 8;
  79581. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79582. break;
  79583. case FOURCC_DXT3:
  79584. blockBytes = 16;
  79585. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79586. break;
  79587. case FOURCC_DXT5:
  79588. blockBytes = 16;
  79589. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79590. break;
  79591. case FOURCC_D3DFMT_R16G16B16A16F:
  79592. computeFormats = true;
  79593. break;
  79594. case FOURCC_D3DFMT_R32G32B32A32F:
  79595. computeFormats = true;
  79596. break;
  79597. case FOURCC_DX10:
  79598. // There is an additionnal header so dataOffset need to be changed
  79599. dataOffset += 5 * 4; // 5 uints
  79600. var supported = false;
  79601. switch (info.dxgiFormat) {
  79602. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79603. computeFormats = true;
  79604. supported = true;
  79605. break;
  79606. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79607. info.isRGB = true;
  79608. info.isFourCC = false;
  79609. bpp = 32;
  79610. supported = true;
  79611. break;
  79612. }
  79613. if (supported) {
  79614. break;
  79615. }
  79616. default:
  79617. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79618. return;
  79619. }
  79620. }
  79621. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79622. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79623. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79624. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79625. if (computeFormats) {
  79626. format = engine._getWebGLTextureType(info.textureType);
  79627. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79628. }
  79629. mipmapCount = 1;
  79630. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79631. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79632. }
  79633. for (var face = 0; face < faces; face++) {
  79634. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79635. width = header[off_width];
  79636. height = header[off_height];
  79637. for (mip = 0; mip < mipmapCount; ++mip) {
  79638. if (lodIndex === -1 || lodIndex === mip) {
  79639. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79640. var i = (lodIndex === -1) ? mip : 0;
  79641. if (!info.isCompressed && info.isFourCC) {
  79642. dataLength = width * height * 4;
  79643. var floatArray = null;
  79644. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79645. if (bpp === 128) {
  79646. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79647. }
  79648. else if (bpp === 64) {
  79649. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79650. }
  79651. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79652. format = engine._getWebGLTextureType(info.textureType);
  79653. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79654. }
  79655. else {
  79656. if (bpp === 128) {
  79657. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79658. }
  79659. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79660. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79661. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79662. format = engine._getWebGLTextureType(info.textureType);
  79663. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79664. }
  79665. else {
  79666. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79667. }
  79668. }
  79669. if (floatArray) {
  79670. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79671. }
  79672. }
  79673. else if (info.isRGB) {
  79674. if (bpp === 24) {
  79675. dataLength = width * height * 3;
  79676. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79677. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79678. }
  79679. else {
  79680. dataLength = width * height * 4;
  79681. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79682. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79683. }
  79684. }
  79685. else if (info.isLuminance) {
  79686. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79687. var unpaddedRowSize = width;
  79688. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79689. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79690. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79691. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79692. }
  79693. else {
  79694. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79695. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79696. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79697. }
  79698. }
  79699. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79700. width *= 0.5;
  79701. height *= 0.5;
  79702. width = Math.max(1.0, width);
  79703. height = Math.max(1.0, height);
  79704. }
  79705. if (currentFace !== undefined) {
  79706. // Loading a single face
  79707. break;
  79708. }
  79709. }
  79710. };
  79711. DDSTools.StoreLODInAlphaChannel = false;
  79712. return DDSTools;
  79713. }());
  79714. BABYLON.DDSTools = DDSTools;
  79715. })(BABYLON || (BABYLON = {}));
  79716. //# sourceMappingURL=babylon.dds.js.map
  79717. var BABYLON;
  79718. (function (BABYLON) {
  79719. /**
  79720. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79721. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79722. */
  79723. var KhronosTextureContainer = /** @class */ (function () {
  79724. /**
  79725. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79726. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79727. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79728. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79729. */
  79730. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79731. this.arrayBuffer = arrayBuffer;
  79732. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79733. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79734. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79735. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79736. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  79737. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  79738. BABYLON.Tools.Error("texture missing KTX identifier");
  79739. return;
  79740. }
  79741. // load the reset of the header in native 32 bit int
  79742. var header = new Int32Array(this.arrayBuffer, 12, 13);
  79743. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  79744. var oppositeEndianess = header[0] === 0x01020304;
  79745. // read all the header elements in order they exist in the file, without modification (sans endainness)
  79746. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  79747. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  79748. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  79749. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  79750. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  79751. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  79752. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  79753. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  79754. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79755. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79756. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79757. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79758. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79759. if (this.glType !== 0) {
  79760. BABYLON.Tools.Error("only compressed formats currently supported");
  79761. return;
  79762. }
  79763. else {
  79764. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79765. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79766. }
  79767. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79768. BABYLON.Tools.Error("only 2D textures currently supported");
  79769. return;
  79770. }
  79771. if (this.numberOfArrayElements !== 0) {
  79772. BABYLON.Tools.Error("texture arrays not currently supported");
  79773. return;
  79774. }
  79775. if (this.numberOfFaces !== facesExpected) {
  79776. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79777. return;
  79778. }
  79779. // we now have a completely validated file, so could use existence of loadType as success
  79780. // would need to make this more elaborate & adjust checks above to support more than one load type
  79781. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79782. }
  79783. // not as fast hardware based, but will probably never need to use
  79784. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79785. return ((val & 0xFF) << 24)
  79786. | ((val & 0xFF00) << 8)
  79787. | ((val >> 8) & 0xFF00)
  79788. | ((val >> 24) & 0xFF);
  79789. };
  79790. /**
  79791. * It is assumed that the texture has already been created & is currently bound
  79792. */
  79793. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79794. switch (this.loadType) {
  79795. case KhronosTextureContainer.COMPRESSED_2D:
  79796. this._upload2DCompressedLevels(gl, loadMipmaps);
  79797. break;
  79798. case KhronosTextureContainer.TEX_2D:
  79799. case KhronosTextureContainer.COMPRESSED_3D:
  79800. case KhronosTextureContainer.TEX_3D:
  79801. }
  79802. };
  79803. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  79804. // initialize width & height for level 1
  79805. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  79806. var width = this.pixelWidth;
  79807. var height = this.pixelHeight;
  79808. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  79809. for (var level = 0; level < mipmapCount; level++) {
  79810. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  79811. for (var face = 0; face < this.numberOfFaces; face++) {
  79812. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  79813. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  79814. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  79815. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  79816. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  79817. }
  79818. width = Math.max(1.0, width * 0.5);
  79819. height = Math.max(1.0, height * 0.5);
  79820. }
  79821. };
  79822. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  79823. // load types
  79824. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  79825. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  79826. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  79827. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  79828. return KhronosTextureContainer;
  79829. }());
  79830. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  79831. })(BABYLON || (BABYLON = {}));
  79832. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  79833. var BABYLON;
  79834. (function (BABYLON) {
  79835. var Debug = /** @class */ (function () {
  79836. function Debug() {
  79837. }
  79838. Debug.AxesViewer = /** @class */ (function () {
  79839. function AxesViewer(scene, scaleLines) {
  79840. if (scaleLines === void 0) { scaleLines = 1; }
  79841. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79842. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79843. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79844. this.scaleLines = 1;
  79845. this.scaleLines = scaleLines;
  79846. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  79847. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  79848. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  79849. this._xmesh.renderingGroupId = 2;
  79850. this._ymesh.renderingGroupId = 2;
  79851. this._zmesh.renderingGroupId = 2;
  79852. this._xmesh.material.checkReadyOnlyOnce = true;
  79853. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  79854. this._ymesh.material.checkReadyOnlyOnce = true;
  79855. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  79856. this._zmesh.material.checkReadyOnlyOnce = true;
  79857. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  79858. this.scene = scene;
  79859. }
  79860. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  79861. var scaleLines = this.scaleLines;
  79862. if (this._xmesh) {
  79863. this._xmesh.position.copyFrom(position);
  79864. }
  79865. if (this._ymesh) {
  79866. this._ymesh.position.copyFrom(position);
  79867. }
  79868. if (this._zmesh) {
  79869. this._zmesh.position.copyFrom(position);
  79870. }
  79871. var point2 = this._xline[1];
  79872. point2.x = xaxis.x * scaleLines;
  79873. point2.y = xaxis.y * scaleLines;
  79874. point2.z = xaxis.z * scaleLines;
  79875. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  79876. point2 = this._yline[1];
  79877. point2.x = yaxis.x * scaleLines;
  79878. point2.y = yaxis.y * scaleLines;
  79879. point2.z = yaxis.z * scaleLines;
  79880. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  79881. point2 = this._zline[1];
  79882. point2.x = zaxis.x * scaleLines;
  79883. point2.y = zaxis.y * scaleLines;
  79884. point2.z = zaxis.z * scaleLines;
  79885. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  79886. };
  79887. AxesViewer.prototype.dispose = function () {
  79888. if (this._xmesh) {
  79889. this._xmesh.dispose();
  79890. }
  79891. if (this._ymesh) {
  79892. this._ymesh.dispose();
  79893. }
  79894. if (this._zmesh) {
  79895. this._zmesh.dispose();
  79896. }
  79897. this._xmesh = null;
  79898. this._ymesh = null;
  79899. this._zmesh = null;
  79900. this.scene = null;
  79901. };
  79902. return AxesViewer;
  79903. }());
  79904. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79905. __extends(BoneAxesViewer, _super);
  79906. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79907. if (scaleLines === void 0) { scaleLines = 1; }
  79908. var _this = _super.call(this, scene, scaleLines) || this;
  79909. _this.pos = BABYLON.Vector3.Zero();
  79910. _this.xaxis = BABYLON.Vector3.Zero();
  79911. _this.yaxis = BABYLON.Vector3.Zero();
  79912. _this.zaxis = BABYLON.Vector3.Zero();
  79913. _this.mesh = mesh;
  79914. _this.bone = bone;
  79915. return _this;
  79916. }
  79917. BoneAxesViewer.prototype.update = function () {
  79918. if (!this.mesh || !this.bone) {
  79919. return;
  79920. }
  79921. var bone = this.bone;
  79922. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79923. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79924. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79925. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79926. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79927. };
  79928. BoneAxesViewer.prototype.dispose = function () {
  79929. if (this.mesh) {
  79930. this.mesh = null;
  79931. this.bone = null;
  79932. _super.prototype.dispose.call(this);
  79933. }
  79934. };
  79935. return BoneAxesViewer;
  79936. }(Debug.AxesViewer));
  79937. Debug.PhysicsViewer = /** @class */ (function () {
  79938. function PhysicsViewer(scene) {
  79939. this._impostors = [];
  79940. this._meshes = [];
  79941. this._numMeshes = 0;
  79942. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79943. var physicEngine = this._scene.getPhysicsEngine();
  79944. if (physicEngine) {
  79945. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79946. }
  79947. }
  79948. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79949. var plugin = this._physicsEnginePlugin;
  79950. for (var i = 0; i < this._numMeshes; i++) {
  79951. var impostor = this._impostors[i];
  79952. if (!impostor) {
  79953. continue;
  79954. }
  79955. if (impostor.isDisposed) {
  79956. this.hideImpostor(this._impostors[i--]);
  79957. }
  79958. else {
  79959. var mesh = this._meshes[i];
  79960. if (mesh && plugin) {
  79961. plugin.syncMeshWithImpostor(mesh, impostor);
  79962. }
  79963. }
  79964. }
  79965. };
  79966. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79967. if (!this._scene) {
  79968. return;
  79969. }
  79970. for (var i = 0; i < this._numMeshes; i++) {
  79971. if (this._impostors[i] == impostor) {
  79972. return;
  79973. }
  79974. }
  79975. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79976. if (debugMesh) {
  79977. this._impostors[this._numMeshes] = impostor;
  79978. this._meshes[this._numMeshes] = debugMesh;
  79979. if (this._numMeshes === 0) {
  79980. this._renderFunction = this._updateDebugMeshes.bind(this);
  79981. this._scene.registerBeforeRender(this._renderFunction);
  79982. }
  79983. this._numMeshes++;
  79984. }
  79985. };
  79986. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79987. if (!impostor || !this._scene) {
  79988. return;
  79989. }
  79990. var removed = false;
  79991. for (var i = 0; i < this._numMeshes; i++) {
  79992. if (this._impostors[i] == impostor) {
  79993. var mesh = this._meshes[i];
  79994. if (!mesh) {
  79995. continue;
  79996. }
  79997. this._scene.removeMesh(mesh);
  79998. mesh.dispose();
  79999. this._numMeshes--;
  80000. if (this._numMeshes > 0) {
  80001. this._meshes[i] = this._meshes[this._numMeshes];
  80002. this._impostors[i] = this._impostors[this._numMeshes];
  80003. this._meshes[this._numMeshes] = null;
  80004. this._impostors[this._numMeshes] = null;
  80005. }
  80006. else {
  80007. this._meshes[0] = null;
  80008. this._impostors[0] = null;
  80009. }
  80010. removed = true;
  80011. break;
  80012. }
  80013. }
  80014. if (removed && this._numMeshes === 0) {
  80015. this._scene.unregisterBeforeRender(this._renderFunction);
  80016. }
  80017. };
  80018. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80019. if (!this._debugMaterial) {
  80020. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80021. this._debugMaterial.wireframe = true;
  80022. }
  80023. return this._debugMaterial;
  80024. };
  80025. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80026. if (!this._debugBoxMesh) {
  80027. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80028. this._debugBoxMesh.renderingGroupId = 1;
  80029. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80030. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80031. scene.removeMesh(this._debugBoxMesh);
  80032. }
  80033. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80034. };
  80035. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80036. if (!this._debugSphereMesh) {
  80037. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80038. this._debugSphereMesh.renderingGroupId = 1;
  80039. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80040. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80041. scene.removeMesh(this._debugSphereMesh);
  80042. }
  80043. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80044. };
  80045. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80046. var mesh = null;
  80047. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80048. mesh = this._getDebugBoxMesh(scene);
  80049. impostor.getBoxSizeToRef(mesh.scaling);
  80050. }
  80051. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80052. mesh = this._getDebugSphereMesh(scene);
  80053. var radius = impostor.getRadius();
  80054. mesh.scaling.x = radius * 2;
  80055. mesh.scaling.y = radius * 2;
  80056. mesh.scaling.z = radius * 2;
  80057. }
  80058. return mesh;
  80059. };
  80060. PhysicsViewer.prototype.dispose = function () {
  80061. for (var i = 0; i < this._numMeshes; i++) {
  80062. this.hideImpostor(this._impostors[i]);
  80063. }
  80064. if (this._debugBoxMesh) {
  80065. this._debugBoxMesh.dispose();
  80066. }
  80067. if (this._debugSphereMesh) {
  80068. this._debugSphereMesh.dispose();
  80069. }
  80070. if (this._debugMaterial) {
  80071. this._debugMaterial.dispose();
  80072. }
  80073. this._impostors.length = 0;
  80074. this._scene = null;
  80075. this._physicsEnginePlugin = null;
  80076. };
  80077. return PhysicsViewer;
  80078. }());
  80079. Debug.SkeletonViewer = /** @class */ (function () {
  80080. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80081. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80082. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80083. this.skeleton = skeleton;
  80084. this.mesh = mesh;
  80085. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80086. this.renderingGroupId = renderingGroupId;
  80087. this.color = BABYLON.Color3.White();
  80088. this._debugLines = new Array();
  80089. this._isEnabled = false;
  80090. this._scene = scene;
  80091. this.update();
  80092. this._renderFunction = this.update.bind(this);
  80093. }
  80094. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80095. get: function () {
  80096. return this._isEnabled;
  80097. },
  80098. set: function (value) {
  80099. if (this._isEnabled === value) {
  80100. return;
  80101. }
  80102. this._isEnabled = value;
  80103. if (value) {
  80104. this._scene.registerBeforeRender(this._renderFunction);
  80105. }
  80106. else {
  80107. this._scene.unregisterBeforeRender(this._renderFunction);
  80108. }
  80109. },
  80110. enumerable: true,
  80111. configurable: true
  80112. });
  80113. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80114. if (x === void 0) { x = 0; }
  80115. if (y === void 0) { y = 0; }
  80116. if (z === void 0) { z = 0; }
  80117. var tmat = BABYLON.Tmp.Matrix[0];
  80118. var parentBone = bone.getParent();
  80119. tmat.copyFrom(bone.getLocalMatrix());
  80120. if (x !== 0 || y !== 0 || z !== 0) {
  80121. var tmat2 = BABYLON.Tmp.Matrix[1];
  80122. BABYLON.Matrix.IdentityToRef(tmat2);
  80123. tmat2.m[12] = x;
  80124. tmat2.m[13] = y;
  80125. tmat2.m[14] = z;
  80126. tmat2.multiplyToRef(tmat, tmat);
  80127. }
  80128. if (parentBone) {
  80129. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80130. }
  80131. tmat.multiplyToRef(meshMat, tmat);
  80132. position.x = tmat.m[12];
  80133. position.y = tmat.m[13];
  80134. position.z = tmat.m[14];
  80135. };
  80136. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80137. var len = bones.length;
  80138. var meshPos = this.mesh.position;
  80139. for (var i = 0; i < len; i++) {
  80140. var bone = bones[i];
  80141. var points = this._debugLines[i];
  80142. if (!points) {
  80143. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80144. this._debugLines[i] = points;
  80145. }
  80146. this._getBonePosition(points[0], bone, meshMat);
  80147. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80148. points[0].subtractInPlace(meshPos);
  80149. points[1].subtractInPlace(meshPos);
  80150. }
  80151. };
  80152. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80153. var len = bones.length;
  80154. var boneNum = 0;
  80155. var meshPos = this.mesh.position;
  80156. for (var i = len - 1; i >= 0; i--) {
  80157. var childBone = bones[i];
  80158. var parentBone = childBone.getParent();
  80159. if (!parentBone) {
  80160. continue;
  80161. }
  80162. var points = this._debugLines[boneNum];
  80163. if (!points) {
  80164. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80165. this._debugLines[boneNum] = points;
  80166. }
  80167. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80168. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80169. points[0].subtractInPlace(meshPos);
  80170. points[1].subtractInPlace(meshPos);
  80171. boneNum++;
  80172. }
  80173. };
  80174. SkeletonViewer.prototype.update = function () {
  80175. if (this.autoUpdateBonesMatrices) {
  80176. this.skeleton.computeAbsoluteTransforms();
  80177. }
  80178. if (this.skeleton.bones[0].length === undefined) {
  80179. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80180. }
  80181. else {
  80182. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80183. }
  80184. if (!this._debugMesh) {
  80185. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80186. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80187. }
  80188. else {
  80189. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80190. }
  80191. this._debugMesh.position.copyFrom(this.mesh.position);
  80192. this._debugMesh.color = this.color;
  80193. };
  80194. SkeletonViewer.prototype.dispose = function () {
  80195. if (this._debugMesh) {
  80196. this.isEnabled = false;
  80197. this._debugMesh.dispose();
  80198. this._debugMesh = null;
  80199. }
  80200. };
  80201. return SkeletonViewer;
  80202. }());
  80203. return Debug;
  80204. }());
  80205. BABYLON.Debug = Debug;
  80206. })(BABYLON || (BABYLON = {}));
  80207. //# sourceMappingURL=babylon.debugModules.js.map
  80208. var BABYLON;
  80209. (function (BABYLON) {
  80210. var RayHelper = /** @class */ (function () {
  80211. function RayHelper(ray) {
  80212. this.ray = ray;
  80213. }
  80214. RayHelper.CreateAndShow = function (ray, scene, color) {
  80215. var helper = new RayHelper(ray);
  80216. helper.show(scene, color);
  80217. return helper;
  80218. };
  80219. RayHelper.prototype.show = function (scene, color) {
  80220. if (!this._renderFunction && this.ray) {
  80221. var ray = this.ray;
  80222. this._renderFunction = this._render.bind(this);
  80223. this._scene = scene;
  80224. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80225. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80226. if (this._renderFunction) {
  80227. this._scene.registerBeforeRender(this._renderFunction);
  80228. }
  80229. }
  80230. if (color && this._renderLine) {
  80231. this._renderLine.color.copyFrom(color);
  80232. }
  80233. };
  80234. RayHelper.prototype.hide = function () {
  80235. if (this._renderFunction && this._scene) {
  80236. this._scene.unregisterBeforeRender(this._renderFunction);
  80237. this._scene = null;
  80238. this._renderFunction = null;
  80239. if (this._renderLine) {
  80240. this._renderLine.dispose();
  80241. this._renderLine = null;
  80242. }
  80243. this._renderPoints = [];
  80244. }
  80245. };
  80246. RayHelper.prototype._render = function () {
  80247. var ray = this.ray;
  80248. if (!ray) {
  80249. return;
  80250. }
  80251. var point = this._renderPoints[1];
  80252. var len = Math.min(ray.length, 1000000);
  80253. point.copyFrom(ray.direction);
  80254. point.scaleInPlace(len);
  80255. point.addInPlace(ray.origin);
  80256. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80257. };
  80258. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80259. this._attachedToMesh = mesh;
  80260. var ray = this.ray;
  80261. if (!ray) {
  80262. return;
  80263. }
  80264. if (!ray.direction) {
  80265. ray.direction = BABYLON.Vector3.Zero();
  80266. }
  80267. if (!ray.origin) {
  80268. ray.origin = BABYLON.Vector3.Zero();
  80269. }
  80270. if (length) {
  80271. ray.length = length;
  80272. }
  80273. if (!meshSpaceOrigin) {
  80274. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80275. }
  80276. if (!meshSpaceDirection) {
  80277. // -1 so that this will work with Mesh.lookAt
  80278. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80279. }
  80280. if (!this._meshSpaceDirection) {
  80281. this._meshSpaceDirection = meshSpaceDirection.clone();
  80282. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80283. }
  80284. else {
  80285. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80286. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80287. }
  80288. if (!this._updateToMeshFunction) {
  80289. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80290. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80291. }
  80292. this._updateToMesh();
  80293. };
  80294. RayHelper.prototype.detachFromMesh = function () {
  80295. if (this._attachedToMesh) {
  80296. if (this._updateToMeshFunction) {
  80297. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80298. }
  80299. this._attachedToMesh = null;
  80300. this._updateToMeshFunction = null;
  80301. }
  80302. };
  80303. RayHelper.prototype._updateToMesh = function () {
  80304. var ray = this.ray;
  80305. if (!this._attachedToMesh || !ray) {
  80306. return;
  80307. }
  80308. if (this._attachedToMesh._isDisposed) {
  80309. this.detachFromMesh();
  80310. return;
  80311. }
  80312. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80313. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80314. };
  80315. RayHelper.prototype.dispose = function () {
  80316. this.hide();
  80317. this.detachFromMesh();
  80318. this.ray = null;
  80319. };
  80320. return RayHelper;
  80321. }());
  80322. BABYLON.RayHelper = RayHelper;
  80323. })(BABYLON || (BABYLON = {}));
  80324. //# sourceMappingURL=babylon.rayHelper.js.map
  80325. var BABYLON;
  80326. (function (BABYLON) {
  80327. // load the inspector using require, if not present in the global namespace.
  80328. var DebugLayer = /** @class */ (function () {
  80329. function DebugLayer(scene) {
  80330. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80331. this._scene = scene;
  80332. // load inspector using require, if it doesn't exist on the global namespace.
  80333. }
  80334. /** Creates the inspector window. */
  80335. DebugLayer.prototype._createInspector = function (config) {
  80336. if (config === void 0) { config = {}; }
  80337. var popup = config.popup || false;
  80338. var initialTab = config.initialTab || 0;
  80339. var parentElement = config.parentElement || null;
  80340. if (!this._inspector) {
  80341. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80342. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80343. } // else nothing to do,; instance is already existing
  80344. };
  80345. DebugLayer.prototype.isVisible = function () {
  80346. if (!this._inspector) {
  80347. return false;
  80348. }
  80349. return true;
  80350. };
  80351. DebugLayer.prototype.hide = function () {
  80352. if (this._inspector) {
  80353. try {
  80354. this._inspector.dispose();
  80355. }
  80356. catch (e) {
  80357. // If the inspector has been removed directly from the inspector tool
  80358. }
  80359. this._inspector = null;
  80360. }
  80361. };
  80362. DebugLayer.prototype.show = function (config) {
  80363. if (config === void 0) { config = {}; }
  80364. if (typeof this.BJSINSPECTOR == 'undefined') {
  80365. // Load inspector and add it to the DOM
  80366. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80367. }
  80368. else {
  80369. // Otherwise creates the inspector
  80370. this._createInspector(config);
  80371. }
  80372. };
  80373. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80374. return DebugLayer;
  80375. }());
  80376. BABYLON.DebugLayer = DebugLayer;
  80377. })(BABYLON || (BABYLON = {}));
  80378. //# sourceMappingURL=babylon.debugLayer.js.map
  80379. var BABYLON;
  80380. (function (BABYLON) {
  80381. var BoundingBoxRenderer = /** @class */ (function () {
  80382. function BoundingBoxRenderer(scene) {
  80383. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80384. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80385. this.showBackLines = true;
  80386. this.renderList = new BABYLON.SmartArray(32);
  80387. this._vertexBuffers = {};
  80388. this._scene = scene;
  80389. }
  80390. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80391. if (this._colorShader) {
  80392. return;
  80393. }
  80394. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80395. attributes: [BABYLON.VertexBuffer.PositionKind],
  80396. uniforms: ["world", "viewProjection", "color"]
  80397. });
  80398. var engine = this._scene.getEngine();
  80399. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80400. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80401. this._createIndexBuffer();
  80402. };
  80403. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80404. var engine = this._scene.getEngine();
  80405. 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]);
  80406. };
  80407. BoundingBoxRenderer.prototype._rebuild = function () {
  80408. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80409. if (vb) {
  80410. vb._rebuild();
  80411. }
  80412. this._createIndexBuffer();
  80413. };
  80414. BoundingBoxRenderer.prototype.reset = function () {
  80415. this.renderList.reset();
  80416. };
  80417. BoundingBoxRenderer.prototype.render = function () {
  80418. if (this.renderList.length === 0) {
  80419. return;
  80420. }
  80421. this._prepareRessources();
  80422. if (!this._colorShader.isReady()) {
  80423. return;
  80424. }
  80425. var engine = this._scene.getEngine();
  80426. engine.setDepthWrite(false);
  80427. this._colorShader._preBind();
  80428. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80429. var boundingBox = this.renderList.data[boundingBoxIndex];
  80430. var min = boundingBox.minimum;
  80431. var max = boundingBox.maximum;
  80432. var diff = max.subtract(min);
  80433. var median = min.add(diff.scale(0.5));
  80434. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80435. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80436. .multiply(boundingBox.getWorldMatrix());
  80437. // VBOs
  80438. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80439. if (this.showBackLines) {
  80440. // Back
  80441. engine.setDepthFunctionToGreaterOrEqual();
  80442. this._scene.resetCachedMaterial();
  80443. this._colorShader.setColor4("color", this.backColor.toColor4());
  80444. this._colorShader.bind(worldMatrix);
  80445. // Draw order
  80446. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80447. }
  80448. // Front
  80449. engine.setDepthFunctionToLess();
  80450. this._scene.resetCachedMaterial();
  80451. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80452. this._colorShader.bind(worldMatrix);
  80453. // Draw order
  80454. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80455. }
  80456. this._colorShader.unbind();
  80457. engine.setDepthFunctionToLessOrEqual();
  80458. engine.setDepthWrite(true);
  80459. };
  80460. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80461. this._prepareRessources();
  80462. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80463. return;
  80464. }
  80465. var engine = this._scene.getEngine();
  80466. engine.setDepthWrite(false);
  80467. engine.setColorWrite(false);
  80468. this._colorShader._preBind();
  80469. var boundingBox = mesh._boundingInfo.boundingBox;
  80470. var min = boundingBox.minimum;
  80471. var max = boundingBox.maximum;
  80472. var diff = max.subtract(min);
  80473. var median = min.add(diff.scale(0.5));
  80474. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80475. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80476. .multiply(boundingBox.getWorldMatrix());
  80477. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80478. engine.setDepthFunctionToLess();
  80479. this._scene.resetCachedMaterial();
  80480. this._colorShader.bind(worldMatrix);
  80481. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80482. this._colorShader.unbind();
  80483. engine.setDepthFunctionToLessOrEqual();
  80484. engine.setDepthWrite(true);
  80485. engine.setColorWrite(true);
  80486. };
  80487. BoundingBoxRenderer.prototype.dispose = function () {
  80488. if (!this._colorShader) {
  80489. return;
  80490. }
  80491. this.renderList.dispose();
  80492. this._colorShader.dispose();
  80493. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80494. if (buffer) {
  80495. buffer.dispose();
  80496. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80497. }
  80498. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80499. };
  80500. return BoundingBoxRenderer;
  80501. }());
  80502. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80503. })(BABYLON || (BABYLON = {}));
  80504. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80505. var BABYLON;
  80506. (function (BABYLON) {
  80507. var MorphTarget = /** @class */ (function () {
  80508. function MorphTarget(name, influence) {
  80509. if (influence === void 0) { influence = 0; }
  80510. this.name = name;
  80511. this.animations = new Array();
  80512. this._positions = null;
  80513. this._normals = null;
  80514. this._tangents = null;
  80515. this.onInfluenceChanged = new BABYLON.Observable();
  80516. this.influence = influence;
  80517. }
  80518. Object.defineProperty(MorphTarget.prototype, "influence", {
  80519. get: function () {
  80520. return this._influence;
  80521. },
  80522. set: function (influence) {
  80523. if (this._influence === influence) {
  80524. return;
  80525. }
  80526. var previous = this._influence;
  80527. this._influence = influence;
  80528. if (this.onInfluenceChanged.hasObservers) {
  80529. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80530. }
  80531. },
  80532. enumerable: true,
  80533. configurable: true
  80534. });
  80535. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80536. get: function () {
  80537. return !!this._positions;
  80538. },
  80539. enumerable: true,
  80540. configurable: true
  80541. });
  80542. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80543. get: function () {
  80544. return !!this._normals;
  80545. },
  80546. enumerable: true,
  80547. configurable: true
  80548. });
  80549. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80550. get: function () {
  80551. return !!this._tangents;
  80552. },
  80553. enumerable: true,
  80554. configurable: true
  80555. });
  80556. MorphTarget.prototype.setPositions = function (data) {
  80557. this._positions = data;
  80558. };
  80559. MorphTarget.prototype.getPositions = function () {
  80560. return this._positions;
  80561. };
  80562. MorphTarget.prototype.setNormals = function (data) {
  80563. this._normals = data;
  80564. };
  80565. MorphTarget.prototype.getNormals = function () {
  80566. return this._normals;
  80567. };
  80568. MorphTarget.prototype.setTangents = function (data) {
  80569. this._tangents = data;
  80570. };
  80571. MorphTarget.prototype.getTangents = function () {
  80572. return this._tangents;
  80573. };
  80574. /**
  80575. * Serializes the current target into a Serialization object.
  80576. * Returns the serialized object.
  80577. */
  80578. MorphTarget.prototype.serialize = function () {
  80579. var serializationObject = {};
  80580. serializationObject.name = this.name;
  80581. serializationObject.influence = this.influence;
  80582. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80583. if (this.hasNormals) {
  80584. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80585. }
  80586. if (this.hasTangents) {
  80587. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80588. }
  80589. // Animations
  80590. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80591. return serializationObject;
  80592. };
  80593. // Statics
  80594. MorphTarget.Parse = function (serializationObject) {
  80595. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80596. result.setPositions(serializationObject.positions);
  80597. if (serializationObject.normals) {
  80598. result.setNormals(serializationObject.normals);
  80599. }
  80600. if (serializationObject.tangents) {
  80601. result.setTangents(serializationObject.tangents);
  80602. }
  80603. // Animations
  80604. if (serializationObject.animations) {
  80605. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80606. var parsedAnimation = serializationObject.animations[animationIndex];
  80607. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80608. }
  80609. }
  80610. return result;
  80611. };
  80612. MorphTarget.FromMesh = function (mesh, name, influence) {
  80613. if (!name) {
  80614. name = mesh.name;
  80615. }
  80616. var result = new MorphTarget(name, influence);
  80617. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80618. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80619. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80620. }
  80621. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80622. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80623. }
  80624. return result;
  80625. };
  80626. return MorphTarget;
  80627. }());
  80628. BABYLON.MorphTarget = MorphTarget;
  80629. })(BABYLON || (BABYLON = {}));
  80630. //# sourceMappingURL=babylon.morphTarget.js.map
  80631. var BABYLON;
  80632. (function (BABYLON) {
  80633. var MorphTargetManager = /** @class */ (function () {
  80634. function MorphTargetManager(scene) {
  80635. if (scene === void 0) { scene = null; }
  80636. this._targets = new Array();
  80637. this._targetObservable = new Array();
  80638. this._activeTargets = new BABYLON.SmartArray(16);
  80639. this._supportsNormals = false;
  80640. this._supportsTangents = false;
  80641. this._vertexCount = 0;
  80642. this._uniqueId = 0;
  80643. this._tempInfluences = new Array();
  80644. if (!scene) {
  80645. scene = BABYLON.Engine.LastCreatedScene;
  80646. }
  80647. this._scene = scene;
  80648. if (this._scene) {
  80649. this._scene.morphTargetManagers.push(this);
  80650. this._uniqueId = this._scene.getUniqueId();
  80651. }
  80652. }
  80653. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80654. get: function () {
  80655. return this._uniqueId;
  80656. },
  80657. enumerable: true,
  80658. configurable: true
  80659. });
  80660. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80661. get: function () {
  80662. return this._vertexCount;
  80663. },
  80664. enumerable: true,
  80665. configurable: true
  80666. });
  80667. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80668. get: function () {
  80669. return this._supportsNormals;
  80670. },
  80671. enumerable: true,
  80672. configurable: true
  80673. });
  80674. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80675. get: function () {
  80676. return this._supportsTangents;
  80677. },
  80678. enumerable: true,
  80679. configurable: true
  80680. });
  80681. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80682. get: function () {
  80683. return this._targets.length;
  80684. },
  80685. enumerable: true,
  80686. configurable: true
  80687. });
  80688. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80689. get: function () {
  80690. return this._activeTargets.length;
  80691. },
  80692. enumerable: true,
  80693. configurable: true
  80694. });
  80695. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80696. get: function () {
  80697. return this._influences;
  80698. },
  80699. enumerable: true,
  80700. configurable: true
  80701. });
  80702. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80703. return this._activeTargets.data[index];
  80704. };
  80705. MorphTargetManager.prototype.getTarget = function (index) {
  80706. return this._targets[index];
  80707. };
  80708. MorphTargetManager.prototype.addTarget = function (target) {
  80709. var _this = this;
  80710. this._targets.push(target);
  80711. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80712. _this._syncActiveTargets(needUpdate);
  80713. }));
  80714. this._syncActiveTargets(true);
  80715. };
  80716. MorphTargetManager.prototype.removeTarget = function (target) {
  80717. var index = this._targets.indexOf(target);
  80718. if (index >= 0) {
  80719. this._targets.splice(index, 1);
  80720. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80721. this._syncActiveTargets(true);
  80722. }
  80723. };
  80724. /**
  80725. * Serializes the current manager into a Serialization object.
  80726. * Returns the serialized object.
  80727. */
  80728. MorphTargetManager.prototype.serialize = function () {
  80729. var serializationObject = {};
  80730. serializationObject.id = this.uniqueId;
  80731. serializationObject.targets = [];
  80732. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80733. var target = _a[_i];
  80734. serializationObject.targets.push(target.serialize());
  80735. }
  80736. return serializationObject;
  80737. };
  80738. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  80739. var influenceCount = 0;
  80740. this._activeTargets.reset();
  80741. this._supportsNormals = true;
  80742. this._supportsTangents = true;
  80743. this._vertexCount = 0;
  80744. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80745. var target = _a[_i];
  80746. this._activeTargets.push(target);
  80747. this._tempInfluences[influenceCount++] = target.influence;
  80748. var positions = target.getPositions();
  80749. if (positions) {
  80750. this._supportsNormals = this._supportsNormals && target.hasNormals;
  80751. this._supportsTangents = this._supportsTangents && target.hasTangents;
  80752. var vertexCount = positions.length / 3;
  80753. if (this._vertexCount === 0) {
  80754. this._vertexCount = vertexCount;
  80755. }
  80756. else if (this._vertexCount !== vertexCount) {
  80757. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80758. return;
  80759. }
  80760. }
  80761. }
  80762. if (!this._influences || this._influences.length !== influenceCount) {
  80763. this._influences = new Float32Array(influenceCount);
  80764. }
  80765. for (var index = 0; index < influenceCount; index++) {
  80766. this._influences[index] = this._tempInfluences[index];
  80767. }
  80768. if (needUpdate && this._scene) {
  80769. // Flag meshes as dirty to resync with the active targets
  80770. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80771. var mesh = _c[_b];
  80772. if (mesh.morphTargetManager === this) {
  80773. mesh._syncGeometryWithMorphTargetManager();
  80774. }
  80775. }
  80776. }
  80777. };
  80778. // Statics
  80779. MorphTargetManager.Parse = function (serializationObject, scene) {
  80780. var result = new MorphTargetManager(scene);
  80781. result._uniqueId = serializationObject.id;
  80782. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80783. var targetData = _a[_i];
  80784. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80785. }
  80786. return result;
  80787. };
  80788. return MorphTargetManager;
  80789. }());
  80790. BABYLON.MorphTargetManager = MorphTargetManager;
  80791. })(BABYLON || (BABYLON = {}));
  80792. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80793. var BABYLON;
  80794. (function (BABYLON) {
  80795. var Octree = /** @class */ (function () {
  80796. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  80797. if (maxDepth === void 0) { maxDepth = 2; }
  80798. this.maxDepth = maxDepth;
  80799. this.dynamicContent = new Array();
  80800. this._maxBlockCapacity = maxBlockCapacity || 64;
  80801. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  80802. this._creationFunc = creationFunc;
  80803. }
  80804. // Methods
  80805. Octree.prototype.update = function (worldMin, worldMax, entries) {
  80806. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  80807. };
  80808. Octree.prototype.addMesh = function (entry) {
  80809. for (var index = 0; index < this.blocks.length; index++) {
  80810. var block = this.blocks[index];
  80811. block.addEntry(entry);
  80812. }
  80813. };
  80814. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  80815. this._selectionContent.reset();
  80816. for (var index = 0; index < this.blocks.length; index++) {
  80817. var block = this.blocks[index];
  80818. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  80819. }
  80820. if (allowDuplicate) {
  80821. this._selectionContent.concat(this.dynamicContent);
  80822. }
  80823. else {
  80824. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80825. }
  80826. return this._selectionContent;
  80827. };
  80828. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  80829. this._selectionContent.reset();
  80830. for (var index = 0; index < this.blocks.length; index++) {
  80831. var block = this.blocks[index];
  80832. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  80833. }
  80834. if (allowDuplicate) {
  80835. this._selectionContent.concat(this.dynamicContent);
  80836. }
  80837. else {
  80838. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80839. }
  80840. return this._selectionContent;
  80841. };
  80842. Octree.prototype.intersectsRay = function (ray) {
  80843. this._selectionContent.reset();
  80844. for (var index = 0; index < this.blocks.length; index++) {
  80845. var block = this.blocks[index];
  80846. block.intersectsRay(ray, this._selectionContent);
  80847. }
  80848. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80849. return this._selectionContent;
  80850. };
  80851. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  80852. target.blocks = new Array();
  80853. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  80854. // Segmenting space
  80855. for (var x = 0; x < 2; x++) {
  80856. for (var y = 0; y < 2; y++) {
  80857. for (var z = 0; z < 2; z++) {
  80858. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  80859. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  80860. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  80861. block.addEntries(entries);
  80862. target.blocks.push(block);
  80863. }
  80864. }
  80865. }
  80866. };
  80867. Octree.CreationFuncForMeshes = function (entry, block) {
  80868. var boundingInfo = entry.getBoundingInfo();
  80869. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80870. block.entries.push(entry);
  80871. }
  80872. };
  80873. Octree.CreationFuncForSubMeshes = function (entry, block) {
  80874. var boundingInfo = entry.getBoundingInfo();
  80875. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80876. block.entries.push(entry);
  80877. }
  80878. };
  80879. return Octree;
  80880. }());
  80881. BABYLON.Octree = Octree;
  80882. })(BABYLON || (BABYLON = {}));
  80883. //# sourceMappingURL=babylon.octree.js.map
  80884. var BABYLON;
  80885. (function (BABYLON) {
  80886. var OctreeBlock = /** @class */ (function () {
  80887. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  80888. this.entries = new Array();
  80889. this._boundingVectors = new Array();
  80890. this._capacity = capacity;
  80891. this._depth = depth;
  80892. this._maxDepth = maxDepth;
  80893. this._creationFunc = creationFunc;
  80894. this._minPoint = minPoint;
  80895. this._maxPoint = maxPoint;
  80896. this._boundingVectors.push(minPoint.clone());
  80897. this._boundingVectors.push(maxPoint.clone());
  80898. this._boundingVectors.push(minPoint.clone());
  80899. this._boundingVectors[2].x = maxPoint.x;
  80900. this._boundingVectors.push(minPoint.clone());
  80901. this._boundingVectors[3].y = maxPoint.y;
  80902. this._boundingVectors.push(minPoint.clone());
  80903. this._boundingVectors[4].z = maxPoint.z;
  80904. this._boundingVectors.push(maxPoint.clone());
  80905. this._boundingVectors[5].z = minPoint.z;
  80906. this._boundingVectors.push(maxPoint.clone());
  80907. this._boundingVectors[6].x = minPoint.x;
  80908. this._boundingVectors.push(maxPoint.clone());
  80909. this._boundingVectors[7].y = minPoint.y;
  80910. }
  80911. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80912. // Property
  80913. get: function () {
  80914. return this._capacity;
  80915. },
  80916. enumerable: true,
  80917. configurable: true
  80918. });
  80919. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80920. get: function () {
  80921. return this._minPoint;
  80922. },
  80923. enumerable: true,
  80924. configurable: true
  80925. });
  80926. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80927. get: function () {
  80928. return this._maxPoint;
  80929. },
  80930. enumerable: true,
  80931. configurable: true
  80932. });
  80933. // Methods
  80934. OctreeBlock.prototype.addEntry = function (entry) {
  80935. if (this.blocks) {
  80936. for (var index = 0; index < this.blocks.length; index++) {
  80937. var block = this.blocks[index];
  80938. block.addEntry(entry);
  80939. }
  80940. return;
  80941. }
  80942. this._creationFunc(entry, this);
  80943. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80944. this.createInnerBlocks();
  80945. }
  80946. };
  80947. OctreeBlock.prototype.addEntries = function (entries) {
  80948. for (var index = 0; index < entries.length; index++) {
  80949. var mesh = entries[index];
  80950. this.addEntry(mesh);
  80951. }
  80952. };
  80953. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80954. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80955. if (this.blocks) {
  80956. for (var index = 0; index < this.blocks.length; index++) {
  80957. var block = this.blocks[index];
  80958. block.select(frustumPlanes, selection, allowDuplicate);
  80959. }
  80960. return;
  80961. }
  80962. if (allowDuplicate) {
  80963. selection.concat(this.entries);
  80964. }
  80965. else {
  80966. selection.concatWithNoDuplicate(this.entries);
  80967. }
  80968. }
  80969. };
  80970. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80971. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80972. if (this.blocks) {
  80973. for (var index = 0; index < this.blocks.length; index++) {
  80974. var block = this.blocks[index];
  80975. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80976. }
  80977. return;
  80978. }
  80979. if (allowDuplicate) {
  80980. selection.concat(this.entries);
  80981. }
  80982. else {
  80983. selection.concatWithNoDuplicate(this.entries);
  80984. }
  80985. }
  80986. };
  80987. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80988. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80989. if (this.blocks) {
  80990. for (var index = 0; index < this.blocks.length; index++) {
  80991. var block = this.blocks[index];
  80992. block.intersectsRay(ray, selection);
  80993. }
  80994. return;
  80995. }
  80996. selection.concatWithNoDuplicate(this.entries);
  80997. }
  80998. };
  80999. OctreeBlock.prototype.createInnerBlocks = function () {
  81000. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81001. };
  81002. return OctreeBlock;
  81003. }());
  81004. BABYLON.OctreeBlock = OctreeBlock;
  81005. })(BABYLON || (BABYLON = {}));
  81006. //# sourceMappingURL=babylon.octreeBlock.js.map
  81007. var BABYLON;
  81008. (function (BABYLON) {
  81009. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81010. __extends(VRDistortionCorrectionPostProcess, _super);
  81011. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81012. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81013. 'LensCenter',
  81014. 'Scale',
  81015. 'ScaleIn',
  81016. 'HmdWarpParam'
  81017. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81018. _this._isRightEye = isRightEye;
  81019. _this._distortionFactors = vrMetrics.distortionK;
  81020. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81021. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81022. _this.adaptScaleToCurrentViewport = true;
  81023. _this.onSizeChangedObservable.add(function () {
  81024. _this.aspectRatio = _this.width * .5 / _this.height;
  81025. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81026. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81027. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81028. });
  81029. _this.onApplyObservable.add(function (effect) {
  81030. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81031. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81032. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81033. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81034. });
  81035. return _this;
  81036. }
  81037. return VRDistortionCorrectionPostProcess;
  81038. }(BABYLON.PostProcess));
  81039. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81040. })(BABYLON || (BABYLON = {}));
  81041. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81042. var BABYLON;
  81043. (function (BABYLON) {
  81044. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81045. __extends(AnaglyphPostProcess, _super);
  81046. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81047. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81048. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81049. _this.onApplyObservable.add(function (effect) {
  81050. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81051. });
  81052. return _this;
  81053. }
  81054. return AnaglyphPostProcess;
  81055. }(BABYLON.PostProcess));
  81056. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81057. })(BABYLON || (BABYLON = {}));
  81058. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81059. var BABYLON;
  81060. (function (BABYLON) {
  81061. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81062. __extends(StereoscopicInterlacePostProcess, _super);
  81063. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81064. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81065. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81066. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81067. _this.onSizeChangedObservable.add(function () {
  81068. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81069. });
  81070. _this.onApplyObservable.add(function (effect) {
  81071. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81072. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81073. });
  81074. return _this;
  81075. }
  81076. return StereoscopicInterlacePostProcess;
  81077. }(BABYLON.PostProcess));
  81078. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81079. })(BABYLON || (BABYLON = {}));
  81080. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81081. var BABYLON;
  81082. (function (BABYLON) {
  81083. /**
  81084. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81085. * Screen rotation is taken into account.
  81086. */
  81087. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81088. function FreeCameraDeviceOrientationInput() {
  81089. var _this = this;
  81090. this._screenOrientationAngle = 0;
  81091. this._screenQuaternion = new BABYLON.Quaternion();
  81092. this._alpha = 0;
  81093. this._beta = 0;
  81094. this._gamma = 0;
  81095. this._orientationChanged = function () {
  81096. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81097. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81098. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81099. };
  81100. this._deviceOrientation = function (evt) {
  81101. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81102. _this._beta = evt.beta !== null ? evt.beta : 0;
  81103. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81104. };
  81105. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81106. this._orientationChanged();
  81107. }
  81108. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81109. get: function () {
  81110. return this._camera;
  81111. },
  81112. set: function (camera) {
  81113. this._camera = camera;
  81114. if (this._camera != null && !this._camera.rotationQuaternion) {
  81115. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81116. }
  81117. },
  81118. enumerable: true,
  81119. configurable: true
  81120. });
  81121. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81122. window.addEventListener("orientationchange", this._orientationChanged);
  81123. window.addEventListener("deviceorientation", this._deviceOrientation);
  81124. //In certain cases, the attach control is called AFTER orientation was changed,
  81125. //So this is needed.
  81126. this._orientationChanged();
  81127. };
  81128. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81129. window.removeEventListener("orientationchange", this._orientationChanged);
  81130. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81131. };
  81132. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81133. //if no device orientation provided, don't update the rotation.
  81134. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81135. if (!this._alpha)
  81136. return;
  81137. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81138. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81139. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81140. //Mirror on XY Plane
  81141. this._camera.rotationQuaternion.z *= -1;
  81142. this._camera.rotationQuaternion.w *= -1;
  81143. };
  81144. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81145. return "FreeCameraDeviceOrientationInput";
  81146. };
  81147. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81148. return "deviceOrientation";
  81149. };
  81150. return FreeCameraDeviceOrientationInput;
  81151. }());
  81152. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81153. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81154. })(BABYLON || (BABYLON = {}));
  81155. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81156. var BABYLON;
  81157. (function (BABYLON) {
  81158. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81159. function ArcRotateCameraVRDeviceOrientationInput() {
  81160. this.alphaCorrection = 1;
  81161. this.betaCorrection = 1;
  81162. this.gammaCorrection = 1;
  81163. this._alpha = 0;
  81164. this._gamma = 0;
  81165. this._dirty = false;
  81166. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81167. }
  81168. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81169. this.camera.attachControl(element, noPreventDefault);
  81170. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81171. };
  81172. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81173. if (evt.alpha !== null) {
  81174. this._alpha = +evt.alpha | 0;
  81175. }
  81176. if (evt.gamma !== null) {
  81177. this._gamma = +evt.gamma | 0;
  81178. }
  81179. this._dirty = true;
  81180. };
  81181. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81182. if (this._dirty) {
  81183. this._dirty = false;
  81184. if (this._gamma < 0) {
  81185. this._gamma = 180 + this._gamma;
  81186. }
  81187. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81188. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81189. }
  81190. };
  81191. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81192. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81193. };
  81194. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81195. return "ArcRotateCameraVRDeviceOrientationInput";
  81196. };
  81197. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81198. return "VRDeviceOrientation";
  81199. };
  81200. return ArcRotateCameraVRDeviceOrientationInput;
  81201. }());
  81202. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81203. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81204. })(BABYLON || (BABYLON = {}));
  81205. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81206. var BABYLON;
  81207. (function (BABYLON) {
  81208. var VRCameraMetrics = /** @class */ (function () {
  81209. function VRCameraMetrics() {
  81210. this.compensateDistortion = true;
  81211. }
  81212. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81213. get: function () {
  81214. return this.hResolution / (2 * this.vResolution);
  81215. },
  81216. enumerable: true,
  81217. configurable: true
  81218. });
  81219. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81220. get: function () {
  81221. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81222. },
  81223. enumerable: true,
  81224. configurable: true
  81225. });
  81226. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81227. get: function () {
  81228. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81229. var h = (4 * meters) / this.hScreenSize;
  81230. return BABYLON.Matrix.Translation(h, 0, 0);
  81231. },
  81232. enumerable: true,
  81233. configurable: true
  81234. });
  81235. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81236. get: function () {
  81237. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81238. var h = (4 * meters) / this.hScreenSize;
  81239. return BABYLON.Matrix.Translation(-h, 0, 0);
  81240. },
  81241. enumerable: true,
  81242. configurable: true
  81243. });
  81244. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81245. get: function () {
  81246. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81247. },
  81248. enumerable: true,
  81249. configurable: true
  81250. });
  81251. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81252. get: function () {
  81253. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81254. },
  81255. enumerable: true,
  81256. configurable: true
  81257. });
  81258. VRCameraMetrics.GetDefault = function () {
  81259. var result = new VRCameraMetrics();
  81260. result.hResolution = 1280;
  81261. result.vResolution = 800;
  81262. result.hScreenSize = 0.149759993;
  81263. result.vScreenSize = 0.0935999975;
  81264. result.vScreenCenter = 0.0467999987;
  81265. result.eyeToScreenDistance = 0.0410000011;
  81266. result.lensSeparationDistance = 0.0635000020;
  81267. result.interpupillaryDistance = 0.0640000030;
  81268. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81269. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81270. result.postProcessScaleFactor = 1.714605507808412;
  81271. result.lensCenterOffset = 0.151976421;
  81272. return result;
  81273. };
  81274. return VRCameraMetrics;
  81275. }());
  81276. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81277. })(BABYLON || (BABYLON = {}));
  81278. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81279. var BABYLON;
  81280. (function (BABYLON) {
  81281. /**
  81282. * This represents a WebVR camera.
  81283. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81284. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81285. */
  81286. var WebVRFreeCamera = /** @class */ (function (_super) {
  81287. __extends(WebVRFreeCamera, _super);
  81288. /**
  81289. * Instantiates a WebVRFreeCamera.
  81290. * @param name The name of the WebVRFreeCamera
  81291. * @param position The starting anchor position for the camera
  81292. * @param scene The scene the camera belongs to
  81293. * @param webVROptions a set of customizable options for the webVRCamera
  81294. */
  81295. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81296. if (webVROptions === void 0) { webVROptions = {}; }
  81297. var _this = _super.call(this, name, position, scene) || this;
  81298. _this.webVROptions = webVROptions;
  81299. /**
  81300. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81301. */
  81302. _this._vrDevice = null;
  81303. /**
  81304. * The rawPose of the vrDevice.
  81305. */
  81306. _this.rawPose = null;
  81307. _this._specsVersion = "1.1";
  81308. _this._attached = false;
  81309. _this._descendants = [];
  81310. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81311. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81312. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81313. _this._standingMatrix = null;
  81314. /**
  81315. * Represents device position in babylon space.
  81316. */
  81317. _this.devicePosition = BABYLON.Vector3.Zero();
  81318. /**
  81319. * Represents device rotation in babylon space.
  81320. */
  81321. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81322. /**
  81323. * The scale of the device to be used when translating from device space to babylon space.
  81324. */
  81325. _this.deviceScaleFactor = 1;
  81326. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81327. _this._worldToDevice = BABYLON.Matrix.Identity();
  81328. /**
  81329. * References to the webVR controllers for the vrDevice.
  81330. */
  81331. _this.controllers = [];
  81332. /**
  81333. * Emits an event when a controller is attached.
  81334. */
  81335. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81336. /**
  81337. * Emits an event when a controller's mesh has been loaded;
  81338. */
  81339. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81340. /**
  81341. * If the rig cameras be used as parent instead of this camera.
  81342. */
  81343. _this.rigParenting = true;
  81344. _this._defaultHeight = undefined;
  81345. _this._workingVector = BABYLON.Vector3.Zero();
  81346. _this._oneVector = BABYLON.Vector3.One();
  81347. _this._workingMatrix = BABYLON.Matrix.Identity();
  81348. _this._cache.position = BABYLON.Vector3.Zero();
  81349. if (webVROptions.defaultHeight) {
  81350. _this._defaultHeight = webVROptions.defaultHeight;
  81351. _this.position.y = _this._defaultHeight;
  81352. }
  81353. _this.minZ = 0.1;
  81354. //legacy support - the compensation boolean was removed.
  81355. if (arguments.length === 5) {
  81356. _this.webVROptions = arguments[4];
  81357. }
  81358. // default webVR options
  81359. if (_this.webVROptions.trackPosition == undefined) {
  81360. _this.webVROptions.trackPosition = true;
  81361. }
  81362. if (_this.webVROptions.controllerMeshes == undefined) {
  81363. _this.webVROptions.controllerMeshes = true;
  81364. }
  81365. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81366. _this.webVROptions.defaultLightingOnControllers = true;
  81367. }
  81368. _this.rotationQuaternion = new BABYLON.Quaternion();
  81369. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81370. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81371. }
  81372. //enable VR
  81373. var engine = _this.getEngine();
  81374. _this._onVREnabled = function (success) { if (success) {
  81375. _this.initControllers();
  81376. } };
  81377. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81378. engine.initWebVR().add(function (event) {
  81379. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81380. return;
  81381. }
  81382. _this._vrDevice = event.vrDisplay;
  81383. //reset the rig parameters.
  81384. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81385. if (_this._attached) {
  81386. _this.getEngine().enableVR();
  81387. }
  81388. });
  81389. if (typeof (VRFrameData) !== "undefined")
  81390. _this._frameData = new VRFrameData();
  81391. /**
  81392. * The idea behind the following lines:
  81393. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81394. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81395. * the second will not show it correctly.
  81396. *
  81397. * To solve this - each object that has the camera as parent will be added to a protected array.
  81398. * When the rig camera renders, it will take this array and set all of those to be its children.
  81399. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81400. * Amazing!
  81401. */
  81402. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81403. if (camera.parent === _this && _this.rigParenting) {
  81404. _this._descendants = _this.getDescendants(true, function (n) {
  81405. // don't take the cameras or the controllers!
  81406. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81407. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81408. return !isController && !isRigCamera;
  81409. });
  81410. _this._descendants.forEach(function (node) {
  81411. node.parent = camera;
  81412. });
  81413. }
  81414. });
  81415. scene.onAfterCameraRenderObservable.add(function (camera) {
  81416. if (camera.parent === _this && _this.rigParenting) {
  81417. _this._descendants.forEach(function (node) {
  81418. node.parent = _this;
  81419. });
  81420. }
  81421. });
  81422. return _this;
  81423. }
  81424. /**
  81425. * Gets the device distance from the ground in meters.
  81426. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  81427. */
  81428. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81429. if (this._standingMatrix) {
  81430. // Add standing matrix offset to get real offset from ground in room
  81431. this._standingMatrix.getTranslationToRef(this._workingVector);
  81432. return this._deviceRoomPosition.y + this._workingVector.y;
  81433. }
  81434. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81435. return this._defaultHeight || 0;
  81436. };
  81437. /**
  81438. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81439. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81440. */
  81441. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81442. var _this = this;
  81443. if (callback === void 0) { callback = function (bool) { }; }
  81444. // Use standing matrix if available
  81445. this.getEngine().initWebVRAsync().then(function (result) {
  81446. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81447. callback(false);
  81448. }
  81449. else {
  81450. _this._standingMatrix = new BABYLON.Matrix();
  81451. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81452. if (!_this.getScene().useRightHandedSystem) {
  81453. [2, 6, 8, 9, 14].forEach(function (num) {
  81454. if (_this._standingMatrix) {
  81455. _this._standingMatrix.m[num] *= -1;
  81456. }
  81457. });
  81458. }
  81459. callback(true);
  81460. }
  81461. });
  81462. };
  81463. /**
  81464. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81465. * @returns A promise with a boolean set to if the standing matrix is supported.
  81466. */
  81467. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81468. var _this = this;
  81469. return new Promise(function (res, rej) {
  81470. _this.useStandingMatrix(function (supported) {
  81471. res(supported);
  81472. });
  81473. });
  81474. };
  81475. /**
  81476. * Disposes the camera
  81477. */
  81478. WebVRFreeCamera.prototype.dispose = function () {
  81479. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81480. _super.prototype.dispose.call(this);
  81481. };
  81482. /**
  81483. * Gets a vrController by name.
  81484. * @param name The name of the controller to retreive
  81485. * @returns the controller matching the name specified or null if not found
  81486. */
  81487. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81488. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81489. var gp = _a[_i];
  81490. if (gp.hand === name) {
  81491. return gp;
  81492. }
  81493. }
  81494. return null;
  81495. };
  81496. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81497. /**
  81498. * The controller corrisponding to the users left hand.
  81499. */
  81500. get: function () {
  81501. if (!this._leftController) {
  81502. this._leftController = this.getControllerByName("left");
  81503. }
  81504. return this._leftController;
  81505. },
  81506. enumerable: true,
  81507. configurable: true
  81508. });
  81509. ;
  81510. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81511. /**
  81512. * The controller corrisponding to the users right hand.
  81513. */
  81514. get: function () {
  81515. if (!this._rightController) {
  81516. this._rightController = this.getControllerByName("right");
  81517. }
  81518. return this._rightController;
  81519. },
  81520. enumerable: true,
  81521. configurable: true
  81522. });
  81523. ;
  81524. /**
  81525. * Casts a ray forward from the vrCamera's gaze.
  81526. * @param length Length of the ray (default: 100)
  81527. * @returns the ray corrisponding to the gaze
  81528. */
  81529. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81530. if (length === void 0) { length = 100; }
  81531. if (this.leftCamera) {
  81532. // Use left eye to avoid computation to compute center on every call
  81533. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81534. }
  81535. else {
  81536. return _super.prototype.getForwardRay.call(this, length);
  81537. }
  81538. };
  81539. /**
  81540. * Updates the camera based on device's frame data
  81541. */
  81542. WebVRFreeCamera.prototype._checkInputs = function () {
  81543. if (this._vrDevice && this._vrDevice.isPresenting) {
  81544. this._vrDevice.getFrameData(this._frameData);
  81545. this.updateFromDevice(this._frameData.pose);
  81546. }
  81547. _super.prototype._checkInputs.call(this);
  81548. };
  81549. /**
  81550. * Updates the poseControlled values based on the input device pose.
  81551. * @param poseData Pose coming from the device
  81552. */
  81553. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81554. if (poseData && poseData.orientation) {
  81555. this.rawPose = poseData;
  81556. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81557. if (this.getScene().useRightHandedSystem) {
  81558. this._deviceRoomRotationQuaternion.z *= -1;
  81559. this._deviceRoomRotationQuaternion.w *= -1;
  81560. }
  81561. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81562. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81563. if (this.getScene().useRightHandedSystem) {
  81564. this._deviceRoomPosition.z *= -1;
  81565. }
  81566. }
  81567. }
  81568. };
  81569. /**
  81570. * WebVR's attach control will start broadcasting frames to the device.
  81571. * Note that in certain browsers (chrome for example) this function must be called
  81572. * within a user-interaction callback. Example:
  81573. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81574. *
  81575. * @param element html element to attach the vrDevice to
  81576. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81577. */
  81578. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81579. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81580. this._attached = true;
  81581. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81582. if (this._vrDevice) {
  81583. this.getEngine().enableVR();
  81584. }
  81585. };
  81586. /**
  81587. * Detaches the camera from the html element and disables VR
  81588. *
  81589. * @param element html element to detach from
  81590. */
  81591. WebVRFreeCamera.prototype.detachControl = function (element) {
  81592. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81593. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81594. _super.prototype.detachControl.call(this, element);
  81595. this._attached = false;
  81596. this.getEngine().disableVR();
  81597. };
  81598. /**
  81599. * @returns the name of this class
  81600. */
  81601. WebVRFreeCamera.prototype.getClassName = function () {
  81602. return "WebVRFreeCamera";
  81603. };
  81604. /**
  81605. * Calls resetPose on the vrDisplay
  81606. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81607. */
  81608. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81609. //uses the vrDisplay's "resetPose()".
  81610. //pitch and roll won't be affected.
  81611. this._vrDevice.resetPose();
  81612. };
  81613. /**
  81614. * Updates the rig cameras (left and right eye)
  81615. */
  81616. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81617. var camLeft = this._rigCameras[0];
  81618. var camRight = this._rigCameras[1];
  81619. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81620. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81621. camLeft.position.copyFrom(this._deviceRoomPosition);
  81622. camRight.position.copyFrom(this._deviceRoomPosition);
  81623. };
  81624. /**
  81625. * Updates the cached values of the camera
  81626. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81627. */
  81628. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81629. var _this = this;
  81630. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81631. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81632. if (!this.updateCacheCalled) {
  81633. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81634. this.updateCacheCalled = true;
  81635. this.update();
  81636. }
  81637. // Set working vector to the device position in room space rotated by the new rotation
  81638. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81639. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81640. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81641. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81642. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81643. // Add translation from anchor position
  81644. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81645. this._workingVector.addInPlace(this.position);
  81646. this._workingVector.subtractInPlace(this._cache.position);
  81647. this._deviceToWorld.setTranslation(this._workingVector);
  81648. // Set an inverted matrix to be used when updating the camera
  81649. this._deviceToWorld.invertToRef(this._worldToDevice);
  81650. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81651. this.controllers.forEach(function (controller) {
  81652. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81653. controller.update();
  81654. });
  81655. }
  81656. if (!ignoreParentClass) {
  81657. _super.prototype._updateCache.call(this);
  81658. }
  81659. this.updateCacheCalled = false;
  81660. };
  81661. /**
  81662. * Updates the current device position and rotation in the babylon world
  81663. */
  81664. WebVRFreeCamera.prototype.update = function () {
  81665. // Get current device position in babylon world
  81666. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81667. // Get current device rotation in babylon world
  81668. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81669. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81670. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81671. _super.prototype.update.call(this);
  81672. };
  81673. /**
  81674. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81675. * @returns an identity matrix
  81676. */
  81677. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81678. return BABYLON.Matrix.Identity();
  81679. };
  81680. /**
  81681. * This function is called by the two RIG cameras.
  81682. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81683. */
  81684. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81685. var _this = this;
  81686. // Update the parent camera prior to using a child camera to avoid desynchronization
  81687. var parentCamera = this._cameraRigParams["parentCamera"];
  81688. parentCamera._updateCache();
  81689. //WebVR 1.1
  81690. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81691. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81692. if (!this.getScene().useRightHandedSystem) {
  81693. [2, 6, 8, 9, 14].forEach(function (num) {
  81694. _this._webvrViewMatrix.m[num] *= -1;
  81695. });
  81696. }
  81697. // update the camera rotation matrix
  81698. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81699. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81700. // Computing target and final matrix
  81701. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81702. // should the view matrix be updated with scale and position offset?
  81703. if (parentCamera.deviceScaleFactor !== 1) {
  81704. this._webvrViewMatrix.invert();
  81705. // scale the position, if set
  81706. if (parentCamera.deviceScaleFactor) {
  81707. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81708. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81709. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81710. }
  81711. this._webvrViewMatrix.invert();
  81712. }
  81713. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81714. return this._webvrViewMatrix;
  81715. };
  81716. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81717. var _this = this;
  81718. var parentCamera = this.parent;
  81719. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81720. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81721. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  81722. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  81723. //babylon compatible matrix
  81724. if (!this.getScene().useRightHandedSystem) {
  81725. [8, 9, 10, 11].forEach(function (num) {
  81726. _this._projectionMatrix.m[num] *= -1;
  81727. });
  81728. }
  81729. return this._projectionMatrix;
  81730. };
  81731. /**
  81732. * Initializes the controllers and their meshes
  81733. */
  81734. WebVRFreeCamera.prototype.initControllers = function () {
  81735. var _this = this;
  81736. this.controllers = [];
  81737. var manager = this.getScene().gamepadManager;
  81738. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81739. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81740. var webVrController = gamepad;
  81741. if (webVrController.defaultModel) {
  81742. webVrController.defaultModel.setEnabled(false);
  81743. }
  81744. if (webVrController.hand === "right") {
  81745. _this._rightController = null;
  81746. }
  81747. if (webVrController.hand === "left") {
  81748. _this._leftController = null;
  81749. }
  81750. var controllerIndex = _this.controllers.indexOf(webVrController);
  81751. if (controllerIndex !== -1) {
  81752. _this.controllers.splice(controllerIndex, 1);
  81753. }
  81754. }
  81755. });
  81756. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81757. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81758. var webVrController_1 = gamepad;
  81759. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81760. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81761. if (_this.webVROptions.controllerMeshes) {
  81762. if (webVrController_1.defaultModel) {
  81763. webVrController_1.defaultModel.setEnabled(true);
  81764. }
  81765. else {
  81766. // Load the meshes
  81767. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81768. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81769. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81770. if (_this.webVROptions.defaultLightingOnControllers) {
  81771. if (!_this._lightOnControllers) {
  81772. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81773. }
  81774. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81775. var children = mesh.getChildren();
  81776. if (children.length !== 0) {
  81777. children.forEach(function (mesh) {
  81778. light.includedOnlyMeshes.push(mesh);
  81779. activateLightOnSubMeshes_1(mesh, light);
  81780. });
  81781. }
  81782. };
  81783. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81784. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81785. }
  81786. });
  81787. }
  81788. }
  81789. webVrController_1.attachToPoseControlledCamera(_this);
  81790. // since this is async - sanity check. Is the controller already stored?
  81791. if (_this.controllers.indexOf(webVrController_1) === -1) {
  81792. //add to the controllers array
  81793. _this.controllers.push(webVrController_1);
  81794. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  81795. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  81796. // So we're overriding setting left & right manually to be sure
  81797. var firstViveWandDetected = false;
  81798. for (var i = 0; i < _this.controllers.length; i++) {
  81799. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81800. if (!firstViveWandDetected) {
  81801. firstViveWandDetected = true;
  81802. _this.controllers[i].hand = "left";
  81803. }
  81804. else {
  81805. _this.controllers[i].hand = "right";
  81806. }
  81807. }
  81808. }
  81809. //did we find enough controllers? Great! let the developer know.
  81810. if (_this.controllers.length >= 2) {
  81811. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  81812. }
  81813. }
  81814. }
  81815. });
  81816. };
  81817. return WebVRFreeCamera;
  81818. }(BABYLON.FreeCamera));
  81819. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  81820. })(BABYLON || (BABYLON = {}));
  81821. //# sourceMappingURL=babylon.webVRCamera.js.map
  81822. var BABYLON;
  81823. (function (BABYLON) {
  81824. // We're mainly based on the logic defined into the FreeCamera code
  81825. /**
  81826. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  81827. * being tilted forward or back and left or right.
  81828. */
  81829. var DeviceOrientationCamera = /** @class */ (function (_super) {
  81830. __extends(DeviceOrientationCamera, _super);
  81831. /**
  81832. * Creates a new device orientation camera. @see DeviceOrientationCamera
  81833. * @param name The name of the camera
  81834. * @param position The start position camera
  81835. * @param scene The scene the camera belongs to
  81836. */
  81837. function DeviceOrientationCamera(name, position, scene) {
  81838. var _this = _super.call(this, name, position, scene) || this;
  81839. _this._quaternionCache = new BABYLON.Quaternion();
  81840. _this.inputs.addDeviceOrientation();
  81841. return _this;
  81842. }
  81843. /**
  81844. * Gets the current instance class name ("DeviceOrientationCamera").
  81845. * This helps avoiding instanceof at run time.
  81846. * @returns the class name
  81847. */
  81848. DeviceOrientationCamera.prototype.getClassName = function () {
  81849. return "DeviceOrientationCamera";
  81850. };
  81851. /**
  81852. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  81853. */
  81854. DeviceOrientationCamera.prototype._checkInputs = function () {
  81855. _super.prototype._checkInputs.call(this);
  81856. this._quaternionCache.copyFrom(this.rotationQuaternion);
  81857. if (this._initialQuaternion) {
  81858. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81859. }
  81860. };
  81861. /**
  81862. * Reset the camera to its default orientation on the specified axis only.
  81863. * @param axis The axis to reset
  81864. */
  81865. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  81866. var _this = this;
  81867. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  81868. //can only work if this camera has a rotation quaternion already.
  81869. if (!this.rotationQuaternion)
  81870. return;
  81871. if (!this._initialQuaternion) {
  81872. this._initialQuaternion = new BABYLON.Quaternion();
  81873. }
  81874. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  81875. ['x', 'y', 'z'].forEach(function (axisName) {
  81876. if (!axis[axisName]) {
  81877. _this._initialQuaternion[axisName] = 0;
  81878. }
  81879. else {
  81880. _this._initialQuaternion[axisName] *= -1;
  81881. }
  81882. });
  81883. this._initialQuaternion.normalize();
  81884. //force rotation update
  81885. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81886. };
  81887. return DeviceOrientationCamera;
  81888. }(BABYLON.FreeCamera));
  81889. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  81890. })(BABYLON || (BABYLON = {}));
  81891. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  81892. var BABYLON;
  81893. (function (BABYLON) {
  81894. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  81895. __extends(VRDeviceOrientationFreeCamera, _super);
  81896. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81897. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81898. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81899. var _this = _super.call(this, name, position, scene) || this;
  81900. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81901. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81902. return _this;
  81903. }
  81904. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81905. return "VRDeviceOrientationFreeCamera";
  81906. };
  81907. return VRDeviceOrientationFreeCamera;
  81908. }(BABYLON.DeviceOrientationCamera));
  81909. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81910. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81911. __extends(VRDeviceOrientationGamepadCamera, _super);
  81912. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81913. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81914. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81915. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81916. _this.inputs.addGamepad();
  81917. return _this;
  81918. }
  81919. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81920. return "VRDeviceOrientationGamepadCamera";
  81921. };
  81922. return VRDeviceOrientationGamepadCamera;
  81923. }(VRDeviceOrientationFreeCamera));
  81924. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81925. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81926. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81927. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81928. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81929. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81930. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81931. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81932. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81933. _this.inputs.addVRDeviceOrientation();
  81934. return _this;
  81935. }
  81936. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81937. return "VRDeviceOrientationArcRotateCamera";
  81938. };
  81939. return VRDeviceOrientationArcRotateCamera;
  81940. }(BABYLON.ArcRotateCamera));
  81941. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81942. })(BABYLON || (BABYLON = {}));
  81943. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81944. var BABYLON;
  81945. (function (BABYLON) {
  81946. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81947. __extends(AnaglyphFreeCamera, _super);
  81948. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81949. var _this = _super.call(this, name, position, scene) || this;
  81950. _this.interaxialDistance = interaxialDistance;
  81951. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81952. return _this;
  81953. }
  81954. AnaglyphFreeCamera.prototype.getClassName = function () {
  81955. return "AnaglyphFreeCamera";
  81956. };
  81957. return AnaglyphFreeCamera;
  81958. }(BABYLON.FreeCamera));
  81959. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81960. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81961. __extends(AnaglyphArcRotateCamera, _super);
  81962. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81963. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81964. _this.interaxialDistance = interaxialDistance;
  81965. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81966. return _this;
  81967. }
  81968. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81969. return "AnaglyphArcRotateCamera";
  81970. };
  81971. return AnaglyphArcRotateCamera;
  81972. }(BABYLON.ArcRotateCamera));
  81973. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81974. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81975. __extends(AnaglyphGamepadCamera, _super);
  81976. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81977. var _this = _super.call(this, name, position, scene) || this;
  81978. _this.interaxialDistance = interaxialDistance;
  81979. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81980. return _this;
  81981. }
  81982. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81983. return "AnaglyphGamepadCamera";
  81984. };
  81985. return AnaglyphGamepadCamera;
  81986. }(BABYLON.GamepadCamera));
  81987. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81988. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81989. __extends(AnaglyphUniversalCamera, _super);
  81990. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81991. var _this = _super.call(this, name, position, scene) || this;
  81992. _this.interaxialDistance = interaxialDistance;
  81993. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81994. return _this;
  81995. }
  81996. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81997. return "AnaglyphUniversalCamera";
  81998. };
  81999. return AnaglyphUniversalCamera;
  82000. }(BABYLON.UniversalCamera));
  82001. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82002. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82003. __extends(StereoscopicFreeCamera, _super);
  82004. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82005. var _this = _super.call(this, name, position, scene) || this;
  82006. _this.interaxialDistance = interaxialDistance;
  82007. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82008. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82009. return _this;
  82010. }
  82011. StereoscopicFreeCamera.prototype.getClassName = function () {
  82012. return "StereoscopicFreeCamera";
  82013. };
  82014. return StereoscopicFreeCamera;
  82015. }(BABYLON.FreeCamera));
  82016. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82017. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82018. __extends(StereoscopicArcRotateCamera, _super);
  82019. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82020. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82021. _this.interaxialDistance = interaxialDistance;
  82022. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82023. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82024. return _this;
  82025. }
  82026. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82027. return "StereoscopicArcRotateCamera";
  82028. };
  82029. return StereoscopicArcRotateCamera;
  82030. }(BABYLON.ArcRotateCamera));
  82031. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82032. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82033. __extends(StereoscopicGamepadCamera, _super);
  82034. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82035. var _this = _super.call(this, name, position, scene) || this;
  82036. _this.interaxialDistance = interaxialDistance;
  82037. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82038. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82039. return _this;
  82040. }
  82041. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82042. return "StereoscopicGamepadCamera";
  82043. };
  82044. return StereoscopicGamepadCamera;
  82045. }(BABYLON.GamepadCamera));
  82046. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82047. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82048. __extends(StereoscopicUniversalCamera, _super);
  82049. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82050. var _this = _super.call(this, name, position, scene) || this;
  82051. _this.interaxialDistance = interaxialDistance;
  82052. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82053. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82054. return _this;
  82055. }
  82056. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82057. return "StereoscopicUniversalCamera";
  82058. };
  82059. return StereoscopicUniversalCamera;
  82060. }(BABYLON.UniversalCamera));
  82061. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82062. })(BABYLON || (BABYLON = {}));
  82063. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82064. var BABYLON;
  82065. (function (BABYLON) {
  82066. var VRExperienceHelperGazer = /** @class */ (function () {
  82067. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82068. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82069. this.scene = scene;
  82070. this._pointerDownOnMeshAsked = false;
  82071. this._isActionableMesh = false;
  82072. this._teleportationRequestInitiated = false;
  82073. this._teleportationBackRequestInitiated = false;
  82074. this._dpadPressed = true;
  82075. this._activePointer = false;
  82076. this._id = VRExperienceHelperGazer._idCounter++;
  82077. // Gaze tracker
  82078. if (!gazeTrackerToClone) {
  82079. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82080. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82081. this._gazeTracker.isPickable = false;
  82082. this._gazeTracker.isVisible = false;
  82083. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82084. targetMat.specularColor = BABYLON.Color3.Black();
  82085. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82086. targetMat.backFaceCulling = false;
  82087. this._gazeTracker.material = targetMat;
  82088. }
  82089. else {
  82090. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82091. }
  82092. }
  82093. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82094. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82095. };
  82096. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82097. this._pointerDownOnMeshAsked = true;
  82098. if (this._currentMeshSelected && this._currentHit) {
  82099. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82100. }
  82101. };
  82102. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82103. if (this._currentMeshSelected && this._currentHit) {
  82104. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82105. }
  82106. this._pointerDownOnMeshAsked = false;
  82107. };
  82108. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82109. this._activePointer = true;
  82110. };
  82111. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82112. this._activePointer = false;
  82113. };
  82114. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82115. };
  82116. VRExperienceHelperGazer.prototype.dispose = function () {
  82117. this._interactionsEnabled = false;
  82118. this._teleportationEnabled = false;
  82119. };
  82120. VRExperienceHelperGazer._idCounter = 0;
  82121. return VRExperienceHelperGazer;
  82122. }());
  82123. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82124. __extends(VRExperienceHelperControllerGazer, _super);
  82125. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82126. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82127. _this.webVRController = webVRController;
  82128. // Laser pointer
  82129. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82130. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82131. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82132. laserPointerMaterial.alpha = 0.6;
  82133. _this._laserPointer.material = laserPointerMaterial;
  82134. _this._laserPointer.rotation.x = Math.PI / 2;
  82135. _this._laserPointer.position.z = -0.5;
  82136. _this._laserPointer.isVisible = false;
  82137. if (!webVRController.mesh) {
  82138. // Create an empty mesh that is used prior to loading the high quality model
  82139. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82140. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82141. preloadPointerPose.rotation.x = -0.7;
  82142. preloadMesh.addChild(preloadPointerPose);
  82143. webVRController.attachToMesh(preloadMesh);
  82144. }
  82145. _this._setLaserPointerParent(webVRController.mesh);
  82146. return _this;
  82147. }
  82148. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82149. return this.webVRController.getForwardRay(length);
  82150. };
  82151. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82152. _super.prototype._activatePointer.call(this);
  82153. this._laserPointer.isVisible = true;
  82154. };
  82155. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82156. _super.prototype._deactivatePointer.call(this);
  82157. this._laserPointer.isVisible = false;
  82158. };
  82159. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82160. this._laserPointer.material.emissiveColor = color;
  82161. };
  82162. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82163. var makeNotPick = function (root) {
  82164. root.name += " laserPointer";
  82165. root.getChildMeshes().forEach(function (c) {
  82166. makeNotPick(c);
  82167. });
  82168. };
  82169. makeNotPick(mesh);
  82170. var childMeshes = mesh.getChildMeshes();
  82171. this.webVRController._pointingPoseNode = null;
  82172. for (var i = 0; i < childMeshes.length; i++) {
  82173. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82174. mesh = childMeshes[i];
  82175. this.webVRController._pointingPoseNode = mesh;
  82176. break;
  82177. }
  82178. }
  82179. this._laserPointer.parent = mesh;
  82180. };
  82181. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82182. this._laserPointer.scaling.y = distance;
  82183. this._laserPointer.position.z = -distance / 2;
  82184. };
  82185. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82186. _super.prototype.dispose.call(this);
  82187. this._laserPointer.dispose();
  82188. };
  82189. return VRExperienceHelperControllerGazer;
  82190. }(VRExperienceHelperGazer));
  82191. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82192. __extends(VRExperienceHelperCameraGazer, _super);
  82193. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82194. var _this = _super.call(this, scene) || this;
  82195. _this.getCamera = getCamera;
  82196. return _this;
  82197. }
  82198. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82199. var camera = this.getCamera();
  82200. if (camera) {
  82201. return camera.getForwardRay(length);
  82202. }
  82203. else {
  82204. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82205. }
  82206. };
  82207. return VRExperienceHelperCameraGazer;
  82208. }(VRExperienceHelperGazer));
  82209. /**
  82210. * Helps to quickly add VR support to an existing scene.
  82211. * See http://doc.babylonjs.com/how_to/webvr_helper
  82212. */
  82213. var VRExperienceHelper = /** @class */ (function () {
  82214. /**
  82215. * Instantiates a VRExperienceHelper.
  82216. * Helps to quickly add VR support to an existing scene.
  82217. * @param scene The scene the VRExperienceHelper belongs to.
  82218. * @param webVROptions Options to modify the vr experience helper's behavior.
  82219. */
  82220. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82221. if (webVROptions === void 0) { webVROptions = {}; }
  82222. var _this = this;
  82223. this.webVROptions = webVROptions;
  82224. // Can the system support WebVR, even if a headset isn't plugged in?
  82225. this._webVRsupported = false;
  82226. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82227. this._webVRready = false;
  82228. // Are we waiting for the requestPresent callback to complete?
  82229. this._webVRrequesting = false;
  82230. // Are we presenting to the headset right now?
  82231. this._webVRpresenting = false;
  82232. // Are we presenting in the fullscreen fallback?
  82233. this._fullscreenVRpresenting = false;
  82234. /**
  82235. * Observable raised when entering VR.
  82236. */
  82237. this.onEnteringVRObservable = new BABYLON.Observable();
  82238. /**
  82239. * Observable raised when exiting VR.
  82240. */
  82241. this.onExitingVRObservable = new BABYLON.Observable();
  82242. /**
  82243. * Observable raised when controller mesh is loaded.
  82244. */
  82245. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82246. this._useCustomVRButton = false;
  82247. this._teleportationRequested = false;
  82248. this._teleportActive = false;
  82249. this._floorMeshesCollection = [];
  82250. this._rotationAllowed = true;
  82251. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82252. this._rotationRightAsked = false;
  82253. this._rotationLeftAsked = false;
  82254. this._isDefaultTeleportationTarget = true;
  82255. this._teleportationFillColor = "#444444";
  82256. this._teleportationBorderColor = "#FFFFFF";
  82257. this._rotationAngle = 0;
  82258. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82259. this._padSensibilityUp = 0.65;
  82260. this._padSensibilityDown = 0.35;
  82261. this.leftController = null;
  82262. this.rightController = null;
  82263. /**
  82264. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82265. */
  82266. this.onNewMeshSelected = new BABYLON.Observable();
  82267. /**
  82268. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82269. */
  82270. this.onNewMeshPicked = new BABYLON.Observable();
  82271. /**
  82272. * Observable raised before camera teleportation
  82273. */
  82274. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82275. /**
  82276. * Observable raised after camera teleportation
  82277. */
  82278. this.onAfterCameraTeleport = new BABYLON.Observable();
  82279. /**
  82280. * Observable raised when current selected mesh gets unselected
  82281. */
  82282. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82283. /**
  82284. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82285. */
  82286. this.teleportationEnabled = true;
  82287. this._teleportationInitialized = false;
  82288. this._interactionsEnabled = false;
  82289. this._interactionsRequested = false;
  82290. this._displayGaze = true;
  82291. this._displayLaserPointer = true;
  82292. this._onResize = function () {
  82293. _this.moveButtonToBottomRight();
  82294. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82295. _this.exitVR();
  82296. }
  82297. };
  82298. this._onFullscreenChange = function () {
  82299. if (document.fullscreen !== undefined) {
  82300. _this._fullscreenVRpresenting = document.fullscreen;
  82301. }
  82302. else if (document.mozFullScreen !== undefined) {
  82303. _this._fullscreenVRpresenting = document.mozFullScreen;
  82304. }
  82305. else if (document.webkitIsFullScreen !== undefined) {
  82306. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82307. }
  82308. else if (document.msIsFullScreen !== undefined) {
  82309. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82310. }
  82311. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82312. _this.exitVR();
  82313. if (!_this._useCustomVRButton) {
  82314. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82315. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82316. }
  82317. }
  82318. };
  82319. this.beforeRender = function () {
  82320. if (_this.leftController && _this.leftController._activePointer) {
  82321. _this._castRayAndSelectObject(_this.leftController);
  82322. }
  82323. if (_this.rightController && _this.rightController._activePointer) {
  82324. _this._castRayAndSelectObject(_this.rightController);
  82325. }
  82326. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82327. _this._castRayAndSelectObject(_this._cameraGazer);
  82328. }
  82329. else {
  82330. _this._cameraGazer._gazeTracker.isVisible = false;
  82331. }
  82332. };
  82333. this._onNewGamepadConnected = function (gamepad) {
  82334. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82335. if (gamepad.leftStick) {
  82336. gamepad.onleftstickchanged(function (stickValues) {
  82337. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82338. // Listening to classic/xbox gamepad only if no VR controller is active
  82339. if ((!_this.leftController && !_this.rightController) ||
  82340. ((_this.leftController && !_this.leftController._activePointer) &&
  82341. (_this.rightController && !_this.rightController._activePointer))) {
  82342. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82343. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82344. }
  82345. }
  82346. });
  82347. }
  82348. if (gamepad.rightStick) {
  82349. gamepad.onrightstickchanged(function (stickValues) {
  82350. if (_this._teleportationInitialized) {
  82351. _this._checkRotate(stickValues, _this._cameraGazer);
  82352. }
  82353. });
  82354. }
  82355. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82356. gamepad.onbuttondown(function (buttonPressed) {
  82357. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82358. _this._cameraGazer._selectionPointerDown();
  82359. }
  82360. });
  82361. gamepad.onbuttonup(function (buttonPressed) {
  82362. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82363. _this._cameraGazer._selectionPointerUp();
  82364. }
  82365. });
  82366. }
  82367. }
  82368. else {
  82369. var webVRController = gamepad;
  82370. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82371. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82372. _this.rightController = controller;
  82373. }
  82374. else {
  82375. _this.leftController = controller;
  82376. }
  82377. _this._tryEnableInteractionOnController(controller);
  82378. }
  82379. };
  82380. // 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
  82381. this._tryEnableInteractionOnController = function (controller) {
  82382. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82383. _this._enableInteractionOnController(controller);
  82384. }
  82385. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82386. _this._enableTeleportationOnController(controller);
  82387. }
  82388. };
  82389. this._onNewGamepadDisconnected = function (gamepad) {
  82390. if (gamepad instanceof BABYLON.WebVRController) {
  82391. if (gamepad.hand === "left" && _this.leftController != null) {
  82392. _this.leftController.dispose();
  82393. _this.leftController = null;
  82394. }
  82395. if (gamepad.hand === "right" && _this.rightController != null) {
  82396. _this.rightController.dispose();
  82397. _this.rightController = null;
  82398. }
  82399. }
  82400. };
  82401. this._workingVector = BABYLON.Vector3.Zero();
  82402. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82403. this._workingMatrix = BABYLON.Matrix.Identity();
  82404. this._scene = scene;
  82405. this._canvas = scene.getEngine().getRenderingCanvas();
  82406. // Parse options
  82407. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82408. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82409. }
  82410. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82411. webVROptions.createDeviceOrientationCamera = true;
  82412. }
  82413. if (webVROptions.defaultHeight === undefined) {
  82414. webVROptions.defaultHeight = 1.7;
  82415. }
  82416. if (webVROptions.useCustomVRButton) {
  82417. this._useCustomVRButton = true;
  82418. if (webVROptions.customVRButton) {
  82419. this._btnVR = webVROptions.customVRButton;
  82420. }
  82421. }
  82422. if (webVROptions.rayLength) {
  82423. this._rayLength = webVROptions.rayLength;
  82424. }
  82425. this._defaultHeight = webVROptions.defaultHeight;
  82426. if (webVROptions.positionScale) {
  82427. this._rayLength *= webVROptions.positionScale;
  82428. this._defaultHeight *= webVROptions.positionScale;
  82429. }
  82430. // Set position
  82431. if (this._scene.activeCamera) {
  82432. this._position = this._scene.activeCamera.position.clone();
  82433. }
  82434. else {
  82435. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82436. }
  82437. // Set non-vr camera
  82438. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82439. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82440. // Copy data from existing camera
  82441. if (this._scene.activeCamera) {
  82442. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82443. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82444. // Set rotation from previous camera
  82445. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82446. var targetCamera = this._scene.activeCamera;
  82447. if (targetCamera.rotationQuaternion) {
  82448. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82449. }
  82450. else {
  82451. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82452. }
  82453. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82454. }
  82455. }
  82456. this._scene.activeCamera = this._deviceOrientationCamera;
  82457. if (this._canvas) {
  82458. this._scene.activeCamera.attachControl(this._canvas);
  82459. }
  82460. }
  82461. else {
  82462. this._existingCamera = this._scene.activeCamera;
  82463. }
  82464. // Create VR cameras
  82465. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82466. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82467. }
  82468. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82469. this._webVRCamera.useStandingMatrix();
  82470. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82471. // Create default button
  82472. if (!this._useCustomVRButton) {
  82473. this._btnVR = document.createElement("BUTTON");
  82474. this._btnVR.className = "babylonVRicon";
  82475. this._btnVR.id = "babylonVRiconbtn";
  82476. this._btnVR.title = "Click to switch to VR";
  82477. 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) }";
  82478. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82479. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82480. // css += ".babylonVRicon.vrdisplaysupported { }";
  82481. // css += ".babylonVRicon.vrdisplayready { }";
  82482. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82483. var style = document.createElement('style');
  82484. style.appendChild(document.createTextNode(css));
  82485. document.getElementsByTagName('head')[0].appendChild(style);
  82486. this.moveButtonToBottomRight();
  82487. }
  82488. // VR button click event
  82489. if (this._btnVR) {
  82490. this._btnVR.addEventListener("click", function () {
  82491. if (!_this.isInVRMode) {
  82492. _this.enterVR();
  82493. }
  82494. else {
  82495. _this.exitVR();
  82496. }
  82497. });
  82498. }
  82499. // Window events
  82500. window.addEventListener("resize", this._onResize);
  82501. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82502. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82503. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82504. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82505. // Display vr button when headset is connected
  82506. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82507. this.displayVRButton();
  82508. }
  82509. else {
  82510. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82511. if (e.vrDisplay) {
  82512. _this.displayVRButton();
  82513. }
  82514. });
  82515. }
  82516. // Exiting VR mode using 'ESC' key on desktop
  82517. this._onKeyDown = function (event) {
  82518. if (event.keyCode === 27 && _this.isInVRMode) {
  82519. _this.exitVR();
  82520. }
  82521. };
  82522. document.addEventListener("keydown", this._onKeyDown);
  82523. // Exiting VR mode double tapping the touch screen
  82524. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82525. if (_this.isInVRMode) {
  82526. _this.exitVR();
  82527. if (_this._fullscreenVRpresenting) {
  82528. _this._scene.getEngine().switchFullscreen(true);
  82529. }
  82530. }
  82531. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82532. // Listen for WebVR display changes
  82533. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82534. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82535. this._onVRRequestPresentStart = function () {
  82536. _this._webVRrequesting = true;
  82537. _this.updateButtonVisibility();
  82538. };
  82539. this._onVRRequestPresentComplete = function (success) {
  82540. _this._webVRrequesting = false;
  82541. _this.updateButtonVisibility();
  82542. };
  82543. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82544. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82545. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82546. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82547. scene.onDisposeObservable.add(function () {
  82548. _this.dispose();
  82549. });
  82550. // Gamepad connection events
  82551. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82552. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82553. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82554. this.updateButtonVisibility();
  82555. //create easing functions
  82556. this._circleEase = new BABYLON.CircleEase();
  82557. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82558. }
  82559. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82560. /** Return this.onEnteringVRObservable
  82561. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82562. */
  82563. get: function () {
  82564. return this.onEnteringVRObservable;
  82565. },
  82566. enumerable: true,
  82567. configurable: true
  82568. });
  82569. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82570. /** Return this.onExitingVRObservable
  82571. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82572. */
  82573. get: function () {
  82574. return this.onExitingVRObservable;
  82575. },
  82576. enumerable: true,
  82577. configurable: true
  82578. });
  82579. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82580. /** Return this.onControllerMeshLoadedObservable
  82581. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82582. */
  82583. get: function () {
  82584. return this.onControllerMeshLoadedObservable;
  82585. },
  82586. enumerable: true,
  82587. configurable: true
  82588. });
  82589. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82590. /**
  82591. * The mesh used to display where the user is going to teleport.
  82592. */
  82593. get: function () {
  82594. return this._teleportationTarget;
  82595. },
  82596. /**
  82597. * Sets the mesh to be used to display where the user is going to teleport.
  82598. */
  82599. set: function (value) {
  82600. if (value) {
  82601. value.name = "teleportationTarget";
  82602. this._isDefaultTeleportationTarget = false;
  82603. this._teleportationTarget = value;
  82604. }
  82605. },
  82606. enumerable: true,
  82607. configurable: true
  82608. });
  82609. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82610. /**
  82611. * The mesh used to display where the user is selecting,
  82612. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82613. * See http://doc.babylonjs.com/resources/baking_transformations
  82614. */
  82615. get: function () {
  82616. return this._cameraGazer._gazeTracker;
  82617. },
  82618. set: function (value) {
  82619. if (value) {
  82620. this._cameraGazer._gazeTracker = value;
  82621. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82622. this._cameraGazer._gazeTracker.isPickable = false;
  82623. this._cameraGazer._gazeTracker.isVisible = false;
  82624. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82625. if (this.leftController) {
  82626. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82627. }
  82628. if (this.rightController) {
  82629. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82630. }
  82631. }
  82632. },
  82633. enumerable: true,
  82634. configurable: true
  82635. });
  82636. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82637. /**
  82638. * If the ray of the gaze should be displayed.
  82639. */
  82640. get: function () {
  82641. return this._displayGaze;
  82642. },
  82643. /**
  82644. * Sets if the ray of the gaze should be displayed.
  82645. */
  82646. set: function (value) {
  82647. this._displayGaze = value;
  82648. if (!value) {
  82649. this._cameraGazer._gazeTracker.isVisible = false;
  82650. if (this.leftController) {
  82651. this.leftController._gazeTracker.isVisible = false;
  82652. }
  82653. if (this.rightController) {
  82654. this.rightController._gazeTracker.isVisible = false;
  82655. }
  82656. }
  82657. },
  82658. enumerable: true,
  82659. configurable: true
  82660. });
  82661. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82662. /**
  82663. * If the ray of the LaserPointer should be displayed.
  82664. */
  82665. get: function () {
  82666. return this._displayLaserPointer;
  82667. },
  82668. /**
  82669. * Sets if the ray of the LaserPointer should be displayed.
  82670. */
  82671. set: function (value) {
  82672. this._displayLaserPointer = value;
  82673. if (!value) {
  82674. if (this.rightController) {
  82675. this.rightController._deactivatePointer();
  82676. this.rightController._gazeTracker.isVisible = false;
  82677. }
  82678. if (this.leftController) {
  82679. this.leftController._deactivatePointer();
  82680. this.leftController._gazeTracker.isVisible = false;
  82681. }
  82682. }
  82683. else {
  82684. if (this.rightController) {
  82685. this.rightController._activatePointer();
  82686. }
  82687. else if (this.leftController) {
  82688. this.leftController._activatePointer();
  82689. }
  82690. }
  82691. },
  82692. enumerable: true,
  82693. configurable: true
  82694. });
  82695. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82696. /**
  82697. * The deviceOrientationCamera used as the camera when not in VR.
  82698. */
  82699. get: function () {
  82700. return this._deviceOrientationCamera;
  82701. },
  82702. enumerable: true,
  82703. configurable: true
  82704. });
  82705. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82706. /**
  82707. * Based on the current WebVR support, returns the current VR camera used.
  82708. */
  82709. get: function () {
  82710. if (this._webVRready) {
  82711. return this._webVRCamera;
  82712. }
  82713. else {
  82714. return this._scene.activeCamera;
  82715. }
  82716. },
  82717. enumerable: true,
  82718. configurable: true
  82719. });
  82720. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  82721. /**
  82722. * The webVRCamera which is used when in VR.
  82723. */
  82724. get: function () {
  82725. return this._webVRCamera;
  82726. },
  82727. enumerable: true,
  82728. configurable: true
  82729. });
  82730. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  82731. /**
  82732. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  82733. */
  82734. get: function () {
  82735. return this._vrDeviceOrientationCamera;
  82736. },
  82737. enumerable: true,
  82738. configurable: true
  82739. });
  82740. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  82741. get: function () {
  82742. var result = this._cameraGazer._teleportationRequestInitiated
  82743. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  82744. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  82745. return result;
  82746. },
  82747. enumerable: true,
  82748. configurable: true
  82749. });
  82750. // Raised when one of the controller has loaded successfully its associated default mesh
  82751. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  82752. if (this.leftController && this.leftController.webVRController == webVRController) {
  82753. if (webVRController.mesh) {
  82754. this.leftController._setLaserPointerParent(webVRController.mesh);
  82755. }
  82756. }
  82757. if (this.rightController && this.rightController.webVRController == webVRController) {
  82758. if (webVRController.mesh) {
  82759. this.rightController._setLaserPointerParent(webVRController.mesh);
  82760. }
  82761. }
  82762. try {
  82763. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82764. }
  82765. catch (err) {
  82766. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82767. }
  82768. };
  82769. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82770. /**
  82771. * Gets a value indicating if we are currently in VR mode.
  82772. */
  82773. get: function () {
  82774. return this._webVRpresenting || this._fullscreenVRpresenting;
  82775. },
  82776. enumerable: true,
  82777. configurable: true
  82778. });
  82779. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82780. var vrDisplay = this._scene.getEngine().getVRDevice();
  82781. if (vrDisplay) {
  82782. var wasPresenting = this._webVRpresenting;
  82783. // A VR display is connected
  82784. this._webVRpresenting = vrDisplay.isPresenting;
  82785. if (wasPresenting && !this._webVRpresenting)
  82786. this.exitVR();
  82787. }
  82788. else {
  82789. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  82790. }
  82791. this.updateButtonVisibility();
  82792. };
  82793. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  82794. this._webVRsupported = eventArgs.vrSupported;
  82795. this._webVRready = !!eventArgs.vrDisplay;
  82796. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  82797. this.updateButtonVisibility();
  82798. };
  82799. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  82800. if (this._canvas && !this._useCustomVRButton) {
  82801. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  82802. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  82803. }
  82804. };
  82805. VRExperienceHelper.prototype.displayVRButton = function () {
  82806. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  82807. document.body.appendChild(this._btnVR);
  82808. this._btnVRDisplayed = true;
  82809. }
  82810. };
  82811. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  82812. if (!this._btnVR || this._useCustomVRButton) {
  82813. return;
  82814. }
  82815. this._btnVR.className = "babylonVRicon";
  82816. if (this.isInVRMode) {
  82817. this._btnVR.className += " vrdisplaypresenting";
  82818. }
  82819. else {
  82820. if (this._webVRready)
  82821. this._btnVR.className += " vrdisplayready";
  82822. if (this._webVRsupported)
  82823. this._btnVR.className += " vrdisplaysupported";
  82824. if (this._webVRrequesting)
  82825. this._btnVR.className += " vrdisplayrequesting";
  82826. }
  82827. };
  82828. /**
  82829. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  82830. * Otherwise, will use the fullscreen API.
  82831. */
  82832. VRExperienceHelper.prototype.enterVR = function () {
  82833. if (this.onEnteringVRObservable) {
  82834. try {
  82835. this.onEnteringVRObservable.notifyObservers(this);
  82836. }
  82837. catch (err) {
  82838. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  82839. }
  82840. }
  82841. if (this._scene.activeCamera) {
  82842. this._position = this._scene.activeCamera.position.clone();
  82843. // make sure that we return to the last active camera
  82844. this._existingCamera = this._scene.activeCamera;
  82845. }
  82846. if (this._webVRrequesting)
  82847. return;
  82848. // If WebVR is supported and a headset is connected
  82849. if (this._webVRready) {
  82850. if (!this._webVRpresenting) {
  82851. this._webVRCamera.position = this._position;
  82852. this._scene.activeCamera = this._webVRCamera;
  82853. }
  82854. }
  82855. else if (this._vrDeviceOrientationCamera) {
  82856. this._vrDeviceOrientationCamera.position = this._position;
  82857. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  82858. this._scene.getEngine().switchFullscreen(true);
  82859. this.updateButtonVisibility();
  82860. }
  82861. if (this._scene.activeCamera && this._canvas) {
  82862. this._scene.activeCamera.attachControl(this._canvas);
  82863. }
  82864. if (this._interactionsEnabled) {
  82865. this._scene.registerBeforeRender(this.beforeRender);
  82866. }
  82867. };
  82868. /**
  82869. * Attempt to exit VR, or fullscreen.
  82870. */
  82871. VRExperienceHelper.prototype.exitVR = function () {
  82872. if (this.onExitingVRObservable) {
  82873. try {
  82874. this.onExitingVRObservable.notifyObservers(this);
  82875. }
  82876. catch (err) {
  82877. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  82878. }
  82879. }
  82880. if (this._webVRpresenting) {
  82881. this._scene.getEngine().disableVR();
  82882. }
  82883. if (this._scene.activeCamera) {
  82884. this._position = this._scene.activeCamera.position.clone();
  82885. }
  82886. if (this._deviceOrientationCamera) {
  82887. this._deviceOrientationCamera.position = this._position;
  82888. this._scene.activeCamera = this._deviceOrientationCamera;
  82889. if (this._canvas) {
  82890. this._scene.activeCamera.attachControl(this._canvas);
  82891. }
  82892. }
  82893. else if (this._existingCamera) {
  82894. this._existingCamera.position = this._position;
  82895. this._scene.activeCamera = this._existingCamera;
  82896. }
  82897. this.updateButtonVisibility();
  82898. if (this._interactionsEnabled) {
  82899. this._scene.unregisterBeforeRender(this.beforeRender);
  82900. }
  82901. };
  82902. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82903. /**
  82904. * The position of the vr experience helper.
  82905. */
  82906. get: function () {
  82907. return this._position;
  82908. },
  82909. /**
  82910. * Sets the position of the vr experience helper.
  82911. */
  82912. set: function (value) {
  82913. this._position = value;
  82914. if (this._scene.activeCamera) {
  82915. this._scene.activeCamera.position = value;
  82916. }
  82917. },
  82918. enumerable: true,
  82919. configurable: true
  82920. });
  82921. /**
  82922. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82923. */
  82924. VRExperienceHelper.prototype.enableInteractions = function () {
  82925. var _this = this;
  82926. if (!this._interactionsEnabled) {
  82927. this._interactionsRequested = true;
  82928. if (this.leftController) {
  82929. this._enableInteractionOnController(this.leftController);
  82930. }
  82931. if (this.rightController) {
  82932. this._enableInteractionOnController(this.rightController);
  82933. }
  82934. this.raySelectionPredicate = function (mesh) {
  82935. return mesh.isVisible;
  82936. };
  82937. this.meshSelectionPredicate = function (mesh) {
  82938. return true;
  82939. };
  82940. this._raySelectionPredicate = function (mesh) {
  82941. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82942. && mesh.name.indexOf("teleportationTarget") === -1
  82943. && mesh.name.indexOf("torusTeleportation") === -1
  82944. && mesh.name.indexOf("laserPointer") === -1)) {
  82945. return _this.raySelectionPredicate(mesh);
  82946. }
  82947. return false;
  82948. };
  82949. this._interactionsEnabled = true;
  82950. }
  82951. };
  82952. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82953. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82954. if (this._floorMeshesCollection[i].id === mesh.id) {
  82955. return true;
  82956. }
  82957. }
  82958. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82959. return true;
  82960. }
  82961. return false;
  82962. };
  82963. /**
  82964. * Adds a floor mesh to be used for teleportation.
  82965. * @param floorMesh the mesh to be used for teleportation.
  82966. */
  82967. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82968. if (!this._floorMeshesCollection) {
  82969. return;
  82970. }
  82971. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82972. return;
  82973. }
  82974. this._floorMeshesCollection.push(floorMesh);
  82975. };
  82976. /**
  82977. * Removes a floor mesh from being used for teleportation.
  82978. * @param floorMesh the mesh to be removed.
  82979. */
  82980. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82981. if (!this._floorMeshesCollection) {
  82982. return;
  82983. }
  82984. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82985. if (meshIndex !== -1) {
  82986. this._floorMeshesCollection.splice(meshIndex, 1);
  82987. }
  82988. };
  82989. /**
  82990. * Enables interactions and teleportation using the VR controllers and gaze.
  82991. * @param vrTeleportationOptions options to modify teleportation behavior.
  82992. */
  82993. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82994. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82995. if (!this._teleportationInitialized) {
  82996. this._teleportationRequested = true;
  82997. this.enableInteractions();
  82998. if (vrTeleportationOptions.floorMeshName) {
  82999. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83000. }
  83001. if (vrTeleportationOptions.floorMeshes) {
  83002. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83003. }
  83004. if (this.leftController != null) {
  83005. this._enableTeleportationOnController(this.leftController);
  83006. }
  83007. if (this.rightController != null) {
  83008. this._enableTeleportationOnController(this.rightController);
  83009. }
  83010. // Creates an image processing post process for the vignette not relying
  83011. // on the main scene configuration for image processing to reduce setup and spaces
  83012. // (gamma/linear) conflicts.
  83013. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83014. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83015. imageProcessingConfiguration.vignetteEnabled = true;
  83016. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83017. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83018. this._teleportationInitialized = true;
  83019. if (this._isDefaultTeleportationTarget) {
  83020. this._createTeleportationCircles();
  83021. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83022. }
  83023. }
  83024. };
  83025. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83026. var _this = this;
  83027. var controllerMesh = controller.webVRController.mesh;
  83028. if (controllerMesh) {
  83029. controller._interactionsEnabled = true;
  83030. controller._activatePointer();
  83031. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83032. // Enabling / disabling laserPointer
  83033. if (_this._displayLaserPointer && stateObject.value === 1) {
  83034. if (controller._activePointer) {
  83035. controller._deactivatePointer();
  83036. }
  83037. else {
  83038. controller._activatePointer();
  83039. }
  83040. if (_this.displayGaze) {
  83041. controller._gazeTracker.isVisible = controller._activePointer;
  83042. }
  83043. }
  83044. });
  83045. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83046. if (!controller._pointerDownOnMeshAsked) {
  83047. if (stateObject.value > _this._padSensibilityUp) {
  83048. controller._selectionPointerDown();
  83049. }
  83050. }
  83051. else if (stateObject.value < _this._padSensibilityDown) {
  83052. controller._selectionPointerUp();
  83053. }
  83054. });
  83055. }
  83056. };
  83057. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83058. // Dont teleport if another gaze already requested teleportation
  83059. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83060. return;
  83061. }
  83062. if (!gazer._teleportationRequestInitiated) {
  83063. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83064. gazer._activatePointer();
  83065. gazer._teleportationRequestInitiated = true;
  83066. }
  83067. }
  83068. else {
  83069. // Listening to the proper controller values changes to confirm teleportation
  83070. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83071. if (this._teleportActive) {
  83072. this._teleportCamera(this._haloCenter);
  83073. }
  83074. gazer._teleportationRequestInitiated = false;
  83075. }
  83076. }
  83077. };
  83078. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83079. // Only rotate when user is not currently selecting a teleportation location
  83080. if (gazer._teleportationRequestInitiated) {
  83081. return;
  83082. }
  83083. if (!this._rotationLeftAsked) {
  83084. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83085. this._rotationLeftAsked = true;
  83086. if (this._rotationAllowed) {
  83087. this._rotateCamera(false);
  83088. }
  83089. }
  83090. }
  83091. else {
  83092. if (stateObject.x > -this._padSensibilityDown) {
  83093. this._rotationLeftAsked = false;
  83094. }
  83095. }
  83096. if (!this._rotationRightAsked) {
  83097. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83098. this._rotationRightAsked = true;
  83099. if (this._rotationAllowed) {
  83100. this._rotateCamera(true);
  83101. }
  83102. }
  83103. }
  83104. else {
  83105. if (stateObject.x < this._padSensibilityDown) {
  83106. this._rotationRightAsked = false;
  83107. }
  83108. }
  83109. };
  83110. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83111. // Only teleport backwards when user is not currently selecting a teleportation location
  83112. if (gazer._teleportationRequestInitiated) {
  83113. return;
  83114. }
  83115. // Teleport backwards
  83116. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83117. if (!gazer._teleportationBackRequestInitiated) {
  83118. if (!this.currentVRCamera) {
  83119. return;
  83120. }
  83121. // Get rotation and position of the current camera
  83122. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83123. var position = this.currentVRCamera.position;
  83124. // If the camera has device position, use that instead
  83125. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83126. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83127. position = this.currentVRCamera.devicePosition;
  83128. }
  83129. // Get matrix with only the y rotation of the device rotation
  83130. rotation.toEulerAnglesToRef(this._workingVector);
  83131. this._workingVector.z = 0;
  83132. this._workingVector.x = 0;
  83133. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83134. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83135. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83136. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83137. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83138. var ray = new BABYLON.Ray(position, this._workingVector);
  83139. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83140. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83141. this._teleportCamera(hit.pickedPoint);
  83142. }
  83143. gazer._teleportationBackRequestInitiated = true;
  83144. }
  83145. }
  83146. else {
  83147. gazer._teleportationBackRequestInitiated = false;
  83148. }
  83149. };
  83150. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83151. var _this = this;
  83152. var controllerMesh = controller.webVRController.mesh;
  83153. if (controllerMesh) {
  83154. if (!controller._interactionsEnabled) {
  83155. this._enableInteractionOnController(controller);
  83156. }
  83157. controller._interactionsEnabled = true;
  83158. controller._teleportationEnabled = true;
  83159. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83160. controller._dpadPressed = false;
  83161. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83162. controller._dpadPressed = stateObject.pressed;
  83163. if (!controller._dpadPressed) {
  83164. _this._rotationLeftAsked = false;
  83165. _this._rotationRightAsked = false;
  83166. controller._teleportationBackRequestInitiated = false;
  83167. }
  83168. });
  83169. }
  83170. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83171. if (_this.teleportationEnabled) {
  83172. _this._checkTeleportBackwards(stateObject, controller);
  83173. _this._checkTeleportWithRay(stateObject, controller);
  83174. }
  83175. _this._checkRotate(stateObject, controller);
  83176. });
  83177. }
  83178. };
  83179. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83180. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83181. this._teleportationTarget.isPickable = false;
  83182. var length = 512;
  83183. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83184. dynamicTexture.hasAlpha = true;
  83185. var context = dynamicTexture.getContext();
  83186. var centerX = length / 2;
  83187. var centerY = length / 2;
  83188. var radius = 200;
  83189. context.beginPath();
  83190. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83191. context.fillStyle = this._teleportationFillColor;
  83192. context.fill();
  83193. context.lineWidth = 10;
  83194. context.strokeStyle = this._teleportationBorderColor;
  83195. context.stroke();
  83196. context.closePath();
  83197. dynamicTexture.update();
  83198. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83199. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83200. this._teleportationTarget.material = teleportationCircleMaterial;
  83201. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83202. torus.isPickable = false;
  83203. torus.parent = this._teleportationTarget;
  83204. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83205. var keys = [];
  83206. keys.push({
  83207. frame: 0,
  83208. value: 0
  83209. });
  83210. keys.push({
  83211. frame: 30,
  83212. value: 0.4
  83213. });
  83214. keys.push({
  83215. frame: 60,
  83216. value: 0
  83217. });
  83218. animationInnerCircle.setKeys(keys);
  83219. var easingFunction = new BABYLON.SineEase();
  83220. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83221. animationInnerCircle.setEasingFunction(easingFunction);
  83222. torus.animations = [];
  83223. torus.animations.push(animationInnerCircle);
  83224. this._scene.beginAnimation(torus, 0, 60, true);
  83225. this._hideTeleportationTarget();
  83226. };
  83227. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83228. this._teleportActive = true;
  83229. if (this._teleportationInitialized) {
  83230. this._teleportationTarget.isVisible = true;
  83231. if (this._isDefaultTeleportationTarget) {
  83232. this._teleportationTarget.getChildren()[0].isVisible = true;
  83233. }
  83234. }
  83235. };
  83236. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83237. this._teleportActive = false;
  83238. if (this._teleportationInitialized) {
  83239. this._teleportationTarget.isVisible = false;
  83240. if (this._isDefaultTeleportationTarget) {
  83241. this._teleportationTarget.getChildren()[0].isVisible = false;
  83242. }
  83243. }
  83244. };
  83245. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83246. var _this = this;
  83247. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83248. return;
  83249. }
  83250. if (right) {
  83251. this._rotationAngle++;
  83252. }
  83253. else {
  83254. this._rotationAngle--;
  83255. }
  83256. this.currentVRCamera.animations = [];
  83257. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83258. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83259. var animationRotationKeys = [];
  83260. animationRotationKeys.push({
  83261. frame: 0,
  83262. value: this.currentVRCamera.rotationQuaternion
  83263. });
  83264. animationRotationKeys.push({
  83265. frame: 6,
  83266. value: target
  83267. });
  83268. animationRotation.setKeys(animationRotationKeys);
  83269. animationRotation.setEasingFunction(this._circleEase);
  83270. this.currentVRCamera.animations.push(animationRotation);
  83271. this._postProcessMove.animations = [];
  83272. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83273. var vignetteWeightKeys = [];
  83274. vignetteWeightKeys.push({
  83275. frame: 0,
  83276. value: 0
  83277. });
  83278. vignetteWeightKeys.push({
  83279. frame: 3,
  83280. value: 4
  83281. });
  83282. vignetteWeightKeys.push({
  83283. frame: 6,
  83284. value: 0
  83285. });
  83286. animationPP.setKeys(vignetteWeightKeys);
  83287. animationPP.setEasingFunction(this._circleEase);
  83288. this._postProcessMove.animations.push(animationPP);
  83289. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83290. var vignetteStretchKeys = [];
  83291. vignetteStretchKeys.push({
  83292. frame: 0,
  83293. value: 0
  83294. });
  83295. vignetteStretchKeys.push({
  83296. frame: 3,
  83297. value: 10
  83298. });
  83299. vignetteStretchKeys.push({
  83300. frame: 6,
  83301. value: 0
  83302. });
  83303. animationPP2.setKeys(vignetteStretchKeys);
  83304. animationPP2.setEasingFunction(this._circleEase);
  83305. this._postProcessMove.animations.push(animationPP2);
  83306. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83307. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83308. this._postProcessMove.samples = 4;
  83309. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83310. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83311. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83312. });
  83313. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83314. };
  83315. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83316. if (hit.pickedPoint) {
  83317. if (gazer._teleportationRequestInitiated) {
  83318. this._displayTeleportationTarget();
  83319. this._haloCenter.copyFrom(hit.pickedPoint);
  83320. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83321. }
  83322. var pickNormal = hit.getNormal(true, false);
  83323. if (pickNormal) {
  83324. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83325. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83326. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83327. }
  83328. this._teleportationTarget.position.y += 0.1;
  83329. }
  83330. };
  83331. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83332. var _this = this;
  83333. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83334. return;
  83335. }
  83336. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83337. // offset of the headset from the anchor.
  83338. if (this.webVRCamera.leftCamera) {
  83339. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83340. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83341. location.subtractToRef(this._workingVector, this._workingVector);
  83342. }
  83343. else {
  83344. this._workingVector.copyFrom(location);
  83345. }
  83346. // Add height to account for user's height offset
  83347. if (this.isInVRMode) {
  83348. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83349. }
  83350. else {
  83351. this._workingVector.y += this._defaultHeight;
  83352. }
  83353. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83354. // Create animation from the camera's position to the new location
  83355. this.currentVRCamera.animations = [];
  83356. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83357. var animationCameraTeleportationKeys = [{
  83358. frame: 0,
  83359. value: this.currentVRCamera.position
  83360. },
  83361. {
  83362. frame: 11,
  83363. value: this._workingVector
  83364. }
  83365. ];
  83366. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83367. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83368. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83369. this._postProcessMove.animations = [];
  83370. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83371. var vignetteWeightKeys = [];
  83372. vignetteWeightKeys.push({
  83373. frame: 0,
  83374. value: 0
  83375. });
  83376. vignetteWeightKeys.push({
  83377. frame: 5,
  83378. value: 8
  83379. });
  83380. vignetteWeightKeys.push({
  83381. frame: 11,
  83382. value: 0
  83383. });
  83384. animationPP.setKeys(vignetteWeightKeys);
  83385. this._postProcessMove.animations.push(animationPP);
  83386. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83387. var vignetteStretchKeys = [];
  83388. vignetteStretchKeys.push({
  83389. frame: 0,
  83390. value: 0
  83391. });
  83392. vignetteStretchKeys.push({
  83393. frame: 5,
  83394. value: 10
  83395. });
  83396. vignetteStretchKeys.push({
  83397. frame: 11,
  83398. value: 0
  83399. });
  83400. animationPP2.setKeys(vignetteStretchKeys);
  83401. this._postProcessMove.animations.push(animationPP2);
  83402. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83403. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83404. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83405. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83406. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83407. });
  83408. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83409. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83410. });
  83411. this._hideTeleportationTarget();
  83412. };
  83413. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83414. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83415. return;
  83416. }
  83417. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83418. // Moving the gazeTracker on the mesh face targetted
  83419. if (hit && hit.pickedPoint) {
  83420. if (this._displayGaze) {
  83421. var multiplier = 1;
  83422. gazer._gazeTracker.isVisible = true;
  83423. if (gazer._isActionableMesh) {
  83424. multiplier = 3;
  83425. }
  83426. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83427. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83428. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83429. var pickNormal = hit.getNormal();
  83430. // To avoid z-fighting
  83431. var deltaFighting = 0.002;
  83432. if (pickNormal) {
  83433. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83434. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83435. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83436. }
  83437. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83438. if (gazer._gazeTracker.position.x < 0) {
  83439. gazer._gazeTracker.position.x += deltaFighting;
  83440. }
  83441. else {
  83442. gazer._gazeTracker.position.x -= deltaFighting;
  83443. }
  83444. if (gazer._gazeTracker.position.y < 0) {
  83445. gazer._gazeTracker.position.y += deltaFighting;
  83446. }
  83447. else {
  83448. gazer._gazeTracker.position.y -= deltaFighting;
  83449. }
  83450. if (gazer._gazeTracker.position.z < 0) {
  83451. gazer._gazeTracker.position.z += deltaFighting;
  83452. }
  83453. else {
  83454. gazer._gazeTracker.position.z -= deltaFighting;
  83455. }
  83456. }
  83457. // Changing the size of the laser pointer based on the distance from the targetted point
  83458. gazer._updatePointerDistance(hit.distance);
  83459. }
  83460. else {
  83461. gazer._gazeTracker.isVisible = false;
  83462. }
  83463. if (hit && hit.pickedMesh) {
  83464. gazer._currentHit = hit;
  83465. if (gazer._pointerDownOnMeshAsked) {
  83466. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83467. }
  83468. // The object selected is the floor, we're in a teleportation scenario
  83469. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83470. // Moving the teleportation area to this targetted point
  83471. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83472. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83473. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83474. }
  83475. gazer._currentMeshSelected = null;
  83476. if (gazer._teleportationRequestInitiated) {
  83477. this._moveTeleportationSelectorTo(hit, gazer);
  83478. }
  83479. return;
  83480. }
  83481. // If not, we're in a selection scenario
  83482. //this._teleportationAllowed = false;
  83483. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83484. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83485. this.onNewMeshPicked.notifyObservers(hit);
  83486. gazer._currentMeshSelected = hit.pickedMesh;
  83487. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83488. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83489. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83490. gazer._isActionableMesh = true;
  83491. }
  83492. else {
  83493. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83494. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83495. gazer._isActionableMesh = false;
  83496. }
  83497. try {
  83498. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83499. }
  83500. catch (err) {
  83501. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83502. }
  83503. }
  83504. else {
  83505. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83506. gazer._currentMeshSelected = null;
  83507. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83508. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83509. }
  83510. }
  83511. }
  83512. else {
  83513. gazer._currentHit = null;
  83514. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83515. gazer._currentMeshSelected = null;
  83516. //this._teleportationAllowed = false;
  83517. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83518. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83519. }
  83520. };
  83521. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83522. if (mesh) {
  83523. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83524. }
  83525. };
  83526. /**
  83527. * Sets the color of the laser ray from the vr controllers.
  83528. * @param color new color for the ray.
  83529. */
  83530. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83531. if (this.leftController) {
  83532. this.leftController._setLaserPointerColor(color);
  83533. }
  83534. if (this.rightController) {
  83535. this.rightController._setLaserPointerColor(color);
  83536. }
  83537. };
  83538. /**
  83539. * Sets the color of the ray from the vr headsets gaze.
  83540. * @param color new color for the ray.
  83541. */
  83542. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83543. if (!this._cameraGazer._gazeTracker.material) {
  83544. return;
  83545. }
  83546. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83547. if (this.leftController) {
  83548. this.leftController._gazeTracker.material.emissiveColor = color;
  83549. }
  83550. if (this.rightController) {
  83551. this.rightController._gazeTracker.material.emissiveColor = color;
  83552. }
  83553. };
  83554. /**
  83555. * Exits VR and disposes of the vr experience helper
  83556. */
  83557. VRExperienceHelper.prototype.dispose = function () {
  83558. if (this.isInVRMode) {
  83559. this.exitVR();
  83560. }
  83561. if (this._postProcessMove) {
  83562. this._postProcessMove.dispose();
  83563. }
  83564. if (this._webVRCamera) {
  83565. this._webVRCamera.dispose();
  83566. }
  83567. if (this._vrDeviceOrientationCamera) {
  83568. this._vrDeviceOrientationCamera.dispose();
  83569. }
  83570. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83571. document.body.removeChild(this._btnVR);
  83572. }
  83573. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83574. this._deviceOrientationCamera.dispose();
  83575. }
  83576. if (this._cameraGazer) {
  83577. this._cameraGazer.dispose();
  83578. }
  83579. if (this.leftController) {
  83580. this.leftController.dispose();
  83581. }
  83582. if (this.rightController) {
  83583. this.rightController.dispose();
  83584. }
  83585. if (this._teleportationTarget) {
  83586. this._teleportationTarget.dispose();
  83587. }
  83588. this._floorMeshesCollection = [];
  83589. document.removeEventListener("keydown", this._onKeyDown);
  83590. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83591. window.removeEventListener("resize", this._onResize);
  83592. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83593. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83594. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83595. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83596. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83597. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83598. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83599. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83600. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83601. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83602. this._scene.unregisterBeforeRender(this.beforeRender);
  83603. };
  83604. /**
  83605. * Gets the name of the VRExperienceHelper class
  83606. * @returns "VRExperienceHelper"
  83607. */
  83608. VRExperienceHelper.prototype.getClassName = function () {
  83609. return "VRExperienceHelper";
  83610. };
  83611. return VRExperienceHelper;
  83612. }());
  83613. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83614. })(BABYLON || (BABYLON = {}));
  83615. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83616. // Mainly based on these 2 articles :
  83617. // 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
  83618. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83619. var BABYLON;
  83620. (function (BABYLON) {
  83621. var JoystickAxis;
  83622. (function (JoystickAxis) {
  83623. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83624. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83625. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83626. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83627. var VirtualJoystick = /** @class */ (function () {
  83628. function VirtualJoystick(leftJoystick) {
  83629. var _this = this;
  83630. if (leftJoystick) {
  83631. this._leftJoystick = true;
  83632. }
  83633. else {
  83634. this._leftJoystick = false;
  83635. }
  83636. VirtualJoystick._globalJoystickIndex++;
  83637. // By default left & right arrow keys are moving the X
  83638. // and up & down keys are moving the Y
  83639. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83640. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83641. this.reverseLeftRight = false;
  83642. this.reverseUpDown = false;
  83643. // collections of pointers
  83644. this._touches = new BABYLON.StringDictionary();
  83645. this.deltaPosition = BABYLON.Vector3.Zero();
  83646. this._joystickSensibility = 25;
  83647. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83648. this._onResize = function (evt) {
  83649. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83650. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83651. if (VirtualJoystick.vjCanvas) {
  83652. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83653. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83654. }
  83655. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83656. };
  83657. // injecting a canvas element on top of the canvas 3D game
  83658. if (!VirtualJoystick.vjCanvas) {
  83659. window.addEventListener("resize", this._onResize, false);
  83660. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83661. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83662. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83663. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83664. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83665. VirtualJoystick.vjCanvas.style.width = "100%";
  83666. VirtualJoystick.vjCanvas.style.height = "100%";
  83667. VirtualJoystick.vjCanvas.style.position = "absolute";
  83668. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83669. VirtualJoystick.vjCanvas.style.top = "0px";
  83670. VirtualJoystick.vjCanvas.style.left = "0px";
  83671. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83672. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83673. // Support for jQuery PEP polyfill
  83674. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83675. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83676. if (!context) {
  83677. throw new Error("Unable to create canvas for virtual joystick");
  83678. }
  83679. VirtualJoystick.vjCanvasContext = context;
  83680. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83681. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83682. document.body.appendChild(VirtualJoystick.vjCanvas);
  83683. }
  83684. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83685. this.pressed = false;
  83686. // default joystick color
  83687. this._joystickColor = "cyan";
  83688. this._joystickPointerID = -1;
  83689. // current joystick position
  83690. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83691. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83692. // origin joystick position
  83693. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83694. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83695. this._onPointerDownHandlerRef = function (evt) {
  83696. _this._onPointerDown(evt);
  83697. };
  83698. this._onPointerMoveHandlerRef = function (evt) {
  83699. _this._onPointerMove(evt);
  83700. };
  83701. this._onPointerUpHandlerRef = function (evt) {
  83702. _this._onPointerUp(evt);
  83703. };
  83704. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83705. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83706. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83707. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83708. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83709. evt.preventDefault(); // Disables system menu
  83710. }, false);
  83711. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83712. }
  83713. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83714. this._joystickSensibility = newJoystickSensibility;
  83715. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83716. };
  83717. VirtualJoystick.prototype._onPointerDown = function (e) {
  83718. var positionOnScreenCondition;
  83719. e.preventDefault();
  83720. if (this._leftJoystick === true) {
  83721. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  83722. }
  83723. else {
  83724. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  83725. }
  83726. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  83727. // First contact will be dedicated to the virtual joystick
  83728. this._joystickPointerID = e.pointerId;
  83729. this._joystickPointerStartPos.x = e.clientX;
  83730. this._joystickPointerStartPos.y = e.clientY;
  83731. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  83732. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  83733. this._deltaJoystickVector.x = 0;
  83734. this._deltaJoystickVector.y = 0;
  83735. this.pressed = true;
  83736. this._touches.add(e.pointerId.toString(), e);
  83737. }
  83738. else {
  83739. // You can only trigger the action buttons with a joystick declared
  83740. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  83741. this._action();
  83742. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  83743. }
  83744. }
  83745. };
  83746. VirtualJoystick.prototype._onPointerMove = function (e) {
  83747. // If the current pointer is the one associated to the joystick (first touch contact)
  83748. if (this._joystickPointerID == e.pointerId) {
  83749. this._joystickPointerPos.x = e.clientX;
  83750. this._joystickPointerPos.y = e.clientY;
  83751. this._deltaJoystickVector = this._joystickPointerPos.clone();
  83752. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  83753. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  83754. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83755. switch (this._axisTargetedByLeftAndRight) {
  83756. case JoystickAxis.X:
  83757. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83758. break;
  83759. case JoystickAxis.Y:
  83760. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83761. break;
  83762. case JoystickAxis.Z:
  83763. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83764. break;
  83765. }
  83766. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83767. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83768. switch (this._axisTargetedByUpAndDown) {
  83769. case JoystickAxis.X:
  83770. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83771. break;
  83772. case JoystickAxis.Y:
  83773. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83774. break;
  83775. case JoystickAxis.Z:
  83776. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83777. break;
  83778. }
  83779. }
  83780. else {
  83781. var data = this._touches.get(e.pointerId.toString());
  83782. if (data) {
  83783. data.x = e.clientX;
  83784. data.y = e.clientY;
  83785. }
  83786. }
  83787. };
  83788. VirtualJoystick.prototype._onPointerUp = function (e) {
  83789. if (this._joystickPointerID == e.pointerId) {
  83790. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  83791. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  83792. this._joystickPointerID = -1;
  83793. this.pressed = false;
  83794. }
  83795. else {
  83796. var touch = this._touches.get(e.pointerId.toString());
  83797. if (touch) {
  83798. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83799. }
  83800. }
  83801. this._deltaJoystickVector.x = 0;
  83802. this._deltaJoystickVector.y = 0;
  83803. this._touches.remove(e.pointerId.toString());
  83804. };
  83805. /**
  83806. * Change the color of the virtual joystick
  83807. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  83808. */
  83809. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  83810. this._joystickColor = newColor;
  83811. };
  83812. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  83813. this._action = action;
  83814. };
  83815. // Define which axis you'd like to control for left & right
  83816. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  83817. switch (axis) {
  83818. case JoystickAxis.X:
  83819. case JoystickAxis.Y:
  83820. case JoystickAxis.Z:
  83821. this._axisTargetedByLeftAndRight = axis;
  83822. break;
  83823. default:
  83824. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83825. break;
  83826. }
  83827. };
  83828. // Define which axis you'd like to control for up & down
  83829. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  83830. switch (axis) {
  83831. case JoystickAxis.X:
  83832. case JoystickAxis.Y:
  83833. case JoystickAxis.Z:
  83834. this._axisTargetedByUpAndDown = axis;
  83835. break;
  83836. default:
  83837. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83838. break;
  83839. }
  83840. };
  83841. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  83842. var _this = this;
  83843. if (this.pressed) {
  83844. this._touches.forEach(function (key, touch) {
  83845. if (touch.pointerId === _this._joystickPointerID) {
  83846. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  83847. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  83848. VirtualJoystick.vjCanvasContext.beginPath();
  83849. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83850. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83851. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  83852. VirtualJoystick.vjCanvasContext.stroke();
  83853. VirtualJoystick.vjCanvasContext.closePath();
  83854. VirtualJoystick.vjCanvasContext.beginPath();
  83855. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83856. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83857. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  83858. VirtualJoystick.vjCanvasContext.stroke();
  83859. VirtualJoystick.vjCanvasContext.closePath();
  83860. VirtualJoystick.vjCanvasContext.beginPath();
  83861. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83862. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  83863. VirtualJoystick.vjCanvasContext.stroke();
  83864. VirtualJoystick.vjCanvasContext.closePath();
  83865. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  83866. }
  83867. else {
  83868. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83869. VirtualJoystick.vjCanvasContext.beginPath();
  83870. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  83871. VirtualJoystick.vjCanvasContext.beginPath();
  83872. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  83873. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83874. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  83875. VirtualJoystick.vjCanvasContext.stroke();
  83876. VirtualJoystick.vjCanvasContext.closePath();
  83877. touch.prevX = touch.x;
  83878. touch.prevY = touch.y;
  83879. }
  83880. ;
  83881. });
  83882. }
  83883. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83884. };
  83885. VirtualJoystick.prototype.releaseCanvas = function () {
  83886. if (VirtualJoystick.vjCanvas) {
  83887. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  83888. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  83889. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  83890. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  83891. window.removeEventListener("resize", this._onResize);
  83892. document.body.removeChild(VirtualJoystick.vjCanvas);
  83893. VirtualJoystick.vjCanvas = null;
  83894. }
  83895. };
  83896. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  83897. VirtualJoystick._globalJoystickIndex = 0;
  83898. return VirtualJoystick;
  83899. }());
  83900. BABYLON.VirtualJoystick = VirtualJoystick;
  83901. })(BABYLON || (BABYLON = {}));
  83902. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83903. var BABYLON;
  83904. (function (BABYLON) {
  83905. // We're mainly based on the logic defined into the FreeCamera code
  83906. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83907. __extends(VirtualJoysticksCamera, _super);
  83908. function VirtualJoysticksCamera(name, position, scene) {
  83909. var _this = _super.call(this, name, position, scene) || this;
  83910. _this.inputs.addVirtualJoystick();
  83911. return _this;
  83912. }
  83913. VirtualJoysticksCamera.prototype.getClassName = function () {
  83914. return "VirtualJoysticksCamera";
  83915. };
  83916. return VirtualJoysticksCamera;
  83917. }(BABYLON.FreeCamera));
  83918. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83919. })(BABYLON || (BABYLON = {}));
  83920. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83921. var BABYLON;
  83922. (function (BABYLON) {
  83923. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83924. function FreeCameraVirtualJoystickInput() {
  83925. }
  83926. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83927. return this._leftjoystick;
  83928. };
  83929. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83930. return this._rightjoystick;
  83931. };
  83932. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83933. if (this._leftjoystick) {
  83934. var camera = this.camera;
  83935. var speed = camera._computeLocalCameraSpeed() * 50;
  83936. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83937. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83938. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83939. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83940. if (!this._leftjoystick.pressed) {
  83941. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83942. }
  83943. if (!this._rightjoystick.pressed) {
  83944. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83945. }
  83946. }
  83947. };
  83948. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83949. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83950. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83951. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83952. this._leftjoystick.setJoystickSensibility(0.15);
  83953. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83954. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83955. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83956. this._rightjoystick.reverseUpDown = true;
  83957. this._rightjoystick.setJoystickSensibility(0.05);
  83958. this._rightjoystick.setJoystickColor("yellow");
  83959. };
  83960. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83961. this._leftjoystick.releaseCanvas();
  83962. this._rightjoystick.releaseCanvas();
  83963. };
  83964. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83965. return "FreeCameraVirtualJoystickInput";
  83966. };
  83967. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83968. return "virtualJoystick";
  83969. };
  83970. return FreeCameraVirtualJoystickInput;
  83971. }());
  83972. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83973. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83974. })(BABYLON || (BABYLON = {}));
  83975. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83976. var BABYLON;
  83977. (function (BABYLON) {
  83978. var SimplificationSettings = /** @class */ (function () {
  83979. function SimplificationSettings(quality, distance, optimizeMesh) {
  83980. this.quality = quality;
  83981. this.distance = distance;
  83982. this.optimizeMesh = optimizeMesh;
  83983. }
  83984. return SimplificationSettings;
  83985. }());
  83986. BABYLON.SimplificationSettings = SimplificationSettings;
  83987. var SimplificationQueue = /** @class */ (function () {
  83988. function SimplificationQueue() {
  83989. this.running = false;
  83990. this._simplificationArray = [];
  83991. }
  83992. SimplificationQueue.prototype.addTask = function (task) {
  83993. this._simplificationArray.push(task);
  83994. };
  83995. SimplificationQueue.prototype.executeNext = function () {
  83996. var task = this._simplificationArray.pop();
  83997. if (task) {
  83998. this.running = true;
  83999. this.runSimplification(task);
  84000. }
  84001. else {
  84002. this.running = false;
  84003. }
  84004. };
  84005. SimplificationQueue.prototype.runSimplification = function (task) {
  84006. var _this = this;
  84007. if (task.parallelProcessing) {
  84008. //parallel simplifier
  84009. task.settings.forEach(function (setting) {
  84010. var simplifier = _this.getSimplifier(task);
  84011. simplifier.simplify(setting, function (newMesh) {
  84012. task.mesh.addLODLevel(setting.distance, newMesh);
  84013. newMesh.isVisible = true;
  84014. //check if it is the last
  84015. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84016. //all done, run the success callback.
  84017. task.successCallback();
  84018. }
  84019. _this.executeNext();
  84020. });
  84021. });
  84022. }
  84023. else {
  84024. //single simplifier.
  84025. var simplifier = this.getSimplifier(task);
  84026. var runDecimation = function (setting, callback) {
  84027. simplifier.simplify(setting, function (newMesh) {
  84028. task.mesh.addLODLevel(setting.distance, newMesh);
  84029. newMesh.isVisible = true;
  84030. //run the next quality level
  84031. callback();
  84032. });
  84033. };
  84034. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84035. runDecimation(task.settings[loop.index], function () {
  84036. loop.executeNext();
  84037. });
  84038. }, function () {
  84039. //execution ended, run the success callback.
  84040. if (task.successCallback) {
  84041. task.successCallback();
  84042. }
  84043. _this.executeNext();
  84044. });
  84045. }
  84046. };
  84047. SimplificationQueue.prototype.getSimplifier = function (task) {
  84048. switch (task.simplificationType) {
  84049. case SimplificationType.QUADRATIC:
  84050. default:
  84051. return new QuadraticErrorSimplification(task.mesh);
  84052. }
  84053. };
  84054. return SimplificationQueue;
  84055. }());
  84056. BABYLON.SimplificationQueue = SimplificationQueue;
  84057. /**
  84058. * The implemented types of simplification.
  84059. * At the moment only Quadratic Error Decimation is implemented.
  84060. */
  84061. var SimplificationType;
  84062. (function (SimplificationType) {
  84063. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84064. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84065. var DecimationTriangle = /** @class */ (function () {
  84066. function DecimationTriangle(vertices) {
  84067. this.vertices = vertices;
  84068. this.error = new Array(4);
  84069. this.deleted = false;
  84070. this.isDirty = false;
  84071. this.deletePending = false;
  84072. this.borderFactor = 0;
  84073. }
  84074. return DecimationTriangle;
  84075. }());
  84076. BABYLON.DecimationTriangle = DecimationTriangle;
  84077. var DecimationVertex = /** @class */ (function () {
  84078. function DecimationVertex(position, id) {
  84079. this.position = position;
  84080. this.id = id;
  84081. this.isBorder = true;
  84082. this.q = new QuadraticMatrix();
  84083. this.triangleCount = 0;
  84084. this.triangleStart = 0;
  84085. this.originalOffsets = [];
  84086. }
  84087. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84088. this.position.copyFrom(newPosition);
  84089. };
  84090. return DecimationVertex;
  84091. }());
  84092. BABYLON.DecimationVertex = DecimationVertex;
  84093. var QuadraticMatrix = /** @class */ (function () {
  84094. function QuadraticMatrix(data) {
  84095. this.data = new Array(10);
  84096. for (var i = 0; i < 10; ++i) {
  84097. if (data && data[i]) {
  84098. this.data[i] = data[i];
  84099. }
  84100. else {
  84101. this.data[i] = 0;
  84102. }
  84103. }
  84104. }
  84105. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84106. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84107. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84108. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84109. return det;
  84110. };
  84111. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84112. for (var i = 0; i < 10; ++i) {
  84113. this.data[i] += matrix.data[i];
  84114. }
  84115. };
  84116. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84117. for (var i = 0; i < 10; ++i) {
  84118. this.data[i] += data[i];
  84119. }
  84120. };
  84121. QuadraticMatrix.prototype.add = function (matrix) {
  84122. var m = new QuadraticMatrix();
  84123. for (var i = 0; i < 10; ++i) {
  84124. m.data[i] = this.data[i] + matrix.data[i];
  84125. }
  84126. return m;
  84127. };
  84128. QuadraticMatrix.FromData = function (a, b, c, d) {
  84129. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84130. };
  84131. //returning an array to avoid garbage collection
  84132. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84133. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84134. };
  84135. return QuadraticMatrix;
  84136. }());
  84137. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84138. var Reference = /** @class */ (function () {
  84139. function Reference(vertexId, triangleId) {
  84140. this.vertexId = vertexId;
  84141. this.triangleId = triangleId;
  84142. }
  84143. return Reference;
  84144. }());
  84145. BABYLON.Reference = Reference;
  84146. /**
  84147. * An implementation of the Quadratic Error simplification algorithm.
  84148. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84149. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84150. * @author RaananW
  84151. */
  84152. var QuadraticErrorSimplification = /** @class */ (function () {
  84153. function QuadraticErrorSimplification(_mesh) {
  84154. this._mesh = _mesh;
  84155. this.syncIterations = 5000;
  84156. this.aggressiveness = 7;
  84157. this.decimationIterations = 100;
  84158. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84159. }
  84160. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84161. var _this = this;
  84162. this.initDecimatedMesh();
  84163. //iterating through the submeshes array, one after the other.
  84164. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84165. _this.initWithMesh(loop.index, function () {
  84166. _this.runDecimation(settings, loop.index, function () {
  84167. loop.executeNext();
  84168. });
  84169. }, settings.optimizeMesh);
  84170. }, function () {
  84171. setTimeout(function () {
  84172. successCallback(_this._reconstructedMesh);
  84173. }, 0);
  84174. });
  84175. };
  84176. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84177. var _this = this;
  84178. var targetCount = ~~(this.triangles.length * settings.quality);
  84179. var deletedTriangles = 0;
  84180. var triangleCount = this.triangles.length;
  84181. var iterationFunction = function (iteration, callback) {
  84182. setTimeout(function () {
  84183. if (iteration % 5 === 0) {
  84184. _this.updateMesh(iteration === 0);
  84185. }
  84186. for (var i = 0; i < _this.triangles.length; ++i) {
  84187. _this.triangles[i].isDirty = false;
  84188. }
  84189. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84190. var trianglesIterator = function (i) {
  84191. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84192. var t = _this.triangles[tIdx];
  84193. if (!t)
  84194. return;
  84195. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84196. return;
  84197. }
  84198. for (var j = 0; j < 3; ++j) {
  84199. if (t.error[j] < threshold) {
  84200. var deleted0 = [];
  84201. var deleted1 = [];
  84202. var v0 = t.vertices[j];
  84203. var v1 = t.vertices[(j + 1) % 3];
  84204. if (v0.isBorder || v1.isBorder)
  84205. continue;
  84206. var p = BABYLON.Vector3.Zero();
  84207. var n = BABYLON.Vector3.Zero();
  84208. var uv = BABYLON.Vector2.Zero();
  84209. var color = new BABYLON.Color4(0, 0, 0, 1);
  84210. _this.calculateError(v0, v1, p, n, uv, color);
  84211. var delTr = new Array();
  84212. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84213. continue;
  84214. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84215. continue;
  84216. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84217. continue;
  84218. var uniqueArray = new Array();
  84219. delTr.forEach(function (deletedT) {
  84220. if (uniqueArray.indexOf(deletedT) === -1) {
  84221. deletedT.deletePending = true;
  84222. uniqueArray.push(deletedT);
  84223. }
  84224. });
  84225. if (uniqueArray.length % 2 !== 0) {
  84226. continue;
  84227. }
  84228. v0.q = v1.q.add(v0.q);
  84229. v0.updatePosition(p);
  84230. var tStart = _this.references.length;
  84231. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84232. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84233. var tCount = _this.references.length - tStart;
  84234. if (tCount <= v0.triangleCount) {
  84235. if (tCount) {
  84236. for (var c = 0; c < tCount; c++) {
  84237. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84238. }
  84239. }
  84240. }
  84241. else {
  84242. v0.triangleStart = tStart;
  84243. }
  84244. v0.triangleCount = tCount;
  84245. break;
  84246. }
  84247. }
  84248. };
  84249. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84250. }, 0);
  84251. };
  84252. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84253. if (triangleCount - deletedTriangles <= targetCount)
  84254. loop.breakLoop();
  84255. else {
  84256. iterationFunction(loop.index, function () {
  84257. loop.executeNext();
  84258. });
  84259. }
  84260. }, function () {
  84261. setTimeout(function () {
  84262. //reconstruct this part of the mesh
  84263. _this.reconstructMesh(submeshIndex);
  84264. successCallback();
  84265. }, 0);
  84266. });
  84267. };
  84268. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84269. var _this = this;
  84270. this.vertices = [];
  84271. this.triangles = [];
  84272. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84273. var indices = this._mesh.getIndices();
  84274. var submesh = this._mesh.subMeshes[submeshIndex];
  84275. var findInVertices = function (positionToSearch) {
  84276. if (optimizeMesh) {
  84277. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84278. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84279. return _this.vertices[ii];
  84280. }
  84281. }
  84282. }
  84283. return null;
  84284. };
  84285. var vertexReferences = [];
  84286. var vertexInit = function (i) {
  84287. if (!positionData) {
  84288. return;
  84289. }
  84290. var offset = i + submesh.verticesStart;
  84291. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84292. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84293. vertex.originalOffsets.push(offset);
  84294. if (vertex.id === _this.vertices.length) {
  84295. _this.vertices.push(vertex);
  84296. }
  84297. vertexReferences.push(vertex.id);
  84298. };
  84299. //var totalVertices = mesh.getTotalVertices();
  84300. var totalVertices = submesh.verticesCount;
  84301. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84302. var indicesInit = function (i) {
  84303. if (!indices) {
  84304. return;
  84305. }
  84306. var offset = (submesh.indexStart / 3) + i;
  84307. var pos = (offset * 3);
  84308. var i0 = indices[pos + 0];
  84309. var i1 = indices[pos + 1];
  84310. var i2 = indices[pos + 2];
  84311. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84312. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84313. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84314. var triangle = new DecimationTriangle([v0, v1, v2]);
  84315. triangle.originalOffset = pos;
  84316. _this.triangles.push(triangle);
  84317. };
  84318. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84319. _this.init(callback);
  84320. });
  84321. });
  84322. };
  84323. QuadraticErrorSimplification.prototype.init = function (callback) {
  84324. var _this = this;
  84325. var triangleInit1 = function (i) {
  84326. var t = _this.triangles[i];
  84327. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84328. for (var j = 0; j < 3; j++) {
  84329. 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))));
  84330. }
  84331. };
  84332. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84333. var triangleInit2 = function (i) {
  84334. var t = _this.triangles[i];
  84335. for (var j = 0; j < 3; ++j) {
  84336. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84337. }
  84338. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84339. };
  84340. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84341. callback();
  84342. });
  84343. });
  84344. };
  84345. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84346. var newTriangles = [];
  84347. var i;
  84348. for (i = 0; i < this.vertices.length; ++i) {
  84349. this.vertices[i].triangleCount = 0;
  84350. }
  84351. var t;
  84352. var j;
  84353. for (i = 0; i < this.triangles.length; ++i) {
  84354. if (!this.triangles[i].deleted) {
  84355. t = this.triangles[i];
  84356. for (j = 0; j < 3; ++j) {
  84357. t.vertices[j].triangleCount = 1;
  84358. }
  84359. newTriangles.push(t);
  84360. }
  84361. }
  84362. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84363. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84364. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84365. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84366. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84367. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84368. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84369. var vertexCount = 0;
  84370. for (i = 0; i < this.vertices.length; ++i) {
  84371. var vertex = this.vertices[i];
  84372. vertex.id = vertexCount;
  84373. if (vertex.triangleCount) {
  84374. vertex.originalOffsets.forEach(function (originalOffset) {
  84375. if (!normalData) {
  84376. return;
  84377. }
  84378. newPositionData.push(vertex.position.x);
  84379. newPositionData.push(vertex.position.y);
  84380. newPositionData.push(vertex.position.z);
  84381. newNormalData.push(normalData[originalOffset * 3]);
  84382. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84383. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84384. if (uvs && uvs.length) {
  84385. newUVsData.push(uvs[(originalOffset * 2)]);
  84386. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84387. }
  84388. else if (colorsData && colorsData.length) {
  84389. newColorsData.push(colorsData[(originalOffset * 4)]);
  84390. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84391. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84392. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84393. }
  84394. ++vertexCount;
  84395. });
  84396. }
  84397. }
  84398. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84399. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84400. var submeshesArray = this._reconstructedMesh.subMeshes;
  84401. this._reconstructedMesh.subMeshes = [];
  84402. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84403. var originalIndices = this._mesh.getIndices();
  84404. for (i = 0; i < newTriangles.length; ++i) {
  84405. t = newTriangles[i]; //now get the new referencing point for each vertex
  84406. [0, 1, 2].forEach(function (idx) {
  84407. var id = originalIndices[t.originalOffset + idx];
  84408. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84409. if (offset < 0)
  84410. offset = 0;
  84411. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84412. });
  84413. }
  84414. //overwriting the old vertex buffers and indices.
  84415. this._reconstructedMesh.setIndices(newIndicesArray);
  84416. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84417. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84418. if (newUVsData.length > 0)
  84419. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84420. if (newColorsData.length > 0)
  84421. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84422. //create submesh
  84423. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84424. if (submeshIndex > 0) {
  84425. this._reconstructedMesh.subMeshes = [];
  84426. submeshesArray.forEach(function (submesh) {
  84427. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84428. });
  84429. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84430. }
  84431. };
  84432. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84433. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84434. this._reconstructedMesh.material = this._mesh.material;
  84435. this._reconstructedMesh.parent = this._mesh.parent;
  84436. this._reconstructedMesh.isVisible = false;
  84437. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84438. };
  84439. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84440. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84441. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84442. if (t.deleted)
  84443. continue;
  84444. var s = this.references[vertex1.triangleStart + i].vertexId;
  84445. var v1 = t.vertices[(s + 1) % 3];
  84446. var v2 = t.vertices[(s + 2) % 3];
  84447. if ((v1 === vertex2 || v2 === vertex2)) {
  84448. deletedArray[i] = true;
  84449. delTr.push(t);
  84450. continue;
  84451. }
  84452. var d1 = v1.position.subtract(point);
  84453. d1 = d1.normalize();
  84454. var d2 = v2.position.subtract(point);
  84455. d2 = d2.normalize();
  84456. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84457. return true;
  84458. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84459. deletedArray[i] = false;
  84460. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84461. return true;
  84462. }
  84463. return false;
  84464. };
  84465. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84466. var newDeleted = deletedTriangles;
  84467. for (var i = 0; i < vertex.triangleCount; ++i) {
  84468. var ref = this.references[vertex.triangleStart + i];
  84469. var t = this.triangles[ref.triangleId];
  84470. if (t.deleted)
  84471. continue;
  84472. if (deletedArray[i] && t.deletePending) {
  84473. t.deleted = true;
  84474. newDeleted++;
  84475. continue;
  84476. }
  84477. t.vertices[ref.vertexId] = origVertex;
  84478. t.isDirty = true;
  84479. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84480. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84481. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84482. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84483. this.references.push(ref);
  84484. }
  84485. return newDeleted;
  84486. };
  84487. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84488. for (var i = 0; i < this.vertices.length; ++i) {
  84489. var vCount = [];
  84490. var vId = [];
  84491. var v = this.vertices[i];
  84492. var j;
  84493. for (j = 0; j < v.triangleCount; ++j) {
  84494. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84495. for (var ii = 0; ii < 3; ii++) {
  84496. var ofs = 0;
  84497. var vv = triangle.vertices[ii];
  84498. while (ofs < vCount.length) {
  84499. if (vId[ofs] === vv.id)
  84500. break;
  84501. ++ofs;
  84502. }
  84503. if (ofs === vCount.length) {
  84504. vCount.push(1);
  84505. vId.push(vv.id);
  84506. }
  84507. else {
  84508. vCount[ofs]++;
  84509. }
  84510. }
  84511. }
  84512. for (j = 0; j < vCount.length; ++j) {
  84513. if (vCount[j] === 1) {
  84514. this.vertices[vId[j]].isBorder = true;
  84515. }
  84516. else {
  84517. this.vertices[vId[j]].isBorder = false;
  84518. }
  84519. }
  84520. }
  84521. };
  84522. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84523. if (identifyBorders === void 0) { identifyBorders = false; }
  84524. var i;
  84525. if (!identifyBorders) {
  84526. var newTrianglesVector = [];
  84527. for (i = 0; i < this.triangles.length; ++i) {
  84528. if (!this.triangles[i].deleted) {
  84529. newTrianglesVector.push(this.triangles[i]);
  84530. }
  84531. }
  84532. this.triangles = newTrianglesVector;
  84533. }
  84534. for (i = 0; i < this.vertices.length; ++i) {
  84535. this.vertices[i].triangleCount = 0;
  84536. this.vertices[i].triangleStart = 0;
  84537. }
  84538. var t;
  84539. var j;
  84540. var v;
  84541. for (i = 0; i < this.triangles.length; ++i) {
  84542. t = this.triangles[i];
  84543. for (j = 0; j < 3; ++j) {
  84544. v = t.vertices[j];
  84545. v.triangleCount++;
  84546. }
  84547. }
  84548. var tStart = 0;
  84549. for (i = 0; i < this.vertices.length; ++i) {
  84550. this.vertices[i].triangleStart = tStart;
  84551. tStart += this.vertices[i].triangleCount;
  84552. this.vertices[i].triangleCount = 0;
  84553. }
  84554. var newReferences = new Array(this.triangles.length * 3);
  84555. for (i = 0; i < this.triangles.length; ++i) {
  84556. t = this.triangles[i];
  84557. for (j = 0; j < 3; ++j) {
  84558. v = t.vertices[j];
  84559. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84560. v.triangleCount++;
  84561. }
  84562. }
  84563. this.references = newReferences;
  84564. if (identifyBorders) {
  84565. this.identifyBorder();
  84566. }
  84567. };
  84568. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84569. var x = point.x;
  84570. var y = point.y;
  84571. var z = point.z;
  84572. 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
  84573. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84574. };
  84575. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84576. var q = vertex1.q.add(vertex2.q);
  84577. var border = vertex1.isBorder && vertex2.isBorder;
  84578. var error = 0;
  84579. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84580. if (qDet !== 0 && !border) {
  84581. if (!pointResult) {
  84582. pointResult = BABYLON.Vector3.Zero();
  84583. }
  84584. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84585. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84586. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84587. error = this.vertexError(q, pointResult);
  84588. }
  84589. else {
  84590. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84591. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84592. var error1 = this.vertexError(q, vertex1.position);
  84593. var error2 = this.vertexError(q, vertex2.position);
  84594. var error3 = this.vertexError(q, p3);
  84595. error = Math.min(error1, error2, error3);
  84596. if (error === error1) {
  84597. if (pointResult) {
  84598. pointResult.copyFrom(vertex1.position);
  84599. }
  84600. }
  84601. else if (error === error2) {
  84602. if (pointResult) {
  84603. pointResult.copyFrom(vertex2.position);
  84604. }
  84605. }
  84606. else {
  84607. if (pointResult) {
  84608. pointResult.copyFrom(p3);
  84609. }
  84610. }
  84611. }
  84612. return error;
  84613. };
  84614. return QuadraticErrorSimplification;
  84615. }());
  84616. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84617. })(BABYLON || (BABYLON = {}));
  84618. //# sourceMappingURL=babylon.meshSimplification.js.map
  84619. var BABYLON;
  84620. (function (BABYLON) {
  84621. var MeshLODLevel = /** @class */ (function () {
  84622. function MeshLODLevel(distance, mesh) {
  84623. this.distance = distance;
  84624. this.mesh = mesh;
  84625. }
  84626. return MeshLODLevel;
  84627. }());
  84628. BABYLON.MeshLODLevel = MeshLODLevel;
  84629. })(BABYLON || (BABYLON = {}));
  84630. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84631. var BABYLON;
  84632. (function (BABYLON) {
  84633. /**
  84634. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84635. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84636. */
  84637. var SceneOptimization = /** @class */ (function () {
  84638. /**
  84639. * Creates the SceneOptimization object
  84640. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84641. * @param desc defines the description associated with the optimization
  84642. */
  84643. function SceneOptimization(
  84644. /**
  84645. * Defines the priority of this optimization (0 by default which means first in the list)
  84646. */
  84647. priority) {
  84648. if (priority === void 0) { priority = 0; }
  84649. this.priority = priority;
  84650. }
  84651. /**
  84652. * Gets a string describing the action executed by the current optimization
  84653. * @returns description string
  84654. */
  84655. SceneOptimization.prototype.getDescription = function () {
  84656. return "";
  84657. };
  84658. /**
  84659. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84660. * @param scene defines the current scene where to apply this optimization
  84661. * @param optimizer defines the current optimizer
  84662. * @returns true if everything that can be done was applied
  84663. */
  84664. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84665. return true;
  84666. };
  84667. ;
  84668. return SceneOptimization;
  84669. }());
  84670. BABYLON.SceneOptimization = SceneOptimization;
  84671. /**
  84672. * Defines an optimization used to reduce the size of render target textures
  84673. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84674. */
  84675. var TextureOptimization = /** @class */ (function (_super) {
  84676. __extends(TextureOptimization, _super);
  84677. /**
  84678. * Creates the TextureOptimization object
  84679. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84680. * @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
  84681. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84682. */
  84683. function TextureOptimization(
  84684. /**
  84685. * Defines the priority of this optimization (0 by default which means first in the list)
  84686. */
  84687. priority,
  84688. /**
  84689. * 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
  84690. */
  84691. maximumSize,
  84692. /**
  84693. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84694. */
  84695. step) {
  84696. if (priority === void 0) { priority = 0; }
  84697. if (maximumSize === void 0) { maximumSize = 1024; }
  84698. if (step === void 0) { step = 0.5; }
  84699. var _this = _super.call(this, priority) || this;
  84700. _this.priority = priority;
  84701. _this.maximumSize = maximumSize;
  84702. _this.step = step;
  84703. return _this;
  84704. }
  84705. /**
  84706. * Gets a string describing the action executed by the current optimization
  84707. * @returns description string
  84708. */
  84709. TextureOptimization.prototype.getDescription = function () {
  84710. return "Reducing render target texture size to " + this.maximumSize;
  84711. };
  84712. /**
  84713. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84714. * @param scene defines the current scene where to apply this optimization
  84715. * @param optimizer defines the current optimizer
  84716. * @returns true if everything that can be done was applied
  84717. */
  84718. TextureOptimization.prototype.apply = function (scene, optimizer) {
  84719. var allDone = true;
  84720. for (var index = 0; index < scene.textures.length; index++) {
  84721. var texture = scene.textures[index];
  84722. if (!texture.canRescale || texture.getContext) {
  84723. continue;
  84724. }
  84725. var currentSize = texture.getSize();
  84726. var maxDimension = Math.max(currentSize.width, currentSize.height);
  84727. if (maxDimension > this.maximumSize) {
  84728. texture.scale(this.step);
  84729. allDone = false;
  84730. }
  84731. }
  84732. return allDone;
  84733. };
  84734. return TextureOptimization;
  84735. }(SceneOptimization));
  84736. BABYLON.TextureOptimization = TextureOptimization;
  84737. /**
  84738. * Defines an optimization used to increase or decrease the rendering resolution
  84739. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84740. */
  84741. var HardwareScalingOptimization = /** @class */ (function (_super) {
  84742. __extends(HardwareScalingOptimization, _super);
  84743. /**
  84744. * Creates the HardwareScalingOptimization object
  84745. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84746. * @param maximumScale defines the maximum scale to use (2 by default)
  84747. * @param step defines the step to use between two passes (0.5 by default)
  84748. */
  84749. function HardwareScalingOptimization(
  84750. /**
  84751. * Defines the priority of this optimization (0 by default which means first in the list)
  84752. */
  84753. priority,
  84754. /**
  84755. * Defines the maximum scale to use (2 by default)
  84756. */
  84757. maximumScale,
  84758. /**
  84759. * Defines the step to use between two passes (0.5 by default)
  84760. */
  84761. step) {
  84762. if (priority === void 0) { priority = 0; }
  84763. if (maximumScale === void 0) { maximumScale = 2; }
  84764. if (step === void 0) { step = 0.25; }
  84765. var _this = _super.call(this, priority) || this;
  84766. _this.priority = priority;
  84767. _this.maximumScale = maximumScale;
  84768. _this.step = step;
  84769. _this._currentScale = -1;
  84770. _this._directionOffset = 1;
  84771. return _this;
  84772. }
  84773. /**
  84774. * Gets a string describing the action executed by the current optimization
  84775. * @return description string
  84776. */
  84777. HardwareScalingOptimization.prototype.getDescription = function () {
  84778. return "Setting hardware scaling level to " + this._currentScale;
  84779. };
  84780. /**
  84781. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84782. * @param scene defines the current scene where to apply this optimization
  84783. * @param optimizer defines the current optimizer
  84784. * @returns true if everything that can be done was applied
  84785. */
  84786. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  84787. if (this._currentScale === -1) {
  84788. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  84789. if (this._currentScale > this.maximumScale) {
  84790. this._directionOffset = -1;
  84791. }
  84792. }
  84793. this._currentScale += this._directionOffset * this.step;
  84794. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  84795. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  84796. };
  84797. ;
  84798. return HardwareScalingOptimization;
  84799. }(SceneOptimization));
  84800. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  84801. /**
  84802. * Defines an optimization used to remove shadows
  84803. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84804. */
  84805. var ShadowsOptimization = /** @class */ (function (_super) {
  84806. __extends(ShadowsOptimization, _super);
  84807. function ShadowsOptimization() {
  84808. return _super !== null && _super.apply(this, arguments) || this;
  84809. }
  84810. /**
  84811. * Gets a string describing the action executed by the current optimization
  84812. * @return description string
  84813. */
  84814. ShadowsOptimization.prototype.getDescription = function () {
  84815. return "Turning shadows on/off";
  84816. };
  84817. /**
  84818. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84819. * @param scene defines the current scene where to apply this optimization
  84820. * @param optimizer defines the current optimizer
  84821. * @returns true if everything that can be done was applied
  84822. */
  84823. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  84824. scene.shadowsEnabled = optimizer.isInImprovementMode;
  84825. return true;
  84826. };
  84827. ;
  84828. return ShadowsOptimization;
  84829. }(SceneOptimization));
  84830. BABYLON.ShadowsOptimization = ShadowsOptimization;
  84831. /**
  84832. * Defines an optimization used to turn post-processes off
  84833. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84834. */
  84835. var PostProcessesOptimization = /** @class */ (function (_super) {
  84836. __extends(PostProcessesOptimization, _super);
  84837. function PostProcessesOptimization() {
  84838. return _super !== null && _super.apply(this, arguments) || this;
  84839. }
  84840. /**
  84841. * Gets a string describing the action executed by the current optimization
  84842. * @return description string
  84843. */
  84844. PostProcessesOptimization.prototype.getDescription = function () {
  84845. return "Turning post-processes on/off";
  84846. };
  84847. /**
  84848. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84849. * @param scene defines the current scene where to apply this optimization
  84850. * @param optimizer defines the current optimizer
  84851. * @returns true if everything that can be done was applied
  84852. */
  84853. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  84854. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  84855. return true;
  84856. };
  84857. ;
  84858. return PostProcessesOptimization;
  84859. }(SceneOptimization));
  84860. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  84861. /**
  84862. * Defines an optimization used to turn lens flares off
  84863. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84864. */
  84865. var LensFlaresOptimization = /** @class */ (function (_super) {
  84866. __extends(LensFlaresOptimization, _super);
  84867. function LensFlaresOptimization() {
  84868. return _super !== null && _super.apply(this, arguments) || this;
  84869. }
  84870. /**
  84871. * Gets a string describing the action executed by the current optimization
  84872. * @return description string
  84873. */
  84874. LensFlaresOptimization.prototype.getDescription = function () {
  84875. return "Turning lens flares on/off";
  84876. };
  84877. /**
  84878. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84879. * @param scene defines the current scene where to apply this optimization
  84880. * @param optimizer defines the current optimizer
  84881. * @returns true if everything that can be done was applied
  84882. */
  84883. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  84884. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  84885. return true;
  84886. };
  84887. ;
  84888. return LensFlaresOptimization;
  84889. }(SceneOptimization));
  84890. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  84891. /**
  84892. * Defines an optimization based on user defined callback.
  84893. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84894. */
  84895. var CustomOptimization = /** @class */ (function (_super) {
  84896. __extends(CustomOptimization, _super);
  84897. function CustomOptimization() {
  84898. return _super !== null && _super.apply(this, arguments) || this;
  84899. }
  84900. /**
  84901. * Gets a string describing the action executed by the current optimization
  84902. * @returns description string
  84903. */
  84904. CustomOptimization.prototype.getDescription = function () {
  84905. if (this.onGetDescription) {
  84906. return this.onGetDescription();
  84907. }
  84908. return "Running user defined callback";
  84909. };
  84910. /**
  84911. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84912. * @param scene defines the current scene where to apply this optimization
  84913. * @param optimizer defines the current optimizer
  84914. * @returns true if everything that can be done was applied
  84915. */
  84916. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84917. if (this.onApply) {
  84918. return this.onApply(scene, optimizer);
  84919. }
  84920. return true;
  84921. };
  84922. ;
  84923. return CustomOptimization;
  84924. }(SceneOptimization));
  84925. BABYLON.CustomOptimization = CustomOptimization;
  84926. /**
  84927. * Defines an optimization used to turn particles off
  84928. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84929. */
  84930. var ParticlesOptimization = /** @class */ (function (_super) {
  84931. __extends(ParticlesOptimization, _super);
  84932. function ParticlesOptimization() {
  84933. return _super !== null && _super.apply(this, arguments) || this;
  84934. }
  84935. /**
  84936. * Gets a string describing the action executed by the current optimization
  84937. * @return description string
  84938. */
  84939. ParticlesOptimization.prototype.getDescription = function () {
  84940. return "Turning particles on/off";
  84941. };
  84942. /**
  84943. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84944. * @param scene defines the current scene where to apply this optimization
  84945. * @param optimizer defines the current optimizer
  84946. * @returns true if everything that can be done was applied
  84947. */
  84948. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84949. scene.particlesEnabled = optimizer.isInImprovementMode;
  84950. return true;
  84951. };
  84952. ;
  84953. return ParticlesOptimization;
  84954. }(SceneOptimization));
  84955. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84956. /**
  84957. * Defines an optimization used to turn render targets off
  84958. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84959. */
  84960. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84961. __extends(RenderTargetsOptimization, _super);
  84962. function RenderTargetsOptimization() {
  84963. return _super !== null && _super.apply(this, arguments) || this;
  84964. }
  84965. /**
  84966. * Gets a string describing the action executed by the current optimization
  84967. * @return description string
  84968. */
  84969. RenderTargetsOptimization.prototype.getDescription = function () {
  84970. return "Turning render targets off";
  84971. };
  84972. /**
  84973. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84974. * @param scene defines the current scene where to apply this optimization
  84975. * @param optimizer defines the current optimizer
  84976. * @returns true if everything that can be done was applied
  84977. */
  84978. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84979. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84980. return true;
  84981. };
  84982. ;
  84983. return RenderTargetsOptimization;
  84984. }(SceneOptimization));
  84985. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84986. /**
  84987. * Defines an optimization used to merge meshes with compatible materials
  84988. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84989. */
  84990. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84991. __extends(MergeMeshesOptimization, _super);
  84992. function MergeMeshesOptimization() {
  84993. var _this = _super !== null && _super.apply(this, arguments) || this;
  84994. _this._canBeMerged = function (abstractMesh) {
  84995. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84996. return false;
  84997. }
  84998. var mesh = abstractMesh;
  84999. if (!mesh.isVisible || !mesh.isEnabled()) {
  85000. return false;
  85001. }
  85002. if (mesh.instances.length > 0) {
  85003. return false;
  85004. }
  85005. if (mesh.skeleton || mesh.hasLODLevels) {
  85006. return false;
  85007. }
  85008. if (mesh.parent) {
  85009. return false;
  85010. }
  85011. return true;
  85012. };
  85013. return _this;
  85014. }
  85015. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85016. /**
  85017. * Gets or sets a boolean which defines if optimization octree has to be updated
  85018. */
  85019. get: function () {
  85020. return MergeMeshesOptimization._UpdateSelectionTree;
  85021. },
  85022. /**
  85023. * Gets or sets a boolean which defines if optimization octree has to be updated
  85024. */
  85025. set: function (value) {
  85026. MergeMeshesOptimization._UpdateSelectionTree = value;
  85027. },
  85028. enumerable: true,
  85029. configurable: true
  85030. });
  85031. /**
  85032. * Gets a string describing the action executed by the current optimization
  85033. * @return description string
  85034. */
  85035. MergeMeshesOptimization.prototype.getDescription = function () {
  85036. return "Merging similar meshes together";
  85037. };
  85038. /**
  85039. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85040. * @param scene defines the current scene where to apply this optimization
  85041. * @param optimizer defines the current optimizer
  85042. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85043. * @returns true if everything that can be done was applied
  85044. */
  85045. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85046. var globalPool = scene.meshes.slice(0);
  85047. var globalLength = globalPool.length;
  85048. for (var index = 0; index < globalLength; index++) {
  85049. var currentPool = new Array();
  85050. var current = globalPool[index];
  85051. // Checks
  85052. if (!this._canBeMerged(current)) {
  85053. continue;
  85054. }
  85055. currentPool.push(current);
  85056. // Find compatible meshes
  85057. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85058. var otherMesh = globalPool[subIndex];
  85059. if (!this._canBeMerged(otherMesh)) {
  85060. continue;
  85061. }
  85062. if (otherMesh.material !== current.material) {
  85063. continue;
  85064. }
  85065. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85066. continue;
  85067. }
  85068. currentPool.push(otherMesh);
  85069. globalLength--;
  85070. globalPool.splice(subIndex, 1);
  85071. subIndex--;
  85072. }
  85073. if (currentPool.length < 2) {
  85074. continue;
  85075. }
  85076. // Merge meshes
  85077. BABYLON.Mesh.MergeMeshes(currentPool);
  85078. }
  85079. if (updateSelectionTree != undefined) {
  85080. if (updateSelectionTree) {
  85081. scene.createOrUpdateSelectionOctree();
  85082. }
  85083. }
  85084. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85085. scene.createOrUpdateSelectionOctree();
  85086. }
  85087. return true;
  85088. };
  85089. ;
  85090. MergeMeshesOptimization._UpdateSelectionTree = false;
  85091. return MergeMeshesOptimization;
  85092. }(SceneOptimization));
  85093. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85094. /**
  85095. * Defines a list of options used by SceneOptimizer
  85096. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85097. */
  85098. var SceneOptimizerOptions = /** @class */ (function () {
  85099. /**
  85100. * Creates a new list of options used by SceneOptimizer
  85101. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85102. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85103. */
  85104. function SceneOptimizerOptions(
  85105. /**
  85106. * Defines the target frame rate to reach (60 by default)
  85107. */
  85108. targetFrameRate,
  85109. /**
  85110. * Defines the interval between two checkes (2000ms by default)
  85111. */
  85112. trackerDuration) {
  85113. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85114. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85115. this.targetFrameRate = targetFrameRate;
  85116. this.trackerDuration = trackerDuration;
  85117. /**
  85118. * Gets the list of optimizations to apply
  85119. */
  85120. this.optimizations = new Array();
  85121. }
  85122. /**
  85123. * Add a new optimization
  85124. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85125. * @returns the current SceneOptimizerOptions
  85126. */
  85127. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85128. this.optimizations.push(optimization);
  85129. return this;
  85130. };
  85131. /**
  85132. * Add a new custom optimization
  85133. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85134. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85135. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85136. * @returns the current SceneOptimizerOptions
  85137. */
  85138. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85139. if (priority === void 0) { priority = 0; }
  85140. var optimization = new CustomOptimization(priority);
  85141. optimization.onApply = onApply;
  85142. optimization.onGetDescription = onGetDescription;
  85143. this.optimizations.push(optimization);
  85144. return this;
  85145. };
  85146. /**
  85147. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85148. * @param targetFrameRate defines the target frame rate (60 by default)
  85149. * @returns a SceneOptimizerOptions object
  85150. */
  85151. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85152. var result = new SceneOptimizerOptions(targetFrameRate);
  85153. var priority = 0;
  85154. result.addOptimization(new MergeMeshesOptimization(priority));
  85155. result.addOptimization(new ShadowsOptimization(priority));
  85156. result.addOptimization(new LensFlaresOptimization(priority));
  85157. // Next priority
  85158. priority++;
  85159. result.addOptimization(new PostProcessesOptimization(priority));
  85160. result.addOptimization(new ParticlesOptimization(priority));
  85161. // Next priority
  85162. priority++;
  85163. result.addOptimization(new TextureOptimization(priority, 1024));
  85164. return result;
  85165. };
  85166. /**
  85167. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85168. * @param targetFrameRate defines the target frame rate (60 by default)
  85169. * @returns a SceneOptimizerOptions object
  85170. */
  85171. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85172. var result = new SceneOptimizerOptions(targetFrameRate);
  85173. var priority = 0;
  85174. result.addOptimization(new MergeMeshesOptimization(priority));
  85175. result.addOptimization(new ShadowsOptimization(priority));
  85176. result.addOptimization(new LensFlaresOptimization(priority));
  85177. // Next priority
  85178. priority++;
  85179. result.addOptimization(new PostProcessesOptimization(priority));
  85180. result.addOptimization(new ParticlesOptimization(priority));
  85181. // Next priority
  85182. priority++;
  85183. result.addOptimization(new TextureOptimization(priority, 512));
  85184. // Next priority
  85185. priority++;
  85186. result.addOptimization(new RenderTargetsOptimization(priority));
  85187. // Next priority
  85188. priority++;
  85189. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85190. return result;
  85191. };
  85192. /**
  85193. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85194. * @param targetFrameRate defines the target frame rate (60 by default)
  85195. * @returns a SceneOptimizerOptions object
  85196. */
  85197. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85198. var result = new SceneOptimizerOptions(targetFrameRate);
  85199. var priority = 0;
  85200. result.addOptimization(new MergeMeshesOptimization(priority));
  85201. result.addOptimization(new ShadowsOptimization(priority));
  85202. result.addOptimization(new LensFlaresOptimization(priority));
  85203. // Next priority
  85204. priority++;
  85205. result.addOptimization(new PostProcessesOptimization(priority));
  85206. result.addOptimization(new ParticlesOptimization(priority));
  85207. // Next priority
  85208. priority++;
  85209. result.addOptimization(new TextureOptimization(priority, 256));
  85210. // Next priority
  85211. priority++;
  85212. result.addOptimization(new RenderTargetsOptimization(priority));
  85213. // Next priority
  85214. priority++;
  85215. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85216. return result;
  85217. };
  85218. return SceneOptimizerOptions;
  85219. }());
  85220. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85221. /**
  85222. * Class used to run optimizations in order to reach a target frame rate
  85223. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85224. */
  85225. var SceneOptimizer = /** @class */ (function () {
  85226. /**
  85227. * Creates a new SceneOptimizer
  85228. * @param scene defines the scene to work on
  85229. * @param options defines the options to use with the SceneOptimizer
  85230. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85231. * @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)
  85232. */
  85233. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85234. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85235. if (improvementMode === void 0) { improvementMode = false; }
  85236. var _this = this;
  85237. this._isRunning = false;
  85238. this._currentPriorityLevel = 0;
  85239. this._targetFrameRate = 60;
  85240. this._trackerDuration = 2000;
  85241. this._currentFrameRate = 0;
  85242. this._improvementMode = false;
  85243. /**
  85244. * Defines an observable called when the optimizer reaches the target frame rate
  85245. */
  85246. this.onSuccessObservable = new BABYLON.Observable();
  85247. /**
  85248. * Defines an observable called when the optimizer enables an optimization
  85249. */
  85250. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85251. /**
  85252. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85253. */
  85254. this.onFailureObservable = new BABYLON.Observable();
  85255. if (!options) {
  85256. this._options = new SceneOptimizerOptions();
  85257. }
  85258. else {
  85259. this._options = options;
  85260. }
  85261. if (this._options.targetFrameRate) {
  85262. this._targetFrameRate = this._options.targetFrameRate;
  85263. }
  85264. if (this._options.trackerDuration) {
  85265. this._trackerDuration = this._options.trackerDuration;
  85266. }
  85267. if (autoGeneratePriorities) {
  85268. var priority = 0;
  85269. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85270. var optim = _a[_i];
  85271. optim.priority = priority++;
  85272. }
  85273. }
  85274. this._improvementMode = improvementMode;
  85275. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85276. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85277. _this._sceneDisposeObserver = null;
  85278. _this.dispose();
  85279. });
  85280. }
  85281. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85282. /**
  85283. * Gets a boolean indicating if the optimizer is in improvement mode
  85284. */
  85285. get: function () {
  85286. return this._improvementMode;
  85287. },
  85288. enumerable: true,
  85289. configurable: true
  85290. });
  85291. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85292. /**
  85293. * Gets the current priority level (0 at start)
  85294. */
  85295. get: function () {
  85296. return this._currentPriorityLevel;
  85297. },
  85298. enumerable: true,
  85299. configurable: true
  85300. });
  85301. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85302. /**
  85303. * Gets the current frame rate checked by the SceneOptimizer
  85304. */
  85305. get: function () {
  85306. return this._currentFrameRate;
  85307. },
  85308. enumerable: true,
  85309. configurable: true
  85310. });
  85311. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85312. /**
  85313. * Gets or sets the current target frame rate (60 by default)
  85314. */
  85315. get: function () {
  85316. return this._targetFrameRate;
  85317. },
  85318. /**
  85319. * Gets or sets the current target frame rate (60 by default)
  85320. */
  85321. set: function (value) {
  85322. this._targetFrameRate = value;
  85323. },
  85324. enumerable: true,
  85325. configurable: true
  85326. });
  85327. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85328. /**
  85329. * Gets or sets the current interval between two checks (every 2000ms by default)
  85330. */
  85331. get: function () {
  85332. return this._trackerDuration;
  85333. },
  85334. /**
  85335. * Gets or sets the current interval between two checks (every 2000ms by default)
  85336. */
  85337. set: function (value) {
  85338. this._trackerDuration = value;
  85339. },
  85340. enumerable: true,
  85341. configurable: true
  85342. });
  85343. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85344. /**
  85345. * Gets the list of active optimizations
  85346. */
  85347. get: function () {
  85348. return this._options.optimizations;
  85349. },
  85350. enumerable: true,
  85351. configurable: true
  85352. });
  85353. /**
  85354. * Stops the current optimizer
  85355. */
  85356. SceneOptimizer.prototype.stop = function () {
  85357. this._isRunning = false;
  85358. };
  85359. /**
  85360. * Reset the optimizer to initial step (current priority level = 0)
  85361. */
  85362. SceneOptimizer.prototype.reset = function () {
  85363. this._currentPriorityLevel = 0;
  85364. };
  85365. /**
  85366. * Start the optimizer. By default it will try to reach a specific framerate
  85367. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85368. */
  85369. SceneOptimizer.prototype.start = function () {
  85370. var _this = this;
  85371. if (this._isRunning) {
  85372. return;
  85373. }
  85374. this._isRunning = true;
  85375. // Let's wait for the scene to be ready before running our check
  85376. this._scene.executeWhenReady(function () {
  85377. setTimeout(function () {
  85378. _this._checkCurrentState();
  85379. }, _this._trackerDuration);
  85380. });
  85381. };
  85382. SceneOptimizer.prototype._checkCurrentState = function () {
  85383. var _this = this;
  85384. if (!this._isRunning) {
  85385. return;
  85386. }
  85387. var scene = this._scene;
  85388. var options = this._options;
  85389. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85390. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85391. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85392. this._isRunning = false;
  85393. this.onSuccessObservable.notifyObservers(this);
  85394. return;
  85395. }
  85396. // Apply current level of optimizations
  85397. var allDone = true;
  85398. var noOptimizationApplied = true;
  85399. for (var index = 0; index < options.optimizations.length; index++) {
  85400. var optimization = options.optimizations[index];
  85401. if (optimization.priority === this._currentPriorityLevel) {
  85402. noOptimizationApplied = false;
  85403. allDone = allDone && optimization.apply(scene, this);
  85404. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85405. }
  85406. }
  85407. // If no optimization was applied, this is a failure :(
  85408. if (noOptimizationApplied) {
  85409. this._isRunning = false;
  85410. this.onFailureObservable.notifyObservers(this);
  85411. return;
  85412. }
  85413. // If all optimizations were done, move to next level
  85414. if (allDone) {
  85415. this._currentPriorityLevel++;
  85416. }
  85417. // Let's the system running for a specific amount of time before checking FPS
  85418. scene.executeWhenReady(function () {
  85419. setTimeout(function () {
  85420. _this._checkCurrentState();
  85421. }, _this._trackerDuration);
  85422. });
  85423. };
  85424. /**
  85425. * Release all resources
  85426. */
  85427. SceneOptimizer.prototype.dispose = function () {
  85428. this.stop();
  85429. this.onSuccessObservable.clear();
  85430. this.onFailureObservable.clear();
  85431. this.onNewOptimizationAppliedObservable.clear();
  85432. if (this._sceneDisposeObserver) {
  85433. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85434. }
  85435. };
  85436. /**
  85437. * Helper function to create a SceneOptimizer with one single line of code
  85438. * @param scene defines the scene to work on
  85439. * @param options defines the options to use with the SceneOptimizer
  85440. * @param onSuccess defines a callback to call on success
  85441. * @param onFailure defines a callback to call on failure
  85442. * @returns the new SceneOptimizer object
  85443. */
  85444. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85445. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85446. if (onSuccess) {
  85447. optimizer.onSuccessObservable.add(function () {
  85448. onSuccess();
  85449. });
  85450. }
  85451. if (onFailure) {
  85452. optimizer.onFailureObservable.add(function () {
  85453. onFailure();
  85454. });
  85455. }
  85456. optimizer.start();
  85457. return optimizer;
  85458. };
  85459. return SceneOptimizer;
  85460. }());
  85461. BABYLON.SceneOptimizer = SceneOptimizer;
  85462. })(BABYLON || (BABYLON = {}));
  85463. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85464. var BABYLON;
  85465. (function (BABYLON) {
  85466. var OutlineRenderer = /** @class */ (function () {
  85467. function OutlineRenderer(scene) {
  85468. this.zOffset = 1;
  85469. this._scene = scene;
  85470. }
  85471. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85472. var _this = this;
  85473. if (useOverlay === void 0) { useOverlay = false; }
  85474. var scene = this._scene;
  85475. var engine = this._scene.getEngine();
  85476. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85477. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85478. return;
  85479. }
  85480. var mesh = subMesh.getRenderingMesh();
  85481. var material = subMesh.getMaterial();
  85482. if (!material || !scene.activeCamera) {
  85483. return;
  85484. }
  85485. engine.enableEffect(this._effect);
  85486. // Logarithmic depth
  85487. if (material.useLogarithmicDepth) {
  85488. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85489. }
  85490. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85491. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85492. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85493. // Bones
  85494. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85495. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85496. }
  85497. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85498. // Alpha test
  85499. if (material && material.needAlphaTesting()) {
  85500. var alphaTexture = material.getAlphaTestTexture();
  85501. if (alphaTexture) {
  85502. this._effect.setTexture("diffuseSampler", alphaTexture);
  85503. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85504. }
  85505. }
  85506. engine.setZOffset(-this.zOffset);
  85507. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85508. engine.setZOffset(0);
  85509. };
  85510. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85511. var defines = [];
  85512. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85513. var mesh = subMesh.getMesh();
  85514. var material = subMesh.getMaterial();
  85515. if (material) {
  85516. // Alpha test
  85517. if (material.needAlphaTesting()) {
  85518. defines.push("#define ALPHATEST");
  85519. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85520. attribs.push(BABYLON.VertexBuffer.UVKind);
  85521. defines.push("#define UV1");
  85522. }
  85523. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85524. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85525. defines.push("#define UV2");
  85526. }
  85527. }
  85528. //Logarithmic depth
  85529. if (material.useLogarithmicDepth) {
  85530. defines.push("#define LOGARITHMICDEPTH");
  85531. }
  85532. }
  85533. // Bones
  85534. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85535. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85536. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85537. if (mesh.numBoneInfluencers > 4) {
  85538. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85539. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85540. }
  85541. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85542. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85543. }
  85544. else {
  85545. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85546. }
  85547. // Instances
  85548. if (useInstances) {
  85549. defines.push("#define INSTANCES");
  85550. attribs.push("world0");
  85551. attribs.push("world1");
  85552. attribs.push("world2");
  85553. attribs.push("world3");
  85554. }
  85555. // Get correct effect
  85556. var join = defines.join("\n");
  85557. if (this._cachedDefines !== join) {
  85558. this._cachedDefines = join;
  85559. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85560. }
  85561. return this._effect.isReady();
  85562. };
  85563. return OutlineRenderer;
  85564. }());
  85565. BABYLON.OutlineRenderer = OutlineRenderer;
  85566. })(BABYLON || (BABYLON = {}));
  85567. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85568. var BABYLON;
  85569. (function (BABYLON) {
  85570. var FaceAdjacencies = /** @class */ (function () {
  85571. function FaceAdjacencies() {
  85572. this.edges = new Array();
  85573. this.edgesConnectedCount = 0;
  85574. }
  85575. return FaceAdjacencies;
  85576. }());
  85577. var EdgesRenderer = /** @class */ (function () {
  85578. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85579. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85580. if (epsilon === void 0) { epsilon = 0.95; }
  85581. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85582. this.edgesWidthScalerForOrthographic = 1000.0;
  85583. this.edgesWidthScalerForPerspective = 50.0;
  85584. this._linesPositions = new Array();
  85585. this._linesNormals = new Array();
  85586. this._linesIndices = new Array();
  85587. this._buffers = {};
  85588. this._checkVerticesInsteadOfIndices = false;
  85589. this._source = source;
  85590. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85591. this._epsilon = epsilon;
  85592. this._prepareRessources();
  85593. this._generateEdgesLines();
  85594. }
  85595. EdgesRenderer.prototype._prepareRessources = function () {
  85596. if (this._lineShader) {
  85597. return;
  85598. }
  85599. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85600. attributes: ["position", "normal"],
  85601. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85602. });
  85603. this._lineShader.disableDepthWrite = true;
  85604. this._lineShader.backFaceCulling = false;
  85605. };
  85606. EdgesRenderer.prototype._rebuild = function () {
  85607. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85608. if (buffer) {
  85609. buffer._rebuild();
  85610. }
  85611. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85612. if (buffer) {
  85613. buffer._rebuild();
  85614. }
  85615. var scene = this._source.getScene();
  85616. var engine = scene.getEngine();
  85617. this._ib = engine.createIndexBuffer(this._linesIndices);
  85618. };
  85619. EdgesRenderer.prototype.dispose = function () {
  85620. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85621. if (buffer) {
  85622. buffer.dispose();
  85623. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85624. }
  85625. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85626. if (buffer) {
  85627. buffer.dispose();
  85628. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85629. }
  85630. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85631. this._lineShader.dispose();
  85632. };
  85633. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85634. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85635. return 0;
  85636. }
  85637. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85638. return 1;
  85639. }
  85640. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85641. return 2;
  85642. }
  85643. return -1;
  85644. };
  85645. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85646. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85647. return 0;
  85648. }
  85649. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85650. return 1;
  85651. }
  85652. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85653. return 2;
  85654. }
  85655. return -1;
  85656. };
  85657. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85658. var needToCreateLine;
  85659. if (edge === undefined) {
  85660. needToCreateLine = true;
  85661. }
  85662. else {
  85663. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85664. needToCreateLine = dotProduct < this._epsilon;
  85665. }
  85666. if (needToCreateLine) {
  85667. var offset = this._linesPositions.length / 3;
  85668. var normal = p0.subtract(p1);
  85669. normal.normalize();
  85670. // Positions
  85671. this._linesPositions.push(p0.x);
  85672. this._linesPositions.push(p0.y);
  85673. this._linesPositions.push(p0.z);
  85674. this._linesPositions.push(p0.x);
  85675. this._linesPositions.push(p0.y);
  85676. this._linesPositions.push(p0.z);
  85677. this._linesPositions.push(p1.x);
  85678. this._linesPositions.push(p1.y);
  85679. this._linesPositions.push(p1.z);
  85680. this._linesPositions.push(p1.x);
  85681. this._linesPositions.push(p1.y);
  85682. this._linesPositions.push(p1.z);
  85683. // Normals
  85684. this._linesNormals.push(p1.x);
  85685. this._linesNormals.push(p1.y);
  85686. this._linesNormals.push(p1.z);
  85687. this._linesNormals.push(-1);
  85688. this._linesNormals.push(p1.x);
  85689. this._linesNormals.push(p1.y);
  85690. this._linesNormals.push(p1.z);
  85691. this._linesNormals.push(1);
  85692. this._linesNormals.push(p0.x);
  85693. this._linesNormals.push(p0.y);
  85694. this._linesNormals.push(p0.z);
  85695. this._linesNormals.push(-1);
  85696. this._linesNormals.push(p0.x);
  85697. this._linesNormals.push(p0.y);
  85698. this._linesNormals.push(p0.z);
  85699. this._linesNormals.push(1);
  85700. // Indices
  85701. this._linesIndices.push(offset);
  85702. this._linesIndices.push(offset + 1);
  85703. this._linesIndices.push(offset + 2);
  85704. this._linesIndices.push(offset);
  85705. this._linesIndices.push(offset + 2);
  85706. this._linesIndices.push(offset + 3);
  85707. }
  85708. };
  85709. EdgesRenderer.prototype._generateEdgesLines = function () {
  85710. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85711. var indices = this._source.getIndices();
  85712. if (!indices || !positions) {
  85713. return;
  85714. }
  85715. // First let's find adjacencies
  85716. var adjacencies = new Array();
  85717. var faceNormals = new Array();
  85718. var index;
  85719. var faceAdjacencies;
  85720. // Prepare faces
  85721. for (index = 0; index < indices.length; index += 3) {
  85722. faceAdjacencies = new FaceAdjacencies();
  85723. var p0Index = indices[index];
  85724. var p1Index = indices[index + 1];
  85725. var p2Index = indices[index + 2];
  85726. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  85727. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  85728. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  85729. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  85730. faceNormal.normalize();
  85731. faceNormals.push(faceNormal);
  85732. adjacencies.push(faceAdjacencies);
  85733. }
  85734. // Scan
  85735. for (index = 0; index < adjacencies.length; index++) {
  85736. faceAdjacencies = adjacencies[index];
  85737. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  85738. var otherFaceAdjacencies = adjacencies[otherIndex];
  85739. if (faceAdjacencies.edgesConnectedCount === 3) {
  85740. break;
  85741. }
  85742. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  85743. continue;
  85744. }
  85745. var otherP0 = indices[otherIndex * 3];
  85746. var otherP1 = indices[otherIndex * 3 + 1];
  85747. var otherP2 = indices[otherIndex * 3 + 2];
  85748. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  85749. var otherEdgeIndex = 0;
  85750. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  85751. continue;
  85752. }
  85753. switch (edgeIndex) {
  85754. case 0:
  85755. if (this._checkVerticesInsteadOfIndices) {
  85756. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85757. }
  85758. else {
  85759. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  85760. }
  85761. break;
  85762. case 1:
  85763. if (this._checkVerticesInsteadOfIndices) {
  85764. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85765. }
  85766. else {
  85767. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85768. }
  85769. break;
  85770. case 2:
  85771. if (this._checkVerticesInsteadOfIndices) {
  85772. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85773. }
  85774. else {
  85775. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  85776. }
  85777. break;
  85778. }
  85779. if (otherEdgeIndex === -1) {
  85780. continue;
  85781. }
  85782. faceAdjacencies.edges[edgeIndex] = otherIndex;
  85783. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  85784. faceAdjacencies.edgesConnectedCount++;
  85785. otherFaceAdjacencies.edgesConnectedCount++;
  85786. if (faceAdjacencies.edgesConnectedCount === 3) {
  85787. break;
  85788. }
  85789. }
  85790. }
  85791. }
  85792. // Create lines
  85793. for (index = 0; index < adjacencies.length; index++) {
  85794. // 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
  85795. var current = adjacencies[index];
  85796. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  85797. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  85798. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  85799. }
  85800. // Merge into a single mesh
  85801. var engine = this._source.getScene().getEngine();
  85802. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  85803. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  85804. this._ib = engine.createIndexBuffer(this._linesIndices);
  85805. this._indicesCount = this._linesIndices.length;
  85806. };
  85807. EdgesRenderer.prototype.render = function () {
  85808. var scene = this._source.getScene();
  85809. if (!this._lineShader.isReady() || !scene.activeCamera) {
  85810. return;
  85811. }
  85812. var engine = scene.getEngine();
  85813. this._lineShader._preBind();
  85814. // VBOs
  85815. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  85816. scene.resetCachedMaterial();
  85817. this._lineShader.setColor4("color", this._source.edgesColor);
  85818. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  85819. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  85820. }
  85821. else {
  85822. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  85823. }
  85824. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  85825. this._lineShader.bind(this._source.getWorldMatrix());
  85826. // Draw order
  85827. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  85828. this._lineShader.unbind();
  85829. engine.setDepthWrite(true);
  85830. };
  85831. return EdgesRenderer;
  85832. }());
  85833. BABYLON.EdgesRenderer = EdgesRenderer;
  85834. })(BABYLON || (BABYLON = {}));
  85835. //# sourceMappingURL=babylon.edgesRenderer.js.map
  85836. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85837. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85838. s = arguments[i];
  85839. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85840. t[p] = s[p];
  85841. }
  85842. return t;
  85843. };
  85844. var BABYLON;
  85845. (function (BABYLON) {
  85846. /**
  85847. * The effect layer Helps adding post process effect blended with the main pass.
  85848. *
  85849. * This can be for instance use to generate glow or higlight effects on the scene.
  85850. *
  85851. * The effect layer class can not be used directly and is intented to inherited from to be
  85852. * customized per effects.
  85853. */
  85854. var EffectLayer = /** @class */ (function () {
  85855. /**
  85856. * Instantiates a new effect Layer and references it in the scene.
  85857. * @param name The name of the layer
  85858. * @param scene The scene to use the layer in
  85859. */
  85860. function EffectLayer(
  85861. /** The Friendly of the effect in the scene */
  85862. name, scene) {
  85863. this.name = name;
  85864. this._vertexBuffers = {};
  85865. this._maxSize = 0;
  85866. this._mainTextureDesiredSize = { width: 0, height: 0 };
  85867. this._shouldRender = true;
  85868. this._postProcesses = [];
  85869. this._textures = [];
  85870. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  85871. /**
  85872. * The clear color of the texture used to generate the glow map.
  85873. */
  85874. this.neutralColor = new BABYLON.Color4();
  85875. /**
  85876. * Specifies wether the highlight layer is enabled or not.
  85877. */
  85878. this.isEnabled = true;
  85879. /**
  85880. * An event triggered when the effect layer has been disposed.
  85881. */
  85882. this.onDisposeObservable = new BABYLON.Observable();
  85883. /**
  85884. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  85885. */
  85886. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  85887. /**
  85888. * An event triggered when the generated texture is being merged in the scene.
  85889. */
  85890. this.onBeforeComposeObservable = new BABYLON.Observable();
  85891. /**
  85892. * An event triggered when the generated texture has been merged in the scene.
  85893. */
  85894. this.onAfterComposeObservable = new BABYLON.Observable();
  85895. /**
  85896. * An event triggered when the efffect layer changes its size.
  85897. */
  85898. this.onSizeChangedObservable = new BABYLON.Observable();
  85899. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85900. this._engine = scene.getEngine();
  85901. this._maxSize = this._engine.getCaps().maxTextureSize;
  85902. this._scene.effectLayers.push(this);
  85903. // Generate Buffers
  85904. this._generateIndexBuffer();
  85905. this._genrateVertexBuffer();
  85906. }
  85907. Object.defineProperty(EffectLayer.prototype, "camera", {
  85908. /**
  85909. * Gets the camera attached to the layer.
  85910. */
  85911. get: function () {
  85912. return this._effectLayerOptions.camera;
  85913. },
  85914. enumerable: true,
  85915. configurable: true
  85916. });
  85917. /**
  85918. * Initializes the effect layer with the required options.
  85919. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85920. */
  85921. EffectLayer.prototype._init = function (options) {
  85922. // Adapt options
  85923. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85924. this._setMainTextureSize();
  85925. this._createMainTexture();
  85926. this._createTextureAndPostProcesses();
  85927. this._mergeEffect = this._createMergeEffect();
  85928. };
  85929. /**
  85930. * Generates the index buffer of the full screen quad blending to the main canvas.
  85931. */
  85932. EffectLayer.prototype._generateIndexBuffer = function () {
  85933. // Indices
  85934. var indices = [];
  85935. indices.push(0);
  85936. indices.push(1);
  85937. indices.push(2);
  85938. indices.push(0);
  85939. indices.push(2);
  85940. indices.push(3);
  85941. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85942. };
  85943. /**
  85944. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85945. */
  85946. EffectLayer.prototype._genrateVertexBuffer = function () {
  85947. // VBO
  85948. var vertices = [];
  85949. vertices.push(1, 1);
  85950. vertices.push(-1, 1);
  85951. vertices.push(-1, -1);
  85952. vertices.push(1, -1);
  85953. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85954. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85955. };
  85956. /**
  85957. * Sets the main texture desired size which is the closest power of two
  85958. * of the engine canvas size.
  85959. */
  85960. EffectLayer.prototype._setMainTextureSize = function () {
  85961. if (this._effectLayerOptions.mainTextureFixedSize) {
  85962. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85963. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85964. }
  85965. else {
  85966. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85967. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85968. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85969. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85970. }
  85971. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85972. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85973. };
  85974. /**
  85975. * Creates the main texture for the effect layer.
  85976. */
  85977. EffectLayer.prototype._createMainTexture = function () {
  85978. var _this = this;
  85979. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85980. width: this._mainTextureDesiredSize.width,
  85981. height: this._mainTextureDesiredSize.height
  85982. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85983. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85984. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85985. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85986. this._mainTexture.anisotropicFilteringLevel = 1;
  85987. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85988. this._mainTexture.renderParticles = false;
  85989. this._mainTexture.renderList = null;
  85990. this._mainTexture.ignoreCameraViewport = true;
  85991. // Custom render function
  85992. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85993. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85994. var index;
  85995. var engine = _this._scene.getEngine();
  85996. if (depthOnlySubMeshes.length) {
  85997. engine.setColorWrite(false);
  85998. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85999. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86000. }
  86001. engine.setColorWrite(true);
  86002. }
  86003. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86004. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86005. }
  86006. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86007. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86008. }
  86009. for (index = 0; index < transparentSubMeshes.length; index++) {
  86010. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86011. }
  86012. };
  86013. this._mainTexture.onClearObservable.add(function (engine) {
  86014. engine.clear(_this.neutralColor, true, true, true);
  86015. });
  86016. };
  86017. /**
  86018. * Checks for the readiness of the element composing the layer.
  86019. * @param subMesh the mesh to check for
  86020. * @param useInstances specify wether or not to use instances to render the mesh
  86021. * @param emissiveTexture the associated emissive texture used to generate the glow
  86022. * @return true if ready otherwise, false
  86023. */
  86024. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86025. var material = subMesh.getMaterial();
  86026. if (!material) {
  86027. return false;
  86028. }
  86029. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86030. return false;
  86031. }
  86032. var defines = [];
  86033. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86034. var mesh = subMesh.getMesh();
  86035. var uv1 = false;
  86036. var uv2 = false;
  86037. // Alpha test
  86038. if (material && material.needAlphaTesting()) {
  86039. var alphaTexture = material.getAlphaTestTexture();
  86040. if (alphaTexture) {
  86041. defines.push("#define ALPHATEST");
  86042. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86043. alphaTexture.coordinatesIndex === 1) {
  86044. defines.push("#define DIFFUSEUV2");
  86045. uv2 = true;
  86046. }
  86047. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86048. defines.push("#define DIFFUSEUV1");
  86049. uv1 = true;
  86050. }
  86051. }
  86052. }
  86053. // Emissive
  86054. if (emissiveTexture) {
  86055. defines.push("#define EMISSIVE");
  86056. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86057. emissiveTexture.coordinatesIndex === 1) {
  86058. defines.push("#define EMISSIVEUV2");
  86059. uv2 = true;
  86060. }
  86061. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86062. defines.push("#define EMISSIVEUV1");
  86063. uv1 = true;
  86064. }
  86065. }
  86066. if (uv1) {
  86067. attribs.push(BABYLON.VertexBuffer.UVKind);
  86068. defines.push("#define UV1");
  86069. }
  86070. if (uv2) {
  86071. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86072. defines.push("#define UV2");
  86073. }
  86074. // Bones
  86075. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86076. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86077. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86078. if (mesh.numBoneInfluencers > 4) {
  86079. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86080. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86081. }
  86082. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86083. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86084. }
  86085. else {
  86086. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86087. }
  86088. // Instances
  86089. if (useInstances) {
  86090. defines.push("#define INSTANCES");
  86091. attribs.push("world0");
  86092. attribs.push("world1");
  86093. attribs.push("world2");
  86094. attribs.push("world3");
  86095. }
  86096. // Get correct effect
  86097. var join = defines.join("\n");
  86098. if (this._cachedDefines !== join) {
  86099. this._cachedDefines = join;
  86100. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  86101. }
  86102. return this._effectLayerMapGenerationEffect.isReady();
  86103. };
  86104. /**
  86105. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86106. */
  86107. EffectLayer.prototype.render = function () {
  86108. var currentEffect = this._mergeEffect;
  86109. // Check
  86110. if (!currentEffect.isReady())
  86111. return;
  86112. for (var i = 0; i < this._postProcesses.length; i++) {
  86113. if (!this._postProcesses[i].isReady()) {
  86114. return;
  86115. }
  86116. }
  86117. var engine = this._scene.getEngine();
  86118. this.onBeforeComposeObservable.notifyObservers(this);
  86119. // Render
  86120. engine.enableEffect(currentEffect);
  86121. engine.setState(false);
  86122. // VBOs
  86123. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86124. // Cache
  86125. var previousAlphaMode = engine.getAlphaMode();
  86126. // Go Blend.
  86127. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86128. // Blends the map on the main canvas.
  86129. this._internalRender(currentEffect);
  86130. // Restore Alpha
  86131. engine.setAlphaMode(previousAlphaMode);
  86132. this.onAfterComposeObservable.notifyObservers(this);
  86133. // Handle size changes.
  86134. var size = this._mainTexture.getSize();
  86135. this._setMainTextureSize();
  86136. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86137. // Recreate RTT and post processes on size change.
  86138. this.onSizeChangedObservable.notifyObservers(this);
  86139. this._disposeTextureAndPostProcesses();
  86140. this._createMainTexture();
  86141. this._createTextureAndPostProcesses();
  86142. }
  86143. };
  86144. /**
  86145. * Determine if a given mesh will be used in the current effect.
  86146. * @param mesh mesh to test
  86147. * @returns true if the mesh will be used
  86148. */
  86149. EffectLayer.prototype.hasMesh = function (mesh) {
  86150. return true;
  86151. };
  86152. /**
  86153. * Returns true if the layer contains information to display, otherwise false.
  86154. * @returns true if the glow layer should be rendered
  86155. */
  86156. EffectLayer.prototype.shouldRender = function () {
  86157. return this.isEnabled && this._shouldRender;
  86158. };
  86159. /**
  86160. * Returns true if the mesh should render, otherwise false.
  86161. * @param mesh The mesh to render
  86162. * @returns true if it should render otherwise false
  86163. */
  86164. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86165. return true;
  86166. };
  86167. /**
  86168. * Returns true if the mesh should render, otherwise false.
  86169. * @param mesh The mesh to render
  86170. * @returns true if it should render otherwise false
  86171. */
  86172. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86173. return true;
  86174. };
  86175. /**
  86176. * Renders the submesh passed in parameter to the generation map.
  86177. */
  86178. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86179. var _this = this;
  86180. if (!this.shouldRender()) {
  86181. return;
  86182. }
  86183. var material = subMesh.getMaterial();
  86184. var mesh = subMesh.getRenderingMesh();
  86185. var scene = this._scene;
  86186. var engine = scene.getEngine();
  86187. if (!material) {
  86188. return;
  86189. }
  86190. // Do not block in blend mode.
  86191. if (material.needAlphaBlendingForMesh(mesh)) {
  86192. return;
  86193. }
  86194. // Culling
  86195. engine.setState(material.backFaceCulling);
  86196. // Managing instances
  86197. var batch = mesh._getInstancesRenderList(subMesh._id);
  86198. if (batch.mustReturn) {
  86199. return;
  86200. }
  86201. // Early Exit per mesh
  86202. if (!this._shouldRenderMesh(mesh)) {
  86203. return;
  86204. }
  86205. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86206. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86207. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86208. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86209. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86210. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86211. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86212. // Alpha test
  86213. if (material && material.needAlphaTesting()) {
  86214. var alphaTexture = material.getAlphaTestTexture();
  86215. if (alphaTexture) {
  86216. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86217. var textureMatrix = alphaTexture.getTextureMatrix();
  86218. if (textureMatrix) {
  86219. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86220. }
  86221. }
  86222. }
  86223. // Glow emissive only
  86224. if (this._emissiveTextureAndColor.texture) {
  86225. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86226. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86227. }
  86228. // Bones
  86229. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86230. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86231. }
  86232. // Draw
  86233. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86234. }
  86235. else {
  86236. // Need to reset refresh rate of the shadowMap
  86237. this._mainTexture.resetRefreshCounter();
  86238. }
  86239. };
  86240. /**
  86241. * Rebuild the required buffers.
  86242. * @ignore Internal use only.
  86243. */
  86244. EffectLayer.prototype._rebuild = function () {
  86245. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86246. if (vb) {
  86247. vb._rebuild();
  86248. }
  86249. this._generateIndexBuffer();
  86250. };
  86251. /**
  86252. * Dispose only the render target textures and post process.
  86253. */
  86254. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86255. this._mainTexture.dispose();
  86256. for (var i = 0; i < this._postProcesses.length; i++) {
  86257. if (this._postProcesses[i]) {
  86258. this._postProcesses[i].dispose();
  86259. }
  86260. }
  86261. this._postProcesses = [];
  86262. for (var i = 0; i < this._textures.length; i++) {
  86263. if (this._textures[i]) {
  86264. this._textures[i].dispose();
  86265. }
  86266. }
  86267. this._textures = [];
  86268. };
  86269. /**
  86270. * Dispose the highlight layer and free resources.
  86271. */
  86272. EffectLayer.prototype.dispose = function () {
  86273. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86274. if (vertexBuffer) {
  86275. vertexBuffer.dispose();
  86276. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86277. }
  86278. if (this._indexBuffer) {
  86279. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86280. this._indexBuffer = null;
  86281. }
  86282. // Clean textures and post processes
  86283. this._disposeTextureAndPostProcesses();
  86284. // Remove from scene
  86285. var index = this._scene.effectLayers.indexOf(this, 0);
  86286. if (index > -1) {
  86287. this._scene.effectLayers.splice(index, 1);
  86288. }
  86289. // Callback
  86290. this.onDisposeObservable.notifyObservers(this);
  86291. this.onDisposeObservable.clear();
  86292. this.onBeforeRenderMainTextureObservable.clear();
  86293. this.onBeforeComposeObservable.clear();
  86294. this.onAfterComposeObservable.clear();
  86295. this.onSizeChangedObservable.clear();
  86296. };
  86297. return EffectLayer;
  86298. }());
  86299. BABYLON.EffectLayer = EffectLayer;
  86300. })(BABYLON || (BABYLON = {}));
  86301. //# sourceMappingURL=babylon.effectLayer.js.map
  86302. var BABYLON;
  86303. (function (BABYLON) {
  86304. /**
  86305. * Special Glow Blur post process only blurring the alpha channel
  86306. * It enforces keeping the most luminous color in the color channel.
  86307. */
  86308. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86309. __extends(GlowBlurPostProcess, _super);
  86310. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86312. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86313. _this.direction = direction;
  86314. _this.kernel = kernel;
  86315. _this.onApplyObservable.add(function (effect) {
  86316. effect.setFloat2("screenSize", _this.width, _this.height);
  86317. effect.setVector2("direction", _this.direction);
  86318. effect.setFloat("blurWidth", _this.kernel);
  86319. });
  86320. return _this;
  86321. }
  86322. return GlowBlurPostProcess;
  86323. }(BABYLON.PostProcess));
  86324. /**
  86325. * The highlight layer Helps adding a glow effect around a mesh.
  86326. *
  86327. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86328. * glowy meshes to your scene.
  86329. *
  86330. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86331. */
  86332. var HighlightLayer = /** @class */ (function (_super) {
  86333. __extends(HighlightLayer, _super);
  86334. /**
  86335. * Instantiates a new highlight Layer and references it to the scene..
  86336. * @param name The name of the layer
  86337. * @param scene The scene to use the layer in
  86338. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86339. */
  86340. function HighlightLayer(name, scene, options) {
  86341. var _this = _super.call(this, name, scene) || this;
  86342. _this.name = name;
  86343. /**
  86344. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86345. */
  86346. _this.innerGlow = true;
  86347. /**
  86348. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86349. */
  86350. _this.outerGlow = true;
  86351. /**
  86352. * An event triggered when the highlight layer is being blurred.
  86353. */
  86354. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86355. /**
  86356. * An event triggered when the highlight layer has been blurred.
  86357. */
  86358. _this.onAfterBlurObservable = new BABYLON.Observable();
  86359. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86360. _this._meshes = {};
  86361. _this._excludedMeshes = {};
  86362. _this.neutralColor = HighlightLayer.NeutralColor;
  86363. // Warn on stencil
  86364. if (!_this._engine.isStencilEnable) {
  86365. 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 }");
  86366. }
  86367. // Adapt options
  86368. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86369. // Initialize the layer
  86370. _this._init({
  86371. alphaBlendingMode: _this._options.alphaBlendingMode,
  86372. camera: _this._options.camera,
  86373. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86374. mainTextureRatio: _this._options.mainTextureRatio
  86375. });
  86376. // Do not render as long as no meshes have been added
  86377. _this._shouldRender = false;
  86378. return _this;
  86379. }
  86380. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86381. /**
  86382. * Gets the horizontal size of the blur.
  86383. */
  86384. get: function () {
  86385. return this._horizontalBlurPostprocess.kernel;
  86386. },
  86387. /**
  86388. * Specifies the horizontal size of the blur.
  86389. */
  86390. set: function (value) {
  86391. this._horizontalBlurPostprocess.kernel = value;
  86392. },
  86393. enumerable: true,
  86394. configurable: true
  86395. });
  86396. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86397. /**
  86398. * Gets the vertical size of the blur.
  86399. */
  86400. get: function () {
  86401. return this._verticalBlurPostprocess.kernel;
  86402. },
  86403. /**
  86404. * Specifies the vertical size of the blur.
  86405. */
  86406. set: function (value) {
  86407. this._verticalBlurPostprocess.kernel = value;
  86408. },
  86409. enumerable: true,
  86410. configurable: true
  86411. });
  86412. /**
  86413. * Get the effect name of the layer.
  86414. * @return The effect name
  86415. */
  86416. HighlightLayer.prototype.getEffectName = function () {
  86417. return HighlightLayer.EffectName;
  86418. };
  86419. /**
  86420. * Create the merge effect. This is the shader use to blit the information back
  86421. * to the main canvas at the end of the scene rendering.
  86422. */
  86423. HighlightLayer.prototype._createMergeEffect = function () {
  86424. // Effect
  86425. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86426. };
  86427. /**
  86428. * Creates the render target textures and post processes used in the highlight layer.
  86429. */
  86430. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86431. var _this = this;
  86432. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86433. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86434. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86435. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86436. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86437. width: blurTextureWidth,
  86438. height: blurTextureHeight
  86439. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86440. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86441. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86442. this._blurTexture.anisotropicFilteringLevel = 16;
  86443. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86444. this._blurTexture.renderParticles = false;
  86445. this._blurTexture.ignoreCameraViewport = true;
  86446. this._textures = [this._blurTexture];
  86447. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86448. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86449. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86450. effect.setTexture("textureSampler", _this._mainTexture);
  86451. });
  86452. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86453. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86454. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86455. });
  86456. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86457. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86458. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86459. });
  86460. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86461. }
  86462. else {
  86463. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86464. width: blurTextureWidth,
  86465. height: blurTextureHeight
  86466. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86467. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86468. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86469. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86470. effect.setTexture("textureSampler", _this._mainTexture);
  86471. });
  86472. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86473. width: blurTextureWidth,
  86474. height: blurTextureHeight
  86475. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86476. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86477. }
  86478. this._mainTexture.onAfterUnbindObservable.add(function () {
  86479. _this.onBeforeBlurObservable.notifyObservers(_this);
  86480. var internalTexture = _this._blurTexture.getInternalTexture();
  86481. if (internalTexture) {
  86482. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86483. }
  86484. _this.onAfterBlurObservable.notifyObservers(_this);
  86485. });
  86486. // Prevent autoClear.
  86487. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86488. };
  86489. /**
  86490. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86491. */
  86492. HighlightLayer.prototype.needStencil = function () {
  86493. return true;
  86494. };
  86495. /**
  86496. * Checks for the readiness of the element composing the layer.
  86497. * @param subMesh the mesh to check for
  86498. * @param useInstances specify wether or not to use instances to render the mesh
  86499. * @param emissiveTexture the associated emissive texture used to generate the glow
  86500. * @return true if ready otherwise, false
  86501. */
  86502. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86503. var material = subMesh.getMaterial();
  86504. var mesh = subMesh.getRenderingMesh();
  86505. if (!material || !mesh || !this._meshes) {
  86506. return false;
  86507. }
  86508. var emissiveTexture = null;
  86509. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86510. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86511. emissiveTexture = material.emissiveTexture;
  86512. }
  86513. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86514. };
  86515. /**
  86516. * Implementation specific of rendering the generating effect on the main canvas.
  86517. * @param effect The effect used to render through
  86518. */
  86519. HighlightLayer.prototype._internalRender = function (effect) {
  86520. // Texture
  86521. effect.setTexture("textureSampler", this._blurTexture);
  86522. // Cache
  86523. var engine = this._engine;
  86524. var previousStencilBuffer = engine.getStencilBuffer();
  86525. var previousStencilFunction = engine.getStencilFunction();
  86526. var previousStencilMask = engine.getStencilMask();
  86527. var previousStencilOperationPass = engine.getStencilOperationPass();
  86528. var previousStencilOperationFail = engine.getStencilOperationFail();
  86529. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86530. var previousStencilReference = engine.getStencilFunctionReference();
  86531. // Stencil operations
  86532. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86533. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86534. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86535. // Draw order
  86536. engine.setStencilMask(0x00);
  86537. engine.setStencilBuffer(true);
  86538. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86539. // 2 passes inner outer
  86540. if (this.outerGlow) {
  86541. effect.setFloat("offset", 0);
  86542. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86543. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86544. }
  86545. if (this.innerGlow) {
  86546. effect.setFloat("offset", 1);
  86547. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86548. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86549. }
  86550. // Restore Cache
  86551. engine.setStencilFunction(previousStencilFunction);
  86552. engine.setStencilMask(previousStencilMask);
  86553. engine.setStencilBuffer(previousStencilBuffer);
  86554. engine.setStencilOperationPass(previousStencilOperationPass);
  86555. engine.setStencilOperationFail(previousStencilOperationFail);
  86556. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86557. engine.setStencilFunctionReference(previousStencilReference);
  86558. };
  86559. /**
  86560. * Returns true if the layer contains information to display, otherwise false.
  86561. */
  86562. HighlightLayer.prototype.shouldRender = function () {
  86563. if (_super.prototype.shouldRender.call(this)) {
  86564. return this._meshes ? true : false;
  86565. }
  86566. return false;
  86567. };
  86568. /**
  86569. * Returns true if the mesh should render, otherwise false.
  86570. * @param mesh The mesh to render
  86571. * @returns true if it should render otherwise false
  86572. */
  86573. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86574. // Excluded Mesh
  86575. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86576. return false;
  86577. }
  86578. ;
  86579. return true;
  86580. };
  86581. /**
  86582. * Sets the required values for both the emissive texture and and the main color.
  86583. */
  86584. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86585. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86586. if (highlightLayerMesh) {
  86587. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86588. }
  86589. else {
  86590. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86591. }
  86592. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86593. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86594. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86595. }
  86596. else {
  86597. this._emissiveTextureAndColor.texture = null;
  86598. }
  86599. };
  86600. /**
  86601. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86602. * @param mesh The mesh to exclude from the highlight layer
  86603. */
  86604. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86605. if (!this._excludedMeshes) {
  86606. return;
  86607. }
  86608. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86609. if (!meshExcluded) {
  86610. this._excludedMeshes[mesh.uniqueId] = {
  86611. mesh: mesh,
  86612. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86613. mesh.getEngine().setStencilBuffer(false);
  86614. }),
  86615. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86616. mesh.getEngine().setStencilBuffer(true);
  86617. }),
  86618. };
  86619. }
  86620. };
  86621. /**
  86622. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86623. * @param mesh The mesh to highlight
  86624. */
  86625. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86626. if (!this._excludedMeshes) {
  86627. return;
  86628. }
  86629. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86630. if (meshExcluded) {
  86631. if (meshExcluded.beforeRender) {
  86632. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86633. }
  86634. if (meshExcluded.afterRender) {
  86635. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86636. }
  86637. }
  86638. this._excludedMeshes[mesh.uniqueId] = null;
  86639. };
  86640. /**
  86641. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86642. * @param mesh mesh to test
  86643. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86644. */
  86645. HighlightLayer.prototype.hasMesh = function (mesh) {
  86646. if (!this._meshes) {
  86647. return false;
  86648. }
  86649. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86650. };
  86651. /**
  86652. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86653. * @param mesh The mesh to highlight
  86654. * @param color The color of the highlight
  86655. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86656. */
  86657. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86658. var _this = this;
  86659. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86660. if (!this._meshes) {
  86661. return;
  86662. }
  86663. var meshHighlight = this._meshes[mesh.uniqueId];
  86664. if (meshHighlight) {
  86665. meshHighlight.color = color;
  86666. }
  86667. else {
  86668. this._meshes[mesh.uniqueId] = {
  86669. mesh: mesh,
  86670. color: color,
  86671. // Lambda required for capture due to Observable this context
  86672. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86673. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86674. _this._defaultStencilReference(mesh);
  86675. }
  86676. else {
  86677. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86678. }
  86679. }),
  86680. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86681. glowEmissiveOnly: glowEmissiveOnly
  86682. };
  86683. }
  86684. this._shouldRender = true;
  86685. };
  86686. /**
  86687. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86688. * @param mesh The mesh to highlight
  86689. */
  86690. HighlightLayer.prototype.removeMesh = function (mesh) {
  86691. if (!this._meshes) {
  86692. return;
  86693. }
  86694. var meshHighlight = this._meshes[mesh.uniqueId];
  86695. if (meshHighlight) {
  86696. if (meshHighlight.observerHighlight) {
  86697. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86698. }
  86699. if (meshHighlight.observerDefault) {
  86700. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86701. }
  86702. delete this._meshes[mesh.uniqueId];
  86703. }
  86704. this._shouldRender = false;
  86705. for (var meshHighlightToCheck in this._meshes) {
  86706. if (this._meshes[meshHighlightToCheck]) {
  86707. this._shouldRender = true;
  86708. break;
  86709. }
  86710. }
  86711. };
  86712. /**
  86713. * Force the stencil to the normal expected value for none glowing parts
  86714. */
  86715. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  86716. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  86717. };
  86718. /**
  86719. * Free any resources and references associated to a mesh.
  86720. * Internal use
  86721. * @param mesh The mesh to free.
  86722. */
  86723. HighlightLayer.prototype._disposeMesh = function (mesh) {
  86724. this.removeMesh(mesh);
  86725. this.removeExcludedMesh(mesh);
  86726. };
  86727. /**
  86728. * Dispose the highlight layer and free resources.
  86729. */
  86730. HighlightLayer.prototype.dispose = function () {
  86731. if (this._meshes) {
  86732. // Clean mesh references
  86733. for (var id in this._meshes) {
  86734. var meshHighlight = this._meshes[id];
  86735. if (meshHighlight && meshHighlight.mesh) {
  86736. if (meshHighlight.observerHighlight) {
  86737. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86738. }
  86739. if (meshHighlight.observerDefault) {
  86740. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86741. }
  86742. }
  86743. }
  86744. this._meshes = null;
  86745. }
  86746. if (this._excludedMeshes) {
  86747. for (var id in this._excludedMeshes) {
  86748. var meshHighlight = this._excludedMeshes[id];
  86749. if (meshHighlight) {
  86750. if (meshHighlight.beforeRender) {
  86751. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  86752. }
  86753. if (meshHighlight.afterRender) {
  86754. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  86755. }
  86756. }
  86757. }
  86758. this._excludedMeshes = null;
  86759. }
  86760. _super.prototype.dispose.call(this);
  86761. };
  86762. /**
  86763. * Effect Name of the highlight layer.
  86764. */
  86765. HighlightLayer.EffectName = "HighlightLayer";
  86766. /**
  86767. * The neutral color used during the preparation of the glow effect.
  86768. * This is black by default as the blend operation is a blend operation.
  86769. */
  86770. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  86771. /**
  86772. * Stencil value used for glowing meshes.
  86773. */
  86774. HighlightLayer.GlowingMeshStencilReference = 0x02;
  86775. /**
  86776. * Stencil value used for the other meshes in the scene.
  86777. */
  86778. HighlightLayer.NormalMeshStencilReference = 0x01;
  86779. return HighlightLayer;
  86780. }(BABYLON.EffectLayer));
  86781. BABYLON.HighlightLayer = HighlightLayer;
  86782. })(BABYLON || (BABYLON = {}));
  86783. //# sourceMappingURL=babylon.highlightLayer.js.map
  86784. var BABYLON;
  86785. (function (BABYLON) {
  86786. /**
  86787. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  86788. *
  86789. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86790. * glowy meshes to your scene.
  86791. *
  86792. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  86793. */
  86794. var GlowLayer = /** @class */ (function (_super) {
  86795. __extends(GlowLayer, _super);
  86796. /**
  86797. * Instantiates a new glow Layer and references it to the scene.
  86798. * @param name The name of the layer
  86799. * @param scene The scene to use the layer in
  86800. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  86801. */
  86802. function GlowLayer(name, scene, options) {
  86803. var _this = _super.call(this, name, scene) || this;
  86804. _this.name = name;
  86805. _this._intensity = 1.0;
  86806. _this._includedOnlyMeshes = [];
  86807. _this._excludedMeshes = [];
  86808. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  86809. // Adapt options
  86810. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  86811. // Initialize the layer
  86812. _this._init({
  86813. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  86814. camera: _this._options.camera,
  86815. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86816. mainTextureRatio: _this._options.mainTextureRatio
  86817. });
  86818. return _this;
  86819. }
  86820. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  86821. /**
  86822. * Gets the kernel size of the blur.
  86823. */
  86824. get: function () {
  86825. return this._horizontalBlurPostprocess1.kernel;
  86826. },
  86827. /**
  86828. * Sets the kernel size of the blur.
  86829. */
  86830. set: function (value) {
  86831. this._horizontalBlurPostprocess1.kernel = value;
  86832. this._verticalBlurPostprocess1.kernel = value;
  86833. this._horizontalBlurPostprocess2.kernel = value;
  86834. this._verticalBlurPostprocess2.kernel = value;
  86835. },
  86836. enumerable: true,
  86837. configurable: true
  86838. });
  86839. Object.defineProperty(GlowLayer.prototype, "intensity", {
  86840. /**
  86841. * Gets the glow intensity.
  86842. */
  86843. get: function () {
  86844. return this._intensity;
  86845. },
  86846. /**
  86847. * Sets the glow intensity.
  86848. */
  86849. set: function (value) {
  86850. this._intensity = value;
  86851. },
  86852. enumerable: true,
  86853. configurable: true
  86854. });
  86855. /**
  86856. * Get the effect name of the layer.
  86857. * @return The effect name
  86858. */
  86859. GlowLayer.prototype.getEffectName = function () {
  86860. return GlowLayer.EffectName;
  86861. };
  86862. /**
  86863. * Create the merge effect. This is the shader use to blit the information back
  86864. * to the main canvas at the end of the scene rendering.
  86865. */
  86866. GlowLayer.prototype._createMergeEffect = function () {
  86867. // Effect
  86868. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  86869. };
  86870. /**
  86871. * Creates the render target textures and post processes used in the glow layer.
  86872. */
  86873. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  86874. var _this = this;
  86875. var blurTextureWidth = this._mainTextureDesiredSize.width;
  86876. var blurTextureHeight = this._mainTextureDesiredSize.height;
  86877. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86878. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86879. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  86880. width: blurTextureWidth,
  86881. height: blurTextureHeight
  86882. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86883. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86884. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86885. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86886. this._blurTexture1.renderParticles = false;
  86887. this._blurTexture1.ignoreCameraViewport = true;
  86888. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  86889. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  86890. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  86891. width: blurTextureWidth2,
  86892. height: blurTextureHeight2
  86893. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86894. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86895. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86896. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86897. this._blurTexture2.renderParticles = false;
  86898. this._blurTexture2.ignoreCameraViewport = true;
  86899. this._textures = [this._blurTexture1, this._blurTexture2];
  86900. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86901. width: blurTextureWidth,
  86902. height: blurTextureHeight
  86903. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86904. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86905. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86906. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86907. effect.setTexture("textureSampler", _this._mainTexture);
  86908. });
  86909. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86910. width: blurTextureWidth,
  86911. height: blurTextureHeight
  86912. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86913. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86914. width: blurTextureWidth2,
  86915. height: blurTextureHeight2
  86916. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86917. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86918. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86919. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86920. effect.setTexture("textureSampler", _this._blurTexture1);
  86921. });
  86922. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86923. width: blurTextureWidth2,
  86924. height: blurTextureHeight2
  86925. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86926. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86927. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86928. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86929. this._mainTexture.samples = this._options.mainTextureSamples;
  86930. this._mainTexture.onAfterUnbindObservable.add(function () {
  86931. var internalTexture = _this._blurTexture1.getInternalTexture();
  86932. if (internalTexture) {
  86933. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86934. internalTexture = _this._blurTexture2.getInternalTexture();
  86935. if (internalTexture) {
  86936. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86937. }
  86938. }
  86939. });
  86940. // Prevent autoClear.
  86941. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86942. };
  86943. /**
  86944. * Checks for the readiness of the element composing the layer.
  86945. * @param subMesh the mesh to check for
  86946. * @param useInstances specify wether or not to use instances to render the mesh
  86947. * @param emissiveTexture the associated emissive texture used to generate the glow
  86948. * @return true if ready otherwise, false
  86949. */
  86950. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86951. var material = subMesh.getMaterial();
  86952. var mesh = subMesh.getRenderingMesh();
  86953. if (!material || !mesh) {
  86954. return false;
  86955. }
  86956. var emissiveTexture = material.emissiveTexture;
  86957. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86958. };
  86959. /**
  86960. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86961. */
  86962. GlowLayer.prototype.needStencil = function () {
  86963. return false;
  86964. };
  86965. /**
  86966. * Implementation specific of rendering the generating effect on the main canvas.
  86967. * @param effect The effect used to render through
  86968. */
  86969. GlowLayer.prototype._internalRender = function (effect) {
  86970. // Texture
  86971. effect.setTexture("textureSampler", this._blurTexture1);
  86972. effect.setTexture("textureSampler2", this._blurTexture2);
  86973. effect.setFloat("offset", this._intensity);
  86974. // Cache
  86975. var engine = this._engine;
  86976. var previousStencilBuffer = engine.getStencilBuffer();
  86977. // Draw order
  86978. engine.setStencilBuffer(false);
  86979. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86980. // Draw order
  86981. engine.setStencilBuffer(previousStencilBuffer);
  86982. };
  86983. /**
  86984. * Sets the required values for both the emissive texture and and the main color.
  86985. */
  86986. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86987. var textureLevel = 1.0;
  86988. if (this.customEmissiveTextureSelector) {
  86989. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86990. }
  86991. else {
  86992. if (material) {
  86993. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86994. if (this._emissiveTextureAndColor.texture) {
  86995. textureLevel = this._emissiveTextureAndColor.texture.level;
  86996. }
  86997. }
  86998. else {
  86999. this._emissiveTextureAndColor.texture = null;
  87000. }
  87001. }
  87002. if (this.customEmissiveColorSelector) {
  87003. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87004. }
  87005. else {
  87006. if (material.emissiveColor) {
  87007. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87008. }
  87009. else {
  87010. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87011. }
  87012. }
  87013. };
  87014. /**
  87015. * Returns true if the mesh should render, otherwise false.
  87016. * @param mesh The mesh to render
  87017. * @returns true if it should render otherwise false
  87018. */
  87019. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87020. return this.hasMesh(mesh);
  87021. };
  87022. /**
  87023. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87024. * @param mesh The mesh to exclude from the glow layer
  87025. */
  87026. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87027. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87028. this._excludedMeshes.push(mesh.uniqueId);
  87029. }
  87030. };
  87031. /**
  87032. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87033. * @param mesh The mesh to remove
  87034. */
  87035. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87036. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87037. if (index !== -1) {
  87038. this._excludedMeshes.splice(index, 1);
  87039. }
  87040. };
  87041. /**
  87042. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87043. * @param mesh The mesh to include in the glow layer
  87044. */
  87045. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87046. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87047. this._includedOnlyMeshes.push(mesh.uniqueId);
  87048. }
  87049. };
  87050. /**
  87051. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87052. * @param mesh The mesh to remove
  87053. */
  87054. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87055. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87056. if (index !== -1) {
  87057. this._includedOnlyMeshes.splice(index, 1);
  87058. }
  87059. };
  87060. /**
  87061. * Determine if a given mesh will be used in the glow layer
  87062. * @param mesh The mesh to test
  87063. * @returns true if the mesh will be highlighted by the current glow layer
  87064. */
  87065. GlowLayer.prototype.hasMesh = function (mesh) {
  87066. // Included Mesh
  87067. if (this._includedOnlyMeshes.length) {
  87068. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87069. }
  87070. ;
  87071. // Excluded Mesh
  87072. if (this._excludedMeshes.length) {
  87073. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87074. }
  87075. ;
  87076. return true;
  87077. };
  87078. /**
  87079. * Free any resources and references associated to a mesh.
  87080. * Internal use
  87081. * @param mesh The mesh to free.
  87082. */
  87083. GlowLayer.prototype._disposeMesh = function (mesh) {
  87084. this.removeIncludedOnlyMesh(mesh);
  87085. this.removeExcludedMesh(mesh);
  87086. };
  87087. /**
  87088. * Effect Name of the layer.
  87089. */
  87090. GlowLayer.EffectName = "GlowLayer";
  87091. /**
  87092. * The default blur kernel size used for the glow.
  87093. */
  87094. GlowLayer.DefaultBlurKernelSize = 32;
  87095. /**
  87096. * The default texture size ratio used for the glow.
  87097. */
  87098. GlowLayer.DefaultTextureRatio = 0.5;
  87099. return GlowLayer;
  87100. }(BABYLON.EffectLayer));
  87101. BABYLON.GlowLayer = GlowLayer;
  87102. })(BABYLON || (BABYLON = {}));
  87103. //# sourceMappingURL=babylon.glowLayer.js.map
  87104. var BABYLON;
  87105. (function (BABYLON) {
  87106. /**
  87107. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87108. */
  87109. var AssetTaskState;
  87110. (function (AssetTaskState) {
  87111. /**
  87112. * Initialization
  87113. */
  87114. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87115. /**
  87116. * Running
  87117. */
  87118. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87119. /**
  87120. * Done
  87121. */
  87122. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87123. /**
  87124. * Error
  87125. */
  87126. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87127. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87128. /**
  87129. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87130. */
  87131. var AbstractAssetTask = /** @class */ (function () {
  87132. /**
  87133. * Creates a new {BABYLON.AssetsManager}
  87134. * @param name defines the name of the task
  87135. */
  87136. function AbstractAssetTask(
  87137. /**
  87138. * Task name
  87139. */ name) {
  87140. this.name = name;
  87141. this._isCompleted = false;
  87142. this._taskState = AssetTaskState.INIT;
  87143. }
  87144. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87145. /**
  87146. * Get if the task is completed
  87147. */
  87148. get: function () {
  87149. return this._isCompleted;
  87150. },
  87151. enumerable: true,
  87152. configurable: true
  87153. });
  87154. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87155. /**
  87156. * Gets the current state of the task
  87157. */
  87158. get: function () {
  87159. return this._taskState;
  87160. },
  87161. enumerable: true,
  87162. configurable: true
  87163. });
  87164. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87165. /**
  87166. * Gets the current error object (if task is in error)
  87167. */
  87168. get: function () {
  87169. return this._errorObject;
  87170. },
  87171. enumerable: true,
  87172. configurable: true
  87173. });
  87174. /**
  87175. * Internal only
  87176. * @ignore
  87177. */
  87178. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87179. if (this._errorObject) {
  87180. return;
  87181. }
  87182. this._errorObject = {
  87183. message: message,
  87184. exception: exception
  87185. };
  87186. };
  87187. /**
  87188. * Execute the current task
  87189. * @param scene defines the scene where you want your assets to be loaded
  87190. * @param onSuccess is a callback called when the task is successfully executed
  87191. * @param onError is a callback called if an error occurs
  87192. */
  87193. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87194. var _this = this;
  87195. this._taskState = AssetTaskState.RUNNING;
  87196. this.runTask(scene, function () {
  87197. _this.onDoneCallback(onSuccess, onError);
  87198. }, function (msg, exception) {
  87199. _this.onErrorCallback(onError, msg, exception);
  87200. });
  87201. };
  87202. /**
  87203. * Execute the current task
  87204. * @param scene defines the scene where you want your assets to be loaded
  87205. * @param onSuccess is a callback called when the task is successfully executed
  87206. * @param onError is a callback called if an error occurs
  87207. */
  87208. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87209. throw new Error("runTask is not implemented");
  87210. };
  87211. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87212. this._taskState = AssetTaskState.ERROR;
  87213. this._errorObject = {
  87214. message: message,
  87215. exception: exception
  87216. };
  87217. if (this.onError) {
  87218. this.onError(this, message, exception);
  87219. }
  87220. onError();
  87221. };
  87222. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87223. try {
  87224. this._taskState = AssetTaskState.DONE;
  87225. this._isCompleted = true;
  87226. if (this.onSuccess) {
  87227. this.onSuccess(this);
  87228. }
  87229. onSuccess();
  87230. }
  87231. catch (e) {
  87232. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87233. }
  87234. };
  87235. return AbstractAssetTask;
  87236. }());
  87237. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87238. /**
  87239. * Class used to share progress information about assets loading
  87240. */
  87241. var AssetsProgressEvent = /** @class */ (function () {
  87242. /**
  87243. * Creates a {BABYLON.AssetsProgressEvent}
  87244. * @param remainingCount defines the number of remaining tasks to process
  87245. * @param totalCount defines the total number of tasks
  87246. * @param task defines the task that was just processed
  87247. */
  87248. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87249. this.remainingCount = remainingCount;
  87250. this.totalCount = totalCount;
  87251. this.task = task;
  87252. }
  87253. return AssetsProgressEvent;
  87254. }());
  87255. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87256. /**
  87257. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87258. */
  87259. var MeshAssetTask = /** @class */ (function (_super) {
  87260. __extends(MeshAssetTask, _super);
  87261. /**
  87262. * Creates a new {BABYLON.MeshAssetTask}
  87263. * @param name defines the name of the task
  87264. * @param meshesNames defines the list of mesh's names you want to load
  87265. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87266. * @param sceneFilename defines the filename of the scene to load from
  87267. */
  87268. function MeshAssetTask(
  87269. /**
  87270. * Defines the name of the task
  87271. */
  87272. name,
  87273. /**
  87274. * Defines the list of mesh's names you want to load
  87275. */
  87276. meshesNames,
  87277. /**
  87278. * Defines the root url to use as a base to load your meshes and associated resources
  87279. */
  87280. rootUrl,
  87281. /**
  87282. * Defines the filename of the scene to load from
  87283. */
  87284. sceneFilename) {
  87285. var _this = _super.call(this, name) || this;
  87286. _this.name = name;
  87287. _this.meshesNames = meshesNames;
  87288. _this.rootUrl = rootUrl;
  87289. _this.sceneFilename = sceneFilename;
  87290. return _this;
  87291. }
  87292. /**
  87293. * Execute the current task
  87294. * @param scene defines the scene where you want your assets to be loaded
  87295. * @param onSuccess is a callback called when the task is successfully executed
  87296. * @param onError is a callback called if an error occurs
  87297. */
  87298. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87299. var _this = this;
  87300. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87301. _this.loadedMeshes = meshes;
  87302. _this.loadedParticleSystems = particleSystems;
  87303. _this.loadedSkeletons = skeletons;
  87304. onSuccess();
  87305. }, null, function (scene, message, exception) {
  87306. onError(message, exception);
  87307. });
  87308. };
  87309. return MeshAssetTask;
  87310. }(AbstractAssetTask));
  87311. BABYLON.MeshAssetTask = MeshAssetTask;
  87312. /**
  87313. * Define a task used by {BABYLON.AssetsManager} to load text content
  87314. */
  87315. var TextFileAssetTask = /** @class */ (function (_super) {
  87316. __extends(TextFileAssetTask, _super);
  87317. /**
  87318. * Creates a new TextFileAssetTask object
  87319. * @param name defines the name of the task
  87320. * @param url defines the location of the file to load
  87321. */
  87322. function TextFileAssetTask(
  87323. /**
  87324. * Defines the name of the task
  87325. */
  87326. name,
  87327. /**
  87328. * Defines the location of the file to load
  87329. */
  87330. url) {
  87331. var _this = _super.call(this, name) || this;
  87332. _this.name = name;
  87333. _this.url = url;
  87334. return _this;
  87335. }
  87336. /**
  87337. * Execute the current task
  87338. * @param scene defines the scene where you want your assets to be loaded
  87339. * @param onSuccess is a callback called when the task is successfully executed
  87340. * @param onError is a callback called if an error occurs
  87341. */
  87342. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87343. var _this = this;
  87344. scene._loadFile(this.url, function (data) {
  87345. _this.text = data;
  87346. onSuccess();
  87347. }, undefined, false, false, function (request, exception) {
  87348. if (request) {
  87349. onError(request.status + " " + request.statusText, exception);
  87350. }
  87351. });
  87352. };
  87353. return TextFileAssetTask;
  87354. }(AbstractAssetTask));
  87355. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87356. /**
  87357. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87358. */
  87359. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87360. __extends(BinaryFileAssetTask, _super);
  87361. /**
  87362. * Creates a new BinaryFileAssetTask object
  87363. * @param name defines the name of the new task
  87364. * @param url defines the location of the file to load
  87365. */
  87366. function BinaryFileAssetTask(
  87367. /**
  87368. * Defines the name of the task
  87369. */
  87370. name,
  87371. /**
  87372. * Defines the location of the file to load
  87373. */
  87374. url) {
  87375. var _this = _super.call(this, name) || this;
  87376. _this.name = name;
  87377. _this.url = url;
  87378. return _this;
  87379. }
  87380. /**
  87381. * Execute the current task
  87382. * @param scene defines the scene where you want your assets to be loaded
  87383. * @param onSuccess is a callback called when the task is successfully executed
  87384. * @param onError is a callback called if an error occurs
  87385. */
  87386. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87387. var _this = this;
  87388. scene._loadFile(this.url, function (data) {
  87389. _this.data = data;
  87390. onSuccess();
  87391. }, undefined, true, true, function (request, exception) {
  87392. if (request) {
  87393. onError(request.status + " " + request.statusText, exception);
  87394. }
  87395. });
  87396. };
  87397. return BinaryFileAssetTask;
  87398. }(AbstractAssetTask));
  87399. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87400. /**
  87401. * Define a task used by {BABYLON.AssetsManager} to load images
  87402. */
  87403. var ImageAssetTask = /** @class */ (function (_super) {
  87404. __extends(ImageAssetTask, _super);
  87405. /**
  87406. * Creates a new ImageAssetTask
  87407. * @param name defines the name of the task
  87408. * @param url defines the location of the image to load
  87409. */
  87410. function ImageAssetTask(
  87411. /**
  87412. * Defines the name of the task
  87413. */
  87414. name,
  87415. /**
  87416. * Defines the location of the image to load
  87417. */
  87418. url) {
  87419. var _this = _super.call(this, name) || this;
  87420. _this.name = name;
  87421. _this.url = url;
  87422. return _this;
  87423. }
  87424. /**
  87425. * Execute the current task
  87426. * @param scene defines the scene where you want your assets to be loaded
  87427. * @param onSuccess is a callback called when the task is successfully executed
  87428. * @param onError is a callback called if an error occurs
  87429. */
  87430. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87431. var _this = this;
  87432. var img = new Image();
  87433. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87434. img.onload = function () {
  87435. _this.image = img;
  87436. onSuccess();
  87437. };
  87438. img.onerror = function (err) {
  87439. onError("Error loading image", err);
  87440. };
  87441. img.src = this.url;
  87442. };
  87443. return ImageAssetTask;
  87444. }(AbstractAssetTask));
  87445. BABYLON.ImageAssetTask = ImageAssetTask;
  87446. /**
  87447. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87448. */
  87449. var TextureAssetTask = /** @class */ (function (_super) {
  87450. __extends(TextureAssetTask, _super);
  87451. /**
  87452. * Creates a new TextureAssetTask object
  87453. * @param name defines the name of the task
  87454. * @param url defines the location of the file to load
  87455. * @param noMipmap defines if mipmap should not be generated (default is false)
  87456. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87457. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87458. */
  87459. function TextureAssetTask(
  87460. /**
  87461. * Defines the name of the task
  87462. */
  87463. name,
  87464. /**
  87465. * Defines the location of the file to load
  87466. */
  87467. url,
  87468. /**
  87469. * Defines if mipmap should not be generated (default is false)
  87470. */
  87471. noMipmap,
  87472. /**
  87473. * Defines if texture must be inverted on Y axis (default is false)
  87474. */
  87475. invertY,
  87476. /**
  87477. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87478. */
  87479. samplingMode) {
  87480. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87481. var _this = _super.call(this, name) || this;
  87482. _this.name = name;
  87483. _this.url = url;
  87484. _this.noMipmap = noMipmap;
  87485. _this.invertY = invertY;
  87486. _this.samplingMode = samplingMode;
  87487. return _this;
  87488. }
  87489. /**
  87490. * Execute the current task
  87491. * @param scene defines the scene where you want your assets to be loaded
  87492. * @param onSuccess is a callback called when the task is successfully executed
  87493. * @param onError is a callback called if an error occurs
  87494. */
  87495. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87496. var onload = function () {
  87497. onSuccess();
  87498. };
  87499. var onerror = function (message, exception) {
  87500. onError(message, exception);
  87501. };
  87502. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87503. };
  87504. return TextureAssetTask;
  87505. }(AbstractAssetTask));
  87506. BABYLON.TextureAssetTask = TextureAssetTask;
  87507. /**
  87508. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87509. */
  87510. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87511. __extends(CubeTextureAssetTask, _super);
  87512. /**
  87513. * Creates a new CubeTextureAssetTask
  87514. * @param name defines the name of the task
  87515. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87516. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87517. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87518. * @param files defines the explicit list of files (undefined by default)
  87519. */
  87520. function CubeTextureAssetTask(
  87521. /**
  87522. * Defines the name of the task
  87523. */
  87524. name,
  87525. /**
  87526. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87527. */
  87528. url,
  87529. /**
  87530. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87531. */
  87532. extensions,
  87533. /**
  87534. * Defines if mipmaps should not be generated (default is false)
  87535. */
  87536. noMipmap,
  87537. /**
  87538. * Defines the explicit list of files (undefined by default)
  87539. */
  87540. files) {
  87541. var _this = _super.call(this, name) || this;
  87542. _this.name = name;
  87543. _this.url = url;
  87544. _this.extensions = extensions;
  87545. _this.noMipmap = noMipmap;
  87546. _this.files = files;
  87547. return _this;
  87548. }
  87549. /**
  87550. * Execute the current task
  87551. * @param scene defines the scene where you want your assets to be loaded
  87552. * @param onSuccess is a callback called when the task is successfully executed
  87553. * @param onError is a callback called if an error occurs
  87554. */
  87555. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87556. var onload = function () {
  87557. onSuccess();
  87558. };
  87559. var onerror = function (message, exception) {
  87560. onError(message, exception);
  87561. };
  87562. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87563. };
  87564. return CubeTextureAssetTask;
  87565. }(AbstractAssetTask));
  87566. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87567. /**
  87568. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87569. */
  87570. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87571. __extends(HDRCubeTextureAssetTask, _super);
  87572. /**
  87573. * Creates a new HDRCubeTextureAssetTask object
  87574. * @param name defines the name of the task
  87575. * @param url defines the location of the file to load
  87576. * @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.
  87577. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87578. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87579. * @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)
  87580. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87581. */
  87582. function HDRCubeTextureAssetTask(
  87583. /**
  87584. * Defines the name of the task
  87585. */
  87586. name,
  87587. /**
  87588. * Defines the location of the file to load
  87589. */
  87590. url,
  87591. /**
  87592. * 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.
  87593. */
  87594. size,
  87595. /**
  87596. * Defines if mipmaps should not be generated (default is false)
  87597. */
  87598. noMipmap,
  87599. /**
  87600. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87601. */
  87602. generateHarmonics,
  87603. /**
  87604. * 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)
  87605. */
  87606. useInGammaSpace,
  87607. /**
  87608. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87609. */
  87610. usePMREMGenerator) {
  87611. if (noMipmap === void 0) { noMipmap = false; }
  87612. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87613. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87614. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87615. var _this = _super.call(this, name) || this;
  87616. _this.name = name;
  87617. _this.url = url;
  87618. _this.size = size;
  87619. _this.noMipmap = noMipmap;
  87620. _this.generateHarmonics = generateHarmonics;
  87621. _this.useInGammaSpace = useInGammaSpace;
  87622. _this.usePMREMGenerator = usePMREMGenerator;
  87623. return _this;
  87624. }
  87625. /**
  87626. * Execute the current task
  87627. * @param scene defines the scene where you want your assets to be loaded
  87628. * @param onSuccess is a callback called when the task is successfully executed
  87629. * @param onError is a callback called if an error occurs
  87630. */
  87631. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87632. var onload = function () {
  87633. onSuccess();
  87634. };
  87635. var onerror = function (message, exception) {
  87636. onError(message, exception);
  87637. };
  87638. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87639. };
  87640. return HDRCubeTextureAssetTask;
  87641. }(AbstractAssetTask));
  87642. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87643. /**
  87644. * This class can be used to easily import assets into a scene
  87645. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87646. */
  87647. var AssetsManager = /** @class */ (function () {
  87648. /**
  87649. * Creates a new AssetsManager
  87650. * @param scene defines the scene to work on
  87651. */
  87652. function AssetsManager(scene) {
  87653. this._isLoading = false;
  87654. this._tasks = new Array();
  87655. this._waitingTasksCount = 0;
  87656. this._totalTasksCount = 0;
  87657. /**
  87658. * Observable called when all tasks are processed
  87659. */
  87660. this.onTaskSuccessObservable = new BABYLON.Observable();
  87661. /**
  87662. * Observable called when a task had an error
  87663. */
  87664. this.onTaskErrorObservable = new BABYLON.Observable();
  87665. /**
  87666. * Observable called when a task is successful
  87667. */
  87668. this.onTasksDoneObservable = new BABYLON.Observable();
  87669. /**
  87670. * Observable called when a task is done (whatever the result is)
  87671. */
  87672. this.onProgressObservable = new BABYLON.Observable();
  87673. /**
  87674. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87675. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87676. */
  87677. this.useDefaultLoadingScreen = true;
  87678. this._scene = scene;
  87679. }
  87680. /**
  87681. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87682. * @param taskName defines the name of the new task
  87683. * @param meshesNames defines the name of meshes to load
  87684. * @param rootUrl defines the root url to use to locate files
  87685. * @param sceneFilename defines the filename of the scene file
  87686. * @returns a new {BABYLON.MeshAssetTask} object
  87687. */
  87688. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87689. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87690. this._tasks.push(task);
  87691. return task;
  87692. };
  87693. /**
  87694. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87695. * @param taskName defines the name of the new task
  87696. * @param url defines the url of the file to load
  87697. * @returns a new {BABYLON.TextFileAssetTask} object
  87698. */
  87699. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87700. var task = new TextFileAssetTask(taskName, url);
  87701. this._tasks.push(task);
  87702. return task;
  87703. };
  87704. /**
  87705. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  87706. * @param taskName defines the name of the new task
  87707. * @param url defines the url of the file to load
  87708. * @returns a new {BABYLON.BinaryFileAssetTask} object
  87709. */
  87710. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  87711. var task = new BinaryFileAssetTask(taskName, url);
  87712. this._tasks.push(task);
  87713. return task;
  87714. };
  87715. /**
  87716. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  87717. * @param taskName defines the name of the new task
  87718. * @param url defines the url of the file to load
  87719. * @returns a new {BABYLON.ImageAssetTask} object
  87720. */
  87721. AssetsManager.prototype.addImageTask = function (taskName, url) {
  87722. var task = new ImageAssetTask(taskName, url);
  87723. this._tasks.push(task);
  87724. return task;
  87725. };
  87726. /**
  87727. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  87728. * @param taskName defines the name of the new task
  87729. * @param url defines the url of the file to load
  87730. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87731. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  87732. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  87733. * @returns a new {BABYLON.TextureAssetTask} object
  87734. */
  87735. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  87736. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87737. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  87738. this._tasks.push(task);
  87739. return task;
  87740. };
  87741. /**
  87742. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  87743. * @param taskName defines the name of the new task
  87744. * @param url defines the url of the file to load
  87745. * @param extensions defines the extension to use to load the cube map (can be null)
  87746. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87747. * @param files defines the list of files to load (can be null)
  87748. * @returns a new {BABYLON.CubeTextureAssetTask} object
  87749. */
  87750. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  87751. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  87752. this._tasks.push(task);
  87753. return task;
  87754. };
  87755. /**
  87756. *
  87757. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  87758. * @param taskName defines the name of the new task
  87759. * @param url defines the url of the file to load
  87760. * @param size defines the size you want for the cubemap (can be null)
  87761. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87762. * @param generateHarmonics defines if you want to automatically generate (true by default)
  87763. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  87764. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  87765. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  87766. */
  87767. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  87768. if (noMipmap === void 0) { noMipmap = false; }
  87769. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87770. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87771. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87772. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  87773. this._tasks.push(task);
  87774. return task;
  87775. };
  87776. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  87777. var _this = this;
  87778. this._waitingTasksCount--;
  87779. try {
  87780. if (task.taskState === AssetTaskState.DONE) {
  87781. // Let's remove successfull tasks
  87782. BABYLON.Tools.SetImmediate(function () {
  87783. var index = _this._tasks.indexOf(task);
  87784. if (index > -1) {
  87785. _this._tasks.splice(index, 1);
  87786. }
  87787. });
  87788. }
  87789. if (this.onProgress) {
  87790. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  87791. }
  87792. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  87793. }
  87794. catch (e) {
  87795. BABYLON.Tools.Error("Error running progress callbacks.");
  87796. console.log(e);
  87797. }
  87798. if (this._waitingTasksCount === 0) {
  87799. try {
  87800. if (this.onFinish) {
  87801. this.onFinish(this._tasks);
  87802. }
  87803. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87804. }
  87805. catch (e) {
  87806. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  87807. console.log(e);
  87808. }
  87809. this._isLoading = false;
  87810. this._scene.getEngine().hideLoadingUI();
  87811. }
  87812. };
  87813. AssetsManager.prototype._runTask = function (task) {
  87814. var _this = this;
  87815. var done = function () {
  87816. try {
  87817. if (_this.onTaskSuccess) {
  87818. _this.onTaskSuccess(task);
  87819. }
  87820. _this.onTaskSuccessObservable.notifyObservers(task);
  87821. _this._decreaseWaitingTasksCount(task);
  87822. }
  87823. catch (e) {
  87824. error("Error executing task success callbacks", e);
  87825. }
  87826. };
  87827. var error = function (message, exception) {
  87828. task._setErrorObject(message, exception);
  87829. if (_this.onTaskError) {
  87830. _this.onTaskError(task);
  87831. }
  87832. _this.onTaskErrorObservable.notifyObservers(task);
  87833. _this._decreaseWaitingTasksCount(task);
  87834. };
  87835. task.run(this._scene, done, error);
  87836. };
  87837. /**
  87838. * Reset the {BABYLON.AssetsManager} and remove all tasks
  87839. * @return the current instance of the {BABYLON.AssetsManager}
  87840. */
  87841. AssetsManager.prototype.reset = function () {
  87842. this._isLoading = false;
  87843. this._tasks = new Array();
  87844. return this;
  87845. };
  87846. /**
  87847. * Start the loading process
  87848. * @return the current instance of the {BABYLON.AssetsManager}
  87849. */
  87850. AssetsManager.prototype.load = function () {
  87851. if (this._isLoading) {
  87852. return this;
  87853. }
  87854. this._isLoading = true;
  87855. this._waitingTasksCount = this._tasks.length;
  87856. this._totalTasksCount = this._tasks.length;
  87857. if (this._waitingTasksCount === 0) {
  87858. this._isLoading = false;
  87859. if (this.onFinish) {
  87860. this.onFinish(this._tasks);
  87861. }
  87862. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87863. return this;
  87864. }
  87865. if (this.useDefaultLoadingScreen) {
  87866. this._scene.getEngine().displayLoadingUI();
  87867. }
  87868. for (var index = 0; index < this._tasks.length; index++) {
  87869. var task = this._tasks[index];
  87870. this._runTask(task);
  87871. }
  87872. return this;
  87873. };
  87874. return AssetsManager;
  87875. }());
  87876. BABYLON.AssetsManager = AssetsManager;
  87877. })(BABYLON || (BABYLON = {}));
  87878. //# sourceMappingURL=babylon.assetsManager.js.map
  87879. var BABYLON;
  87880. (function (BABYLON) {
  87881. var serializedGeometries = [];
  87882. var serializeGeometry = function (geometry, serializationGeometries) {
  87883. if (serializedGeometries[geometry.id]) {
  87884. return;
  87885. }
  87886. if (geometry.doNotSerialize) {
  87887. return;
  87888. }
  87889. if (geometry instanceof BABYLON.BoxGeometry) {
  87890. serializationGeometries.boxes.push(geometry.serialize());
  87891. }
  87892. else if (geometry instanceof BABYLON.SphereGeometry) {
  87893. serializationGeometries.spheres.push(geometry.serialize());
  87894. }
  87895. else if (geometry instanceof BABYLON.CylinderGeometry) {
  87896. serializationGeometries.cylinders.push(geometry.serialize());
  87897. }
  87898. else if (geometry instanceof BABYLON.TorusGeometry) {
  87899. serializationGeometries.toruses.push(geometry.serialize());
  87900. }
  87901. else if (geometry instanceof BABYLON.GroundGeometry) {
  87902. serializationGeometries.grounds.push(geometry.serialize());
  87903. }
  87904. else if (geometry instanceof BABYLON.Plane) {
  87905. serializationGeometries.planes.push(geometry.serialize());
  87906. }
  87907. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87908. serializationGeometries.torusKnots.push(geometry.serialize());
  87909. }
  87910. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87911. throw new Error("Unknown primitive type");
  87912. }
  87913. else {
  87914. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87915. }
  87916. serializedGeometries[geometry.id] = true;
  87917. };
  87918. var serializeMesh = function (mesh, serializationScene) {
  87919. var serializationObject = {};
  87920. // Geometry
  87921. var geometry = mesh._geometry;
  87922. if (geometry) {
  87923. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87924. // 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
  87925. serializeGeometry(geometry, serializationScene.geometries);
  87926. }
  87927. }
  87928. // Custom
  87929. if (mesh.serialize) {
  87930. mesh.serialize(serializationObject);
  87931. }
  87932. return serializationObject;
  87933. };
  87934. var finalizeSingleMesh = function (mesh, serializationObject) {
  87935. //only works if the mesh is already loaded
  87936. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87937. //serialize material
  87938. if (mesh.material) {
  87939. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87940. serializationObject.materials = serializationObject.materials || [];
  87941. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87942. serializationObject.materials.push(mesh.material.serialize());
  87943. }
  87944. }
  87945. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87946. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87947. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87948. serializationObject.multiMaterials.push(mesh.material.serialize());
  87949. }
  87950. }
  87951. }
  87952. //serialize geometry
  87953. var geometry = mesh._geometry;
  87954. if (geometry) {
  87955. if (!serializationObject.geometries) {
  87956. serializationObject.geometries = {};
  87957. serializationObject.geometries.boxes = [];
  87958. serializationObject.geometries.spheres = [];
  87959. serializationObject.geometries.cylinders = [];
  87960. serializationObject.geometries.toruses = [];
  87961. serializationObject.geometries.grounds = [];
  87962. serializationObject.geometries.planes = [];
  87963. serializationObject.geometries.torusKnots = [];
  87964. serializationObject.geometries.vertexData = [];
  87965. }
  87966. serializeGeometry(geometry, serializationObject.geometries);
  87967. }
  87968. // Skeletons
  87969. if (mesh.skeleton) {
  87970. serializationObject.skeletons = serializationObject.skeletons || [];
  87971. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87972. }
  87973. //serialize the actual mesh
  87974. serializationObject.meshes = serializationObject.meshes || [];
  87975. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87976. }
  87977. };
  87978. var SceneSerializer = /** @class */ (function () {
  87979. function SceneSerializer() {
  87980. }
  87981. SceneSerializer.ClearCache = function () {
  87982. serializedGeometries = [];
  87983. };
  87984. SceneSerializer.Serialize = function (scene) {
  87985. var serializationObject = {};
  87986. SceneSerializer.ClearCache();
  87987. // Scene
  87988. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87989. serializationObject.autoClear = scene.autoClear;
  87990. serializationObject.clearColor = scene.clearColor.asArray();
  87991. serializationObject.ambientColor = scene.ambientColor.asArray();
  87992. serializationObject.gravity = scene.gravity.asArray();
  87993. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87994. serializationObject.workerCollisions = scene.workerCollisions;
  87995. // Fog
  87996. if (scene.fogMode && scene.fogMode !== 0) {
  87997. serializationObject.fogMode = scene.fogMode;
  87998. serializationObject.fogColor = scene.fogColor.asArray();
  87999. serializationObject.fogStart = scene.fogStart;
  88000. serializationObject.fogEnd = scene.fogEnd;
  88001. serializationObject.fogDensity = scene.fogDensity;
  88002. }
  88003. //Physics
  88004. if (scene.isPhysicsEnabled()) {
  88005. var physicEngine = scene.getPhysicsEngine();
  88006. if (physicEngine) {
  88007. serializationObject.physicsEnabled = true;
  88008. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88009. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88010. }
  88011. }
  88012. // Metadata
  88013. if (scene.metadata) {
  88014. serializationObject.metadata = scene.metadata;
  88015. }
  88016. // Morph targets
  88017. serializationObject.morphTargetManagers = [];
  88018. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88019. var abstractMesh = _a[_i];
  88020. var manager = abstractMesh.morphTargetManager;
  88021. if (manager) {
  88022. serializationObject.morphTargetManagers.push(manager.serialize());
  88023. }
  88024. }
  88025. // Lights
  88026. serializationObject.lights = [];
  88027. var index;
  88028. var light;
  88029. for (index = 0; index < scene.lights.length; index++) {
  88030. light = scene.lights[index];
  88031. if (!light.doNotSerialize) {
  88032. serializationObject.lights.push(light.serialize());
  88033. }
  88034. }
  88035. // Cameras
  88036. serializationObject.cameras = [];
  88037. for (index = 0; index < scene.cameras.length; index++) {
  88038. var camera = scene.cameras[index];
  88039. if (!camera.doNotSerialize) {
  88040. serializationObject.cameras.push(camera.serialize());
  88041. }
  88042. }
  88043. if (scene.activeCamera) {
  88044. serializationObject.activeCameraID = scene.activeCamera.id;
  88045. }
  88046. // Animations
  88047. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88048. // Materials
  88049. serializationObject.materials = [];
  88050. serializationObject.multiMaterials = [];
  88051. var material;
  88052. for (index = 0; index < scene.materials.length; index++) {
  88053. material = scene.materials[index];
  88054. if (!material.doNotSerialize) {
  88055. serializationObject.materials.push(material.serialize());
  88056. }
  88057. }
  88058. // MultiMaterials
  88059. serializationObject.multiMaterials = [];
  88060. for (index = 0; index < scene.multiMaterials.length; index++) {
  88061. var multiMaterial = scene.multiMaterials[index];
  88062. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88063. }
  88064. // Environment texture
  88065. if (scene.environmentTexture) {
  88066. serializationObject.environmentTexture = scene.environmentTexture.name;
  88067. }
  88068. // Skeletons
  88069. serializationObject.skeletons = [];
  88070. for (index = 0; index < scene.skeletons.length; index++) {
  88071. var skeleton = scene.skeletons[index];
  88072. if (!skeleton.doNotSerialize) {
  88073. serializationObject.skeletons.push(skeleton.serialize());
  88074. }
  88075. }
  88076. // Transform nodes
  88077. serializationObject.transformNodes = [];
  88078. for (index = 0; index < scene.transformNodes.length; index++) {
  88079. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88080. }
  88081. // Geometries
  88082. serializationObject.geometries = {};
  88083. serializationObject.geometries.boxes = [];
  88084. serializationObject.geometries.spheres = [];
  88085. serializationObject.geometries.cylinders = [];
  88086. serializationObject.geometries.toruses = [];
  88087. serializationObject.geometries.grounds = [];
  88088. serializationObject.geometries.planes = [];
  88089. serializationObject.geometries.torusKnots = [];
  88090. serializationObject.geometries.vertexData = [];
  88091. serializedGeometries = [];
  88092. var geometries = scene.getGeometries();
  88093. for (index = 0; index < geometries.length; index++) {
  88094. var geometry = geometries[index];
  88095. if (geometry.isReady()) {
  88096. serializeGeometry(geometry, serializationObject.geometries);
  88097. }
  88098. }
  88099. // Meshes
  88100. serializationObject.meshes = [];
  88101. for (index = 0; index < scene.meshes.length; index++) {
  88102. var abstractMesh = scene.meshes[index];
  88103. if (abstractMesh instanceof BABYLON.Mesh) {
  88104. var mesh = abstractMesh;
  88105. if (!mesh.doNotSerialize) {
  88106. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88107. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88108. }
  88109. }
  88110. }
  88111. }
  88112. // Particles Systems
  88113. serializationObject.particleSystems = [];
  88114. for (index = 0; index < scene.particleSystems.length; index++) {
  88115. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88116. }
  88117. // Lens flares
  88118. serializationObject.lensFlareSystems = [];
  88119. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88120. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88121. }
  88122. // Shadows
  88123. serializationObject.shadowGenerators = [];
  88124. for (index = 0; index < scene.lights.length; index++) {
  88125. light = scene.lights[index];
  88126. var shadowGenerator = light.getShadowGenerator();
  88127. if (shadowGenerator) {
  88128. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88129. }
  88130. }
  88131. // Action Manager
  88132. if (scene.actionManager) {
  88133. serializationObject.actions = scene.actionManager.serialize("scene");
  88134. }
  88135. // Audio
  88136. serializationObject.sounds = [];
  88137. for (index = 0; index < scene.soundTracks.length; index++) {
  88138. var soundtrack = scene.soundTracks[index];
  88139. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88140. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88141. }
  88142. }
  88143. return serializationObject;
  88144. };
  88145. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88146. if (withParents === void 0) { withParents = false; }
  88147. if (withChildren === void 0) { withChildren = false; }
  88148. var serializationObject = {};
  88149. SceneSerializer.ClearCache();
  88150. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88151. if (withParents || withChildren) {
  88152. //deliberate for loop! not for each, appended should be processed as well.
  88153. for (var i = 0; i < toSerialize.length; ++i) {
  88154. if (withChildren) {
  88155. toSerialize[i].getDescendants().forEach(function (node) {
  88156. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88157. toSerialize.push(node);
  88158. }
  88159. });
  88160. }
  88161. //make sure the array doesn't contain the object already
  88162. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88163. toSerialize.push(toSerialize[i].parent);
  88164. }
  88165. }
  88166. }
  88167. toSerialize.forEach(function (mesh) {
  88168. finalizeSingleMesh(mesh, serializationObject);
  88169. });
  88170. return serializationObject;
  88171. };
  88172. return SceneSerializer;
  88173. }());
  88174. BABYLON.SceneSerializer = SceneSerializer;
  88175. })(BABYLON || (BABYLON = {}));
  88176. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88177. var BABYLON;
  88178. (function (BABYLON) {
  88179. var ReflectionProbe = /** @class */ (function () {
  88180. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88181. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88182. var _this = this;
  88183. this.name = name;
  88184. this._viewMatrix = BABYLON.Matrix.Identity();
  88185. this._target = BABYLON.Vector3.Zero();
  88186. this._add = BABYLON.Vector3.Zero();
  88187. this._invertYAxis = false;
  88188. this.position = BABYLON.Vector3.Zero();
  88189. this._scene = scene;
  88190. this._scene.reflectionProbes.push(this);
  88191. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88192. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88193. switch (faceIndex) {
  88194. case 0:
  88195. _this._add.copyFromFloats(1, 0, 0);
  88196. break;
  88197. case 1:
  88198. _this._add.copyFromFloats(-1, 0, 0);
  88199. break;
  88200. case 2:
  88201. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88202. break;
  88203. case 3:
  88204. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88205. break;
  88206. case 4:
  88207. _this._add.copyFromFloats(0, 0, 1);
  88208. break;
  88209. case 5:
  88210. _this._add.copyFromFloats(0, 0, -1);
  88211. break;
  88212. }
  88213. if (_this._attachedMesh) {
  88214. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88215. }
  88216. _this.position.addToRef(_this._add, _this._target);
  88217. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88218. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88219. scene._forcedViewPosition = _this.position;
  88220. });
  88221. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88222. scene._forcedViewPosition = null;
  88223. scene.updateTransformMatrix(true);
  88224. });
  88225. if (scene.activeCamera) {
  88226. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88227. }
  88228. }
  88229. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88230. get: function () {
  88231. return this._renderTargetTexture.samples;
  88232. },
  88233. set: function (value) {
  88234. this._renderTargetTexture.samples = value;
  88235. },
  88236. enumerable: true,
  88237. configurable: true
  88238. });
  88239. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88240. get: function () {
  88241. return this._renderTargetTexture.refreshRate;
  88242. },
  88243. set: function (value) {
  88244. this._renderTargetTexture.refreshRate = value;
  88245. },
  88246. enumerable: true,
  88247. configurable: true
  88248. });
  88249. ReflectionProbe.prototype.getScene = function () {
  88250. return this._scene;
  88251. };
  88252. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88253. get: function () {
  88254. return this._renderTargetTexture;
  88255. },
  88256. enumerable: true,
  88257. configurable: true
  88258. });
  88259. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88260. get: function () {
  88261. return this._renderTargetTexture.renderList;
  88262. },
  88263. enumerable: true,
  88264. configurable: true
  88265. });
  88266. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88267. this._attachedMesh = mesh;
  88268. };
  88269. /**
  88270. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88271. *
  88272. * @param renderingGroupId The rendering group id corresponding to its index
  88273. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88274. */
  88275. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88276. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88277. };
  88278. ReflectionProbe.prototype.dispose = function () {
  88279. var index = this._scene.reflectionProbes.indexOf(this);
  88280. if (index !== -1) {
  88281. // Remove from the scene if found
  88282. this._scene.reflectionProbes.splice(index, 1);
  88283. }
  88284. if (this._renderTargetTexture) {
  88285. this._renderTargetTexture.dispose();
  88286. this._renderTargetTexture = null;
  88287. }
  88288. };
  88289. return ReflectionProbe;
  88290. }());
  88291. BABYLON.ReflectionProbe = ReflectionProbe;
  88292. })(BABYLON || (BABYLON = {}));
  88293. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88294. var BABYLON;
  88295. (function (BABYLON) {
  88296. var Layer = /** @class */ (function () {
  88297. function Layer(name, imgUrl, scene, isBackground, color) {
  88298. this.name = name;
  88299. this.scale = new BABYLON.Vector2(1, 1);
  88300. this.offset = new BABYLON.Vector2(0, 0);
  88301. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88302. this.layerMask = 0x0FFFFFFF;
  88303. this._vertexBuffers = {};
  88304. // Events
  88305. /**
  88306. * An event triggered when the layer is disposed.
  88307. * @type {BABYLON.Observable}
  88308. */
  88309. this.onDisposeObservable = new BABYLON.Observable();
  88310. /**
  88311. * An event triggered before rendering the scene
  88312. * @type {BABYLON.Observable}
  88313. */
  88314. this.onBeforeRenderObservable = new BABYLON.Observable();
  88315. /**
  88316. * An event triggered after rendering the scene
  88317. * @type {BABYLON.Observable}
  88318. */
  88319. this.onAfterRenderObservable = new BABYLON.Observable();
  88320. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88321. this.isBackground = isBackground === undefined ? true : isBackground;
  88322. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88323. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88324. this._scene.layers.push(this);
  88325. var engine = this._scene.getEngine();
  88326. // VBO
  88327. var vertices = [];
  88328. vertices.push(1, 1);
  88329. vertices.push(-1, 1);
  88330. vertices.push(-1, -1);
  88331. vertices.push(1, -1);
  88332. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88333. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88334. this._createIndexBuffer();
  88335. // Effects
  88336. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88337. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88338. }
  88339. Object.defineProperty(Layer.prototype, "onDispose", {
  88340. set: function (callback) {
  88341. if (this._onDisposeObserver) {
  88342. this.onDisposeObservable.remove(this._onDisposeObserver);
  88343. }
  88344. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88345. },
  88346. enumerable: true,
  88347. configurable: true
  88348. });
  88349. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88350. set: function (callback) {
  88351. if (this._onBeforeRenderObserver) {
  88352. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88353. }
  88354. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88355. },
  88356. enumerable: true,
  88357. configurable: true
  88358. });
  88359. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88360. set: function (callback) {
  88361. if (this._onAfterRenderObserver) {
  88362. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88363. }
  88364. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88365. },
  88366. enumerable: true,
  88367. configurable: true
  88368. });
  88369. Layer.prototype._createIndexBuffer = function () {
  88370. var engine = this._scene.getEngine();
  88371. // Indices
  88372. var indices = [];
  88373. indices.push(0);
  88374. indices.push(1);
  88375. indices.push(2);
  88376. indices.push(0);
  88377. indices.push(2);
  88378. indices.push(3);
  88379. this._indexBuffer = engine.createIndexBuffer(indices);
  88380. };
  88381. Layer.prototype._rebuild = function () {
  88382. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88383. if (vb) {
  88384. vb._rebuild();
  88385. }
  88386. this._createIndexBuffer();
  88387. };
  88388. Layer.prototype.render = function () {
  88389. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88390. // Check
  88391. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88392. return;
  88393. var engine = this._scene.getEngine();
  88394. this.onBeforeRenderObservable.notifyObservers(this);
  88395. // Render
  88396. engine.enableEffect(currentEffect);
  88397. engine.setState(false);
  88398. // Texture
  88399. currentEffect.setTexture("textureSampler", this.texture);
  88400. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88401. // Color
  88402. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88403. // Scale / offset
  88404. currentEffect.setVector2("offset", this.offset);
  88405. currentEffect.setVector2("scale", this.scale);
  88406. // VBOs
  88407. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88408. // Draw order
  88409. if (!this.alphaTest) {
  88410. engine.setAlphaMode(this.alphaBlendingMode);
  88411. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88412. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88413. }
  88414. else {
  88415. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88416. }
  88417. this.onAfterRenderObservable.notifyObservers(this);
  88418. };
  88419. Layer.prototype.dispose = function () {
  88420. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88421. if (vertexBuffer) {
  88422. vertexBuffer.dispose();
  88423. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88424. }
  88425. if (this._indexBuffer) {
  88426. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88427. this._indexBuffer = null;
  88428. }
  88429. if (this.texture) {
  88430. this.texture.dispose();
  88431. this.texture = null;
  88432. }
  88433. // Remove from scene
  88434. var index = this._scene.layers.indexOf(this);
  88435. this._scene.layers.splice(index, 1);
  88436. // Callback
  88437. this.onDisposeObservable.notifyObservers(this);
  88438. this.onDisposeObservable.clear();
  88439. this.onAfterRenderObservable.clear();
  88440. this.onBeforeRenderObservable.clear();
  88441. };
  88442. return Layer;
  88443. }());
  88444. BABYLON.Layer = Layer;
  88445. })(BABYLON || (BABYLON = {}));
  88446. //# sourceMappingURL=babylon.layer.js.map
  88447. var BABYLON;
  88448. (function (BABYLON) {
  88449. var TextureTools = /** @class */ (function () {
  88450. function TextureTools() {
  88451. }
  88452. /**
  88453. * Uses the GPU to create a copy texture rescaled at a given size
  88454. * @param texture Texture to copy from
  88455. * @param width Desired width
  88456. * @param height Desired height
  88457. * @return Generated texture
  88458. */
  88459. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88460. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88461. var scene = texture.getScene();
  88462. var engine = scene.getEngine();
  88463. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88464. rtt.wrapU = texture.wrapU;
  88465. rtt.wrapV = texture.wrapV;
  88466. rtt.uOffset = texture.uOffset;
  88467. rtt.vOffset = texture.vOffset;
  88468. rtt.uScale = texture.uScale;
  88469. rtt.vScale = texture.vScale;
  88470. rtt.uAng = texture.uAng;
  88471. rtt.vAng = texture.vAng;
  88472. rtt.wAng = texture.wAng;
  88473. rtt.coordinatesIndex = texture.coordinatesIndex;
  88474. rtt.level = texture.level;
  88475. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88476. rtt._texture.isReady = false;
  88477. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88478. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88479. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88480. passPostProcess.getEffect().executeWhenCompiled(function () {
  88481. passPostProcess.onApply = function (effect) {
  88482. effect.setTexture("textureSampler", texture);
  88483. };
  88484. var internalTexture = rtt.getInternalTexture();
  88485. if (internalTexture) {
  88486. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88487. engine.unBindFramebuffer(internalTexture);
  88488. rtt.disposeFramebufferObjects();
  88489. passPostProcess.dispose();
  88490. internalTexture.isReady = true;
  88491. }
  88492. });
  88493. return rtt;
  88494. };
  88495. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88496. if (!scene._environmentBRDFTexture) {
  88497. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88498. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88499. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88500. scene._environmentBRDFTexture = texture;
  88501. }
  88502. return scene._environmentBRDFTexture;
  88503. };
  88504. 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=";
  88505. return TextureTools;
  88506. }());
  88507. BABYLON.TextureTools = TextureTools;
  88508. })(BABYLON || (BABYLON = {}));
  88509. //# sourceMappingURL=babylon.textureTools.js.map
  88510. var BABYLON;
  88511. (function (BABYLON) {
  88512. var FramingBehavior = /** @class */ (function () {
  88513. function FramingBehavior() {
  88514. this._mode = FramingBehavior.FitFrustumSidesMode;
  88515. this._radiusScale = 1.0;
  88516. this._positionScale = 0.5;
  88517. this._defaultElevation = 0.3;
  88518. this._elevationReturnTime = 1500;
  88519. this._elevationReturnWaitTime = 1000;
  88520. this._zoomStopsAnimation = false;
  88521. this._framingTime = 1500;
  88522. this._isPointerDown = false;
  88523. this._lastInteractionTime = -Infinity;
  88524. // Framing control
  88525. this._animatables = new Array();
  88526. this._betaIsAnimating = false;
  88527. }
  88528. Object.defineProperty(FramingBehavior.prototype, "name", {
  88529. get: function () {
  88530. return "Framing";
  88531. },
  88532. enumerable: true,
  88533. configurable: true
  88534. });
  88535. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88536. /**
  88537. * Gets current mode used by the behavior.
  88538. */
  88539. get: function () {
  88540. return this._mode;
  88541. },
  88542. /**
  88543. * Sets the current mode used by the behavior
  88544. */
  88545. set: function (mode) {
  88546. this._mode = mode;
  88547. },
  88548. enumerable: true,
  88549. configurable: true
  88550. });
  88551. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88552. /**
  88553. * Gets the scale applied to the radius
  88554. */
  88555. get: function () {
  88556. return this._radiusScale;
  88557. },
  88558. /**
  88559. * Sets the scale applied to the radius (1 by default)
  88560. */
  88561. set: function (radius) {
  88562. this._radiusScale = radius;
  88563. },
  88564. enumerable: true,
  88565. configurable: true
  88566. });
  88567. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88568. /**
  88569. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88570. */
  88571. get: function () {
  88572. return this._positionScale;
  88573. },
  88574. /**
  88575. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88576. */
  88577. set: function (scale) {
  88578. this._positionScale = scale;
  88579. },
  88580. enumerable: true,
  88581. configurable: true
  88582. });
  88583. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88584. /**
  88585. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88586. * behaviour is triggered, in radians.
  88587. */
  88588. get: function () {
  88589. return this._defaultElevation;
  88590. },
  88591. /**
  88592. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88593. * behaviour is triggered, in radians.
  88594. */
  88595. set: function (elevation) {
  88596. this._defaultElevation = elevation;
  88597. },
  88598. enumerable: true,
  88599. configurable: true
  88600. });
  88601. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88602. /**
  88603. * Gets the time (in milliseconds) taken to return to the default beta position.
  88604. * Negative value indicates camera should not return to default.
  88605. */
  88606. get: function () {
  88607. return this._elevationReturnTime;
  88608. },
  88609. /**
  88610. * Sets the time (in milliseconds) taken to return to the default beta position.
  88611. * Negative value indicates camera should not return to default.
  88612. */
  88613. set: function (speed) {
  88614. this._elevationReturnTime = speed;
  88615. },
  88616. enumerable: true,
  88617. configurable: true
  88618. });
  88619. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88620. /**
  88621. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88622. */
  88623. get: function () {
  88624. return this._elevationReturnWaitTime;
  88625. },
  88626. /**
  88627. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88628. */
  88629. set: function (time) {
  88630. this._elevationReturnWaitTime = time;
  88631. },
  88632. enumerable: true,
  88633. configurable: true
  88634. });
  88635. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88636. /**
  88637. * Gets the flag that indicates if user zooming should stop animation.
  88638. */
  88639. get: function () {
  88640. return this._zoomStopsAnimation;
  88641. },
  88642. /**
  88643. * Sets the flag that indicates if user zooming should stop animation.
  88644. */
  88645. set: function (flag) {
  88646. this._zoomStopsAnimation = flag;
  88647. },
  88648. enumerable: true,
  88649. configurable: true
  88650. });
  88651. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88652. /**
  88653. * Gets the transition time when framing the mesh, in milliseconds
  88654. */
  88655. get: function () {
  88656. return this._framingTime;
  88657. },
  88658. /**
  88659. * Sets the transition time when framing the mesh, in milliseconds
  88660. */
  88661. set: function (time) {
  88662. this._framingTime = time;
  88663. },
  88664. enumerable: true,
  88665. configurable: true
  88666. });
  88667. FramingBehavior.prototype.init = function () {
  88668. // Do notihng
  88669. };
  88670. FramingBehavior.prototype.attach = function (camera) {
  88671. var _this = this;
  88672. this._attachedCamera = camera;
  88673. var scene = this._attachedCamera.getScene();
  88674. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  88675. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88676. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88677. _this._isPointerDown = true;
  88678. return;
  88679. }
  88680. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88681. _this._isPointerDown = false;
  88682. }
  88683. });
  88684. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88685. if (mesh) {
  88686. _this.zoomOnMesh(mesh);
  88687. }
  88688. });
  88689. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88690. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88691. _this._applyUserInteraction();
  88692. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88693. // back to the default position after a given timeout
  88694. _this._maintainCameraAboveGround();
  88695. });
  88696. };
  88697. FramingBehavior.prototype.detach = function () {
  88698. if (!this._attachedCamera) {
  88699. return;
  88700. }
  88701. var scene = this._attachedCamera.getScene();
  88702. if (this._onPrePointerObservableObserver) {
  88703. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88704. }
  88705. if (this._onAfterCheckInputsObserver) {
  88706. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88707. }
  88708. if (this._onMeshTargetChangedObserver) {
  88709. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88710. }
  88711. this._attachedCamera = null;
  88712. };
  88713. /**
  88714. * Targets the given mesh and updates zoom level accordingly.
  88715. * @param mesh The mesh to target.
  88716. * @param radius Optional. If a cached radius position already exists, overrides default.
  88717. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88718. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88719. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88720. */
  88721. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88722. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88723. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88724. mesh.computeWorldMatrix(true);
  88725. var boundingBox = mesh.getBoundingInfo().boundingBox;
  88726. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  88727. };
  88728. /**
  88729. * Targets the given mesh with its children and updates zoom level accordingly.
  88730. * @param mesh The mesh to target.
  88731. * @param radius Optional. If a cached radius position already exists, overrides default.
  88732. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88733. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88734. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88735. */
  88736. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88737. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88738. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88739. mesh.computeWorldMatrix(true);
  88740. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  88741. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  88742. };
  88743. /**
  88744. * Targets the given meshes with their children and updates zoom level accordingly.
  88745. * @param meshes The mesh to target.
  88746. * @param radius Optional. If a cached radius position already exists, overrides default.
  88747. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88748. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88749. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88750. */
  88751. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  88752. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88753. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88754. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  88755. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  88756. for (var i = 0; i < meshes.length; i++) {
  88757. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  88758. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  88759. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  88760. }
  88761. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  88762. };
  88763. /**
  88764. * Targets the given mesh and updates zoom level accordingly.
  88765. * @param mesh The mesh to target.
  88766. * @param radius Optional. If a cached radius position already exists, overrides default.
  88767. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88768. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88769. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88770. */
  88771. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  88772. var _this = this;
  88773. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88774. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88775. var zoomTarget;
  88776. if (!this._attachedCamera) {
  88777. return;
  88778. }
  88779. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  88780. var bottom = minimumWorld.y;
  88781. var top = maximumWorld.y;
  88782. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  88783. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  88784. if (focusOnOriginXZ) {
  88785. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  88786. }
  88787. else {
  88788. var centerWorld = minimumWorld.add(radiusWorld);
  88789. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  88790. }
  88791. if (!this._vectorTransition) {
  88792. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  88793. }
  88794. this._betaIsAnimating = true;
  88795. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  88796. if (animatable) {
  88797. this._animatables.push(animatable);
  88798. }
  88799. // sets the radius and lower radius bounds
  88800. // Small delta ensures camera is not always at lower zoom limit.
  88801. var radius = 0;
  88802. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  88803. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88804. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  88805. radius = position;
  88806. }
  88807. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88808. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88809. if (this._attachedCamera.lowerRadiusLimit === null) {
  88810. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  88811. }
  88812. }
  88813. // Set sensibilities
  88814. var extend = maximumWorld.subtract(minimumWorld).length();
  88815. this._attachedCamera.panningSensibility = 5000 / extend;
  88816. this._attachedCamera.wheelPrecision = 100 / radius;
  88817. // transition to new radius
  88818. if (!this._radiusTransition) {
  88819. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88820. }
  88821. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  88822. _this.stopAllAnimations();
  88823. if (onAnimationEnd) {
  88824. onAnimationEnd();
  88825. }
  88826. if (_this._attachedCamera) {
  88827. _this._attachedCamera.storeState();
  88828. }
  88829. });
  88830. if (animatable) {
  88831. this._animatables.push(animatable);
  88832. }
  88833. };
  88834. /**
  88835. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  88836. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  88837. * frustum width.
  88838. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  88839. * to fully enclose the mesh in the viewing frustum.
  88840. */
  88841. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  88842. var size = maximumWorld.subtract(minimumWorld);
  88843. var boxVectorGlobalDiagonal = size.length();
  88844. var frustumSlope = this._getFrustumSlope();
  88845. // Formula for setting distance
  88846. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  88847. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  88848. // Horizon distance
  88849. var radius = radiusWithoutFraming * this._radiusScale;
  88850. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  88851. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  88852. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  88853. var camera = this._attachedCamera;
  88854. if (!camera) {
  88855. return 0;
  88856. }
  88857. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88858. // Don't exceed the requested limit
  88859. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  88860. }
  88861. // Don't exceed the upper radius limit
  88862. if (camera.upperRadiusLimit) {
  88863. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  88864. }
  88865. return distance;
  88866. };
  88867. /**
  88868. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  88869. * is automatically returned to its default position (expected to be above ground plane).
  88870. */
  88871. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  88872. var _this = this;
  88873. if (this._elevationReturnTime < 0) {
  88874. return;
  88875. }
  88876. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  88877. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  88878. var limitBeta = Math.PI * 0.5;
  88879. // Bring the camera back up if below the ground plane
  88880. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  88881. this._betaIsAnimating = true;
  88882. //Transition to new position
  88883. this.stopAllAnimations();
  88884. if (!this._betaTransition) {
  88885. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88886. }
  88887. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  88888. _this._clearAnimationLocks();
  88889. _this.stopAllAnimations();
  88890. });
  88891. if (animatabe) {
  88892. this._animatables.push(animatabe);
  88893. }
  88894. }
  88895. };
  88896. /**
  88897. * Returns the frustum slope based on the canvas ratio and camera FOV
  88898. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  88899. */
  88900. FramingBehavior.prototype._getFrustumSlope = function () {
  88901. // Calculate the viewport ratio
  88902. // Aspect Ratio is Height/Width.
  88903. var camera = this._attachedCamera;
  88904. if (!camera) {
  88905. return BABYLON.Vector2.Zero();
  88906. }
  88907. var engine = camera.getScene().getEngine();
  88908. var aspectRatio = engine.getAspectRatio(camera);
  88909. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88910. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88911. var frustumSlopeY = Math.tan(camera.fov / 2);
  88912. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88913. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88914. // along the forward vector.
  88915. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88916. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88917. };
  88918. /**
  88919. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88920. */
  88921. FramingBehavior.prototype._clearAnimationLocks = function () {
  88922. this._betaIsAnimating = false;
  88923. };
  88924. /**
  88925. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88926. */
  88927. FramingBehavior.prototype._applyUserInteraction = function () {
  88928. if (this.isUserIsMoving) {
  88929. this._lastInteractionTime = BABYLON.Tools.Now;
  88930. this.stopAllAnimations();
  88931. this._clearAnimationLocks();
  88932. }
  88933. };
  88934. /**
  88935. * Stops and removes all animations that have been applied to the camera
  88936. */
  88937. FramingBehavior.prototype.stopAllAnimations = function () {
  88938. if (this._attachedCamera) {
  88939. this._attachedCamera.animations = [];
  88940. }
  88941. while (this._animatables.length) {
  88942. if (this._animatables[0]) {
  88943. this._animatables[0].onAnimationEnd = null;
  88944. this._animatables[0].stop();
  88945. }
  88946. this._animatables.shift();
  88947. }
  88948. };
  88949. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88950. /**
  88951. * Gets a value indicating if the user is moving the camera
  88952. */
  88953. get: function () {
  88954. if (!this._attachedCamera) {
  88955. return false;
  88956. }
  88957. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88958. this._attachedCamera.inertialBetaOffset !== 0 ||
  88959. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88960. this._attachedCamera.inertialPanningX !== 0 ||
  88961. this._attachedCamera.inertialPanningY !== 0 ||
  88962. this._isPointerDown;
  88963. },
  88964. enumerable: true,
  88965. configurable: true
  88966. });
  88967. /**
  88968. * The easing function used by animations
  88969. */
  88970. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88971. /**
  88972. * The easing mode used by animations
  88973. */
  88974. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88975. // Statics
  88976. /**
  88977. * The camera can move all the way towards the mesh.
  88978. */
  88979. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88980. /**
  88981. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88982. */
  88983. FramingBehavior.FitFrustumSidesMode = 1;
  88984. return FramingBehavior;
  88985. }());
  88986. BABYLON.FramingBehavior = FramingBehavior;
  88987. })(BABYLON || (BABYLON = {}));
  88988. //# sourceMappingURL=babylon.framingBehavior.js.map
  88989. var BABYLON;
  88990. (function (BABYLON) {
  88991. /**
  88992. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88993. */
  88994. var BouncingBehavior = /** @class */ (function () {
  88995. function BouncingBehavior() {
  88996. /**
  88997. * The duration of the animation, in milliseconds
  88998. */
  88999. this.transitionDuration = 450;
  89000. /**
  89001. * Length of the distance animated by the transition when lower radius is reached
  89002. */
  89003. this.lowerRadiusTransitionRange = 2;
  89004. /**
  89005. * Length of the distance animated by the transition when upper radius is reached
  89006. */
  89007. this.upperRadiusTransitionRange = -2;
  89008. this._autoTransitionRange = false;
  89009. // Animations
  89010. this._radiusIsAnimating = false;
  89011. this._radiusBounceTransition = null;
  89012. this._animatables = new Array();
  89013. }
  89014. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89015. get: function () {
  89016. return "Bouncing";
  89017. },
  89018. enumerable: true,
  89019. configurable: true
  89020. });
  89021. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89022. /**
  89023. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89024. */
  89025. get: function () {
  89026. return this._autoTransitionRange;
  89027. },
  89028. /**
  89029. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89030. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89031. */
  89032. set: function (value) {
  89033. var _this = this;
  89034. if (this._autoTransitionRange === value) {
  89035. return;
  89036. }
  89037. this._autoTransitionRange = value;
  89038. var camera = this._attachedCamera;
  89039. if (!camera) {
  89040. return;
  89041. }
  89042. if (value) {
  89043. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89044. if (!mesh) {
  89045. return;
  89046. }
  89047. mesh.computeWorldMatrix(true);
  89048. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89049. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89050. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89051. });
  89052. }
  89053. else if (this._onMeshTargetChangedObserver) {
  89054. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89055. }
  89056. },
  89057. enumerable: true,
  89058. configurable: true
  89059. });
  89060. BouncingBehavior.prototype.init = function () {
  89061. // Do notihng
  89062. };
  89063. BouncingBehavior.prototype.attach = function (camera) {
  89064. var _this = this;
  89065. this._attachedCamera = camera;
  89066. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89067. if (!_this._attachedCamera) {
  89068. return;
  89069. }
  89070. // Add the bounce animation to the lower radius limit
  89071. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89072. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89073. }
  89074. // Add the bounce animation to the upper radius limit
  89075. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89076. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89077. }
  89078. });
  89079. };
  89080. BouncingBehavior.prototype.detach = function () {
  89081. if (!this._attachedCamera) {
  89082. return;
  89083. }
  89084. if (this._onAfterCheckInputsObserver) {
  89085. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89086. }
  89087. if (this._onMeshTargetChangedObserver) {
  89088. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89089. }
  89090. this._attachedCamera = null;
  89091. };
  89092. /**
  89093. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89094. * @param radiusLimit The limit to check against.
  89095. * @return Bool to indicate if at limit.
  89096. */
  89097. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89098. if (!this._attachedCamera) {
  89099. return false;
  89100. }
  89101. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89102. return true;
  89103. }
  89104. return false;
  89105. };
  89106. /**
  89107. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89108. * @param radiusDelta The delta by which to animate to. Can be negative.
  89109. */
  89110. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89111. var _this = this;
  89112. if (!this._attachedCamera) {
  89113. return;
  89114. }
  89115. if (!this._radiusBounceTransition) {
  89116. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89117. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89118. }
  89119. // Prevent zoom until bounce has completed
  89120. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89121. this._attachedCamera.wheelPrecision = Infinity;
  89122. this._attachedCamera.inertialRadiusOffset = 0;
  89123. // Animate to the radius limit
  89124. this.stopAllAnimations();
  89125. this._radiusIsAnimating = true;
  89126. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89127. if (animatable) {
  89128. this._animatables.push(animatable);
  89129. }
  89130. };
  89131. /**
  89132. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89133. */
  89134. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89135. this._radiusIsAnimating = false;
  89136. if (this._attachedCamera) {
  89137. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89138. }
  89139. };
  89140. /**
  89141. * Stops and removes all animations that have been applied to the camera
  89142. */
  89143. BouncingBehavior.prototype.stopAllAnimations = function () {
  89144. if (this._attachedCamera) {
  89145. this._attachedCamera.animations = [];
  89146. }
  89147. while (this._animatables.length) {
  89148. this._animatables[0].onAnimationEnd = null;
  89149. this._animatables[0].stop();
  89150. this._animatables.shift();
  89151. }
  89152. };
  89153. /**
  89154. * The easing function used by animations
  89155. */
  89156. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89157. /**
  89158. * The easing mode used by animations
  89159. */
  89160. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89161. return BouncingBehavior;
  89162. }());
  89163. BABYLON.BouncingBehavior = BouncingBehavior;
  89164. })(BABYLON || (BABYLON = {}));
  89165. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89166. var BABYLON;
  89167. (function (BABYLON) {
  89168. var AutoRotationBehavior = /** @class */ (function () {
  89169. function AutoRotationBehavior() {
  89170. this._zoomStopsAnimation = false;
  89171. this._idleRotationSpeed = 0.05;
  89172. this._idleRotationWaitTime = 2000;
  89173. this._idleRotationSpinupTime = 2000;
  89174. this._isPointerDown = false;
  89175. this._lastFrameTime = null;
  89176. this._lastInteractionTime = -Infinity;
  89177. this._cameraRotationSpeed = 0;
  89178. this._lastFrameRadius = 0;
  89179. }
  89180. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89181. get: function () {
  89182. return "AutoRotation";
  89183. },
  89184. enumerable: true,
  89185. configurable: true
  89186. });
  89187. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89188. /**
  89189. * Gets the flag that indicates if user zooming should stop animation.
  89190. */
  89191. get: function () {
  89192. return this._zoomStopsAnimation;
  89193. },
  89194. /**
  89195. * Sets the flag that indicates if user zooming should stop animation.
  89196. */
  89197. set: function (flag) {
  89198. this._zoomStopsAnimation = flag;
  89199. },
  89200. enumerable: true,
  89201. configurable: true
  89202. });
  89203. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89204. /**
  89205. * Gets the default speed at which the camera rotates around the model.
  89206. */
  89207. get: function () {
  89208. return this._idleRotationSpeed;
  89209. },
  89210. /**
  89211. * Sets the default speed at which the camera rotates around the model.
  89212. */
  89213. set: function (speed) {
  89214. this._idleRotationSpeed = speed;
  89215. },
  89216. enumerable: true,
  89217. configurable: true
  89218. });
  89219. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89220. /**
  89221. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89222. */
  89223. get: function () {
  89224. return this._idleRotationWaitTime;
  89225. },
  89226. /**
  89227. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89228. */
  89229. set: function (time) {
  89230. this._idleRotationWaitTime = time;
  89231. },
  89232. enumerable: true,
  89233. configurable: true
  89234. });
  89235. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89236. /**
  89237. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89238. */
  89239. get: function () {
  89240. return this._idleRotationSpinupTime;
  89241. },
  89242. /**
  89243. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89244. */
  89245. set: function (time) {
  89246. this._idleRotationSpinupTime = time;
  89247. },
  89248. enumerable: true,
  89249. configurable: true
  89250. });
  89251. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89252. /**
  89253. * Gets a value indicating if the camera is currently rotating because of this behavior
  89254. */
  89255. get: function () {
  89256. return Math.abs(this._cameraRotationSpeed) > 0;
  89257. },
  89258. enumerable: true,
  89259. configurable: true
  89260. });
  89261. AutoRotationBehavior.prototype.init = function () {
  89262. // Do notihng
  89263. };
  89264. AutoRotationBehavior.prototype.attach = function (camera) {
  89265. var _this = this;
  89266. this._attachedCamera = camera;
  89267. var scene = this._attachedCamera.getScene();
  89268. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89269. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89270. _this._isPointerDown = true;
  89271. return;
  89272. }
  89273. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89274. _this._isPointerDown = false;
  89275. }
  89276. });
  89277. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89278. var now = BABYLON.Tools.Now;
  89279. var dt = 0;
  89280. if (_this._lastFrameTime != null) {
  89281. dt = now - _this._lastFrameTime;
  89282. }
  89283. _this._lastFrameTime = now;
  89284. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89285. _this._applyUserInteraction();
  89286. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89287. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89288. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89289. // Step camera rotation by rotation speed
  89290. if (_this._attachedCamera) {
  89291. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89292. }
  89293. });
  89294. };
  89295. AutoRotationBehavior.prototype.detach = function () {
  89296. if (!this._attachedCamera) {
  89297. return;
  89298. }
  89299. var scene = this._attachedCamera.getScene();
  89300. if (this._onPrePointerObservableObserver) {
  89301. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89302. }
  89303. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89304. this._attachedCamera = null;
  89305. };
  89306. /**
  89307. * Returns true if user is scrolling.
  89308. * @return true if user is scrolling.
  89309. */
  89310. AutoRotationBehavior.prototype._userIsZooming = function () {
  89311. if (!this._attachedCamera) {
  89312. return false;
  89313. }
  89314. return this._attachedCamera.inertialRadiusOffset !== 0;
  89315. };
  89316. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89317. if (!this._attachedCamera) {
  89318. return false;
  89319. }
  89320. var zoomHasHitLimit = false;
  89321. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89322. zoomHasHitLimit = true;
  89323. }
  89324. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89325. this._lastFrameRadius = this._attachedCamera.radius;
  89326. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89327. };
  89328. /**
  89329. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89330. */
  89331. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89332. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89333. this._lastInteractionTime = BABYLON.Tools.Now;
  89334. }
  89335. };
  89336. // Tools
  89337. AutoRotationBehavior.prototype._userIsMoving = function () {
  89338. if (!this._attachedCamera) {
  89339. return false;
  89340. }
  89341. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89342. this._attachedCamera.inertialBetaOffset !== 0 ||
  89343. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89344. this._attachedCamera.inertialPanningX !== 0 ||
  89345. this._attachedCamera.inertialPanningY !== 0 ||
  89346. this._isPointerDown;
  89347. };
  89348. return AutoRotationBehavior;
  89349. }());
  89350. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89351. })(BABYLON || (BABYLON = {}));
  89352. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89353. var BABYLON;
  89354. (function (BABYLON) {
  89355. var NullEngineOptions = /** @class */ (function () {
  89356. function NullEngineOptions() {
  89357. this.renderWidth = 512;
  89358. this.renderHeight = 256;
  89359. this.textureSize = 512;
  89360. this.deterministicLockstep = false;
  89361. this.lockstepMaxSteps = 4;
  89362. }
  89363. return NullEngineOptions;
  89364. }());
  89365. BABYLON.NullEngineOptions = NullEngineOptions;
  89366. /**
  89367. * The null engine class provides support for headless version of babylon.js.
  89368. * This can be used in server side scenario or for testing purposes
  89369. */
  89370. var NullEngine = /** @class */ (function (_super) {
  89371. __extends(NullEngine, _super);
  89372. function NullEngine(options) {
  89373. if (options === void 0) { options = new NullEngineOptions(); }
  89374. var _this = _super.call(this, null) || this;
  89375. if (options.deterministicLockstep === undefined) {
  89376. options.deterministicLockstep = false;
  89377. }
  89378. if (options.lockstepMaxSteps === undefined) {
  89379. options.lockstepMaxSteps = 4;
  89380. }
  89381. _this._options = options;
  89382. // Init caps
  89383. // We consider we are on a webgl1 capable device
  89384. _this._caps = new BABYLON.EngineCapabilities();
  89385. _this._caps.maxTexturesImageUnits = 16;
  89386. _this._caps.maxVertexTextureImageUnits = 16;
  89387. _this._caps.maxTextureSize = 512;
  89388. _this._caps.maxCubemapTextureSize = 512;
  89389. _this._caps.maxRenderTextureSize = 512;
  89390. _this._caps.maxVertexAttribs = 16;
  89391. _this._caps.maxVaryingVectors = 16;
  89392. _this._caps.maxFragmentUniformVectors = 16;
  89393. _this._caps.maxVertexUniformVectors = 16;
  89394. // Extensions
  89395. _this._caps.standardDerivatives = false;
  89396. _this._caps.astc = null;
  89397. _this._caps.s3tc = null;
  89398. _this._caps.pvrtc = null;
  89399. _this._caps.etc1 = null;
  89400. _this._caps.etc2 = null;
  89401. _this._caps.textureAnisotropicFilterExtension = null;
  89402. _this._caps.maxAnisotropy = 0;
  89403. _this._caps.uintIndices = false;
  89404. _this._caps.fragmentDepthSupported = false;
  89405. _this._caps.highPrecisionShaderSupported = true;
  89406. _this._caps.colorBufferFloat = false;
  89407. _this._caps.textureFloat = false;
  89408. _this._caps.textureFloatLinearFiltering = false;
  89409. _this._caps.textureFloatRender = false;
  89410. _this._caps.textureHalfFloat = false;
  89411. _this._caps.textureHalfFloatLinearFiltering = false;
  89412. _this._caps.textureHalfFloatRender = false;
  89413. _this._caps.textureLOD = false;
  89414. _this._caps.drawBuffersExtension = false;
  89415. _this._caps.depthTextureExtension = false;
  89416. _this._caps.vertexArrayObject = false;
  89417. _this._caps.instancedArrays = false;
  89418. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  89419. // Wrappers
  89420. if (typeof URL === "undefined") {
  89421. URL = {
  89422. createObjectURL: function () { },
  89423. revokeObjectURL: function () { }
  89424. };
  89425. }
  89426. if (typeof Blob === "undefined") {
  89427. Blob = function () { };
  89428. }
  89429. return _this;
  89430. }
  89431. NullEngine.prototype.isDeterministicLockStep = function () {
  89432. return this._options.deterministicLockstep;
  89433. };
  89434. NullEngine.prototype.getLockstepMaxSteps = function () {
  89435. return this._options.lockstepMaxSteps;
  89436. };
  89437. NullEngine.prototype.getHardwareScalingLevel = function () {
  89438. return 1.0;
  89439. };
  89440. NullEngine.prototype.createVertexBuffer = function (vertices) {
  89441. return {
  89442. capacity: 0,
  89443. references: 1,
  89444. is32Bits: false
  89445. };
  89446. };
  89447. NullEngine.prototype.createIndexBuffer = function (indices) {
  89448. return {
  89449. capacity: 0,
  89450. references: 1,
  89451. is32Bits: false
  89452. };
  89453. };
  89454. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  89455. if (stencil === void 0) { stencil = false; }
  89456. };
  89457. NullEngine.prototype.getRenderWidth = function (useScreen) {
  89458. if (useScreen === void 0) { useScreen = false; }
  89459. if (!useScreen && this._currentRenderTarget) {
  89460. return this._currentRenderTarget.width;
  89461. }
  89462. return this._options.renderWidth;
  89463. };
  89464. NullEngine.prototype.getRenderHeight = function (useScreen) {
  89465. if (useScreen === void 0) { useScreen = false; }
  89466. if (!useScreen && this._currentRenderTarget) {
  89467. return this._currentRenderTarget.height;
  89468. }
  89469. return this._options.renderHeight;
  89470. };
  89471. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  89472. this._cachedViewport = viewport;
  89473. };
  89474. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  89475. return {
  89476. transformFeedback: null,
  89477. __SPECTOR_rebuildProgram: null
  89478. };
  89479. };
  89480. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  89481. return [];
  89482. };
  89483. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  89484. return [];
  89485. };
  89486. NullEngine.prototype.bindSamplers = function (effect) {
  89487. this._currentEffect = null;
  89488. };
  89489. NullEngine.prototype.enableEffect = function (effect) {
  89490. this._currentEffect = effect;
  89491. if (effect.onBind) {
  89492. effect.onBind(effect);
  89493. }
  89494. effect.onBindObservable.notifyObservers(effect);
  89495. };
  89496. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  89497. if (zOffset === void 0) { zOffset = 0; }
  89498. if (reverseSide === void 0) { reverseSide = false; }
  89499. };
  89500. NullEngine.prototype.setIntArray = function (uniform, array) {
  89501. };
  89502. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  89503. };
  89504. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  89505. };
  89506. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  89507. };
  89508. NullEngine.prototype.setFloatArray = function (uniform, array) {
  89509. };
  89510. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  89511. };
  89512. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  89513. };
  89514. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  89515. };
  89516. NullEngine.prototype.setArray = function (uniform, array) {
  89517. };
  89518. NullEngine.prototype.setArray2 = function (uniform, array) {
  89519. };
  89520. NullEngine.prototype.setArray3 = function (uniform, array) {
  89521. };
  89522. NullEngine.prototype.setArray4 = function (uniform, array) {
  89523. };
  89524. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  89525. };
  89526. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  89527. };
  89528. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  89529. };
  89530. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  89531. };
  89532. NullEngine.prototype.setFloat = function (uniform, value) {
  89533. };
  89534. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  89535. };
  89536. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  89537. };
  89538. NullEngine.prototype.setBool = function (uniform, bool) {
  89539. };
  89540. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  89541. };
  89542. NullEngine.prototype.setColor3 = function (uniform, color3) {
  89543. };
  89544. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  89545. };
  89546. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  89547. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  89548. if (this._alphaMode === mode) {
  89549. return;
  89550. }
  89551. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  89552. if (!noDepthWriteChange) {
  89553. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  89554. }
  89555. this._alphaMode = mode;
  89556. };
  89557. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  89558. };
  89559. NullEngine.prototype.wipeCaches = function (bruteForce) {
  89560. if (this.preventCacheWipeBetweenFrames) {
  89561. return;
  89562. }
  89563. this.resetTextureCache();
  89564. this._currentEffect = null;
  89565. if (bruteForce) {
  89566. this._currentProgram = null;
  89567. this._stencilState.reset();
  89568. this._depthCullingState.reset();
  89569. this._alphaState.reset();
  89570. }
  89571. this._cachedVertexBuffers = null;
  89572. this._cachedIndexBuffer = null;
  89573. this._cachedEffectForVertexBuffers = null;
  89574. };
  89575. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  89576. };
  89577. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  89578. };
  89579. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  89580. };
  89581. NullEngine.prototype._createTexture = function () {
  89582. return {};
  89583. };
  89584. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  89585. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  89586. if (onLoad === void 0) { onLoad = null; }
  89587. if (onError === void 0) { onError = null; }
  89588. if (buffer === void 0) { buffer = null; }
  89589. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  89590. var url = String(urlArg);
  89591. texture.url = url;
  89592. texture.generateMipMaps = !noMipmap;
  89593. texture.samplingMode = samplingMode;
  89594. texture.invertY = invertY;
  89595. texture.baseWidth = this._options.textureSize;
  89596. texture.baseHeight = this._options.textureSize;
  89597. texture.width = this._options.textureSize;
  89598. texture.height = this._options.textureSize;
  89599. if (format) {
  89600. texture.format = format;
  89601. }
  89602. texture.isReady = true;
  89603. if (onLoad) {
  89604. onLoad();
  89605. }
  89606. return texture;
  89607. };
  89608. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  89609. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  89610. if (options !== undefined && typeof options === "object") {
  89611. fullOptions.generateMipMaps = options.generateMipMaps;
  89612. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  89613. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  89614. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  89615. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  89616. }
  89617. else {
  89618. fullOptions.generateMipMaps = options;
  89619. fullOptions.generateDepthBuffer = true;
  89620. fullOptions.generateStencilBuffer = false;
  89621. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89622. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  89623. }
  89624. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  89625. var width = size.width || size;
  89626. var height = size.height || size;
  89627. texture._depthStencilBuffer = {};
  89628. texture._framebuffer = {};
  89629. texture.baseWidth = width;
  89630. texture.baseHeight = height;
  89631. texture.width = width;
  89632. texture.height = height;
  89633. texture.isReady = true;
  89634. texture.samples = 1;
  89635. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89636. texture.samplingMode = fullOptions.samplingMode;
  89637. texture.type = fullOptions.type;
  89638. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  89639. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  89640. return texture;
  89641. };
  89642. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  89643. texture.samplingMode = samplingMode;
  89644. };
  89645. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  89646. if (this._currentRenderTarget) {
  89647. this.unBindFramebuffer(this._currentRenderTarget);
  89648. }
  89649. this._currentRenderTarget = texture;
  89650. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  89651. if (this._cachedViewport && !forceFullscreenViewport) {
  89652. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  89653. }
  89654. };
  89655. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  89656. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  89657. this._currentRenderTarget = null;
  89658. if (onBeforeUnbind) {
  89659. if (texture._MSAAFramebuffer) {
  89660. this._currentFramebuffer = texture._framebuffer;
  89661. }
  89662. onBeforeUnbind();
  89663. }
  89664. this._currentFramebuffer = null;
  89665. };
  89666. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  89667. var vbo = {
  89668. capacity: 1,
  89669. references: 1,
  89670. is32Bits: false
  89671. };
  89672. return vbo;
  89673. };
  89674. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  89675. if (offset === void 0) { offset = 0; }
  89676. };
  89677. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  89678. };
  89679. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  89680. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  89681. this._boundTexturesCache[this._activeChannel] = texture;
  89682. }
  89683. };
  89684. NullEngine.prototype._bindTexture = function (channel, texture) {
  89685. if (channel < 0) {
  89686. return;
  89687. }
  89688. this._bindTextureDirectly(0, texture);
  89689. };
  89690. NullEngine.prototype._releaseBuffer = function (buffer) {
  89691. buffer.references--;
  89692. if (buffer.references === 0) {
  89693. return true;
  89694. }
  89695. return false;
  89696. };
  89697. return NullEngine;
  89698. }(BABYLON.Engine));
  89699. BABYLON.NullEngine = NullEngine;
  89700. })(BABYLON || (BABYLON = {}));
  89701. //# sourceMappingURL=babylon.nullEngine.js.map
  89702. var BABYLON;
  89703. (function (BABYLON) {
  89704. /**
  89705. * This class can be used to get instrumentation data from a Babylon engine
  89706. */
  89707. var EngineInstrumentation = /** @class */ (function () {
  89708. function EngineInstrumentation(engine) {
  89709. this.engine = engine;
  89710. this._captureGPUFrameTime = false;
  89711. this._gpuFrameTime = new BABYLON.PerfCounter();
  89712. this._captureShaderCompilationTime = false;
  89713. this._shaderCompilationTime = new BABYLON.PerfCounter();
  89714. // Observers
  89715. this._onBeginFrameObserver = null;
  89716. this._onEndFrameObserver = null;
  89717. this._onBeforeShaderCompilationObserver = null;
  89718. this._onAfterShaderCompilationObserver = null;
  89719. }
  89720. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  89721. // Properties
  89722. /**
  89723. * Gets the perf counter used for GPU frame time
  89724. */
  89725. get: function () {
  89726. return this._gpuFrameTime;
  89727. },
  89728. enumerable: true,
  89729. configurable: true
  89730. });
  89731. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  89732. /**
  89733. * Gets the GPU frame time capture status
  89734. */
  89735. get: function () {
  89736. return this._captureGPUFrameTime;
  89737. },
  89738. /**
  89739. * Enable or disable the GPU frame time capture
  89740. */
  89741. set: function (value) {
  89742. var _this = this;
  89743. if (value === this._captureGPUFrameTime) {
  89744. return;
  89745. }
  89746. this._captureGPUFrameTime = value;
  89747. if (value) {
  89748. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  89749. if (!_this._gpuFrameTimeToken) {
  89750. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  89751. }
  89752. });
  89753. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  89754. if (!_this._gpuFrameTimeToken) {
  89755. return;
  89756. }
  89757. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  89758. if (time > -1) {
  89759. _this._gpuFrameTimeToken = null;
  89760. _this._gpuFrameTime.fetchNewFrame();
  89761. _this._gpuFrameTime.addCount(time, true);
  89762. }
  89763. });
  89764. }
  89765. else {
  89766. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89767. this._onBeginFrameObserver = null;
  89768. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89769. this._onEndFrameObserver = null;
  89770. }
  89771. },
  89772. enumerable: true,
  89773. configurable: true
  89774. });
  89775. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  89776. /**
  89777. * Gets the perf counter used for shader compilation time
  89778. */
  89779. get: function () {
  89780. return this._shaderCompilationTime;
  89781. },
  89782. enumerable: true,
  89783. configurable: true
  89784. });
  89785. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  89786. /**
  89787. * Gets the shader compilation time capture status
  89788. */
  89789. get: function () {
  89790. return this._captureShaderCompilationTime;
  89791. },
  89792. /**
  89793. * Enable or disable the shader compilation time capture
  89794. */
  89795. set: function (value) {
  89796. var _this = this;
  89797. if (value === this._captureShaderCompilationTime) {
  89798. return;
  89799. }
  89800. this._captureShaderCompilationTime = value;
  89801. if (value) {
  89802. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  89803. _this._shaderCompilationTime.fetchNewFrame();
  89804. _this._shaderCompilationTime.beginMonitoring();
  89805. });
  89806. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  89807. _this._shaderCompilationTime.endMonitoring();
  89808. });
  89809. }
  89810. else {
  89811. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89812. this._onBeforeShaderCompilationObserver = null;
  89813. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89814. this._onAfterShaderCompilationObserver = null;
  89815. }
  89816. },
  89817. enumerable: true,
  89818. configurable: true
  89819. });
  89820. EngineInstrumentation.prototype.dispose = function () {
  89821. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89822. this._onBeginFrameObserver = null;
  89823. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89824. this._onEndFrameObserver = null;
  89825. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89826. this._onBeforeShaderCompilationObserver = null;
  89827. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89828. this._onAfterShaderCompilationObserver = null;
  89829. this.engine = null;
  89830. };
  89831. return EngineInstrumentation;
  89832. }());
  89833. BABYLON.EngineInstrumentation = EngineInstrumentation;
  89834. })(BABYLON || (BABYLON = {}));
  89835. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  89836. var BABYLON;
  89837. (function (BABYLON) {
  89838. /**
  89839. * This class can be used to get instrumentation data from a Babylon engine
  89840. */
  89841. var SceneInstrumentation = /** @class */ (function () {
  89842. function SceneInstrumentation(scene) {
  89843. var _this = this;
  89844. this.scene = scene;
  89845. this._captureActiveMeshesEvaluationTime = false;
  89846. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  89847. this._captureRenderTargetsRenderTime = false;
  89848. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  89849. this._captureFrameTime = false;
  89850. this._frameTime = new BABYLON.PerfCounter();
  89851. this._captureRenderTime = false;
  89852. this._renderTime = new BABYLON.PerfCounter();
  89853. this._captureInterFrameTime = false;
  89854. this._interFrameTime = new BABYLON.PerfCounter();
  89855. this._captureParticlesRenderTime = false;
  89856. this._particlesRenderTime = new BABYLON.PerfCounter();
  89857. this._captureSpritesRenderTime = false;
  89858. this._spritesRenderTime = new BABYLON.PerfCounter();
  89859. this._capturePhysicsTime = false;
  89860. this._physicsTime = new BABYLON.PerfCounter();
  89861. this._captureAnimationsTime = false;
  89862. this._animationsTime = new BABYLON.PerfCounter();
  89863. // Observers
  89864. this._onBeforeActiveMeshesEvaluationObserver = null;
  89865. this._onAfterActiveMeshesEvaluationObserver = null;
  89866. this._onBeforeRenderTargetsRenderObserver = null;
  89867. this._onAfterRenderTargetsRenderObserver = null;
  89868. this._onAfterRenderObserver = null;
  89869. this._onBeforeDrawPhaseObserver = null;
  89870. this._onAfterDrawPhaseObserver = null;
  89871. this._onBeforeAnimationsObserver = null;
  89872. this._onBeforeParticlesRenderingObserver = null;
  89873. this._onAfterParticlesRenderingObserver = null;
  89874. this._onBeforeSpritesRenderingObserver = null;
  89875. this._onAfterSpritesRenderingObserver = null;
  89876. this._onBeforePhysicsObserver = null;
  89877. this._onAfterPhysicsObserver = null;
  89878. this._onAfterAnimationsObserver = null;
  89879. // Before render
  89880. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  89881. if (_this._captureActiveMeshesEvaluationTime) {
  89882. _this._activeMeshesEvaluationTime.fetchNewFrame();
  89883. }
  89884. if (_this._captureRenderTargetsRenderTime) {
  89885. _this._renderTargetsRenderTime.fetchNewFrame();
  89886. }
  89887. if (_this._captureFrameTime) {
  89888. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  89889. _this._frameTime.beginMonitoring();
  89890. }
  89891. if (_this._captureInterFrameTime) {
  89892. _this._interFrameTime.endMonitoring();
  89893. }
  89894. if (_this._captureParticlesRenderTime) {
  89895. _this._particlesRenderTime.fetchNewFrame();
  89896. }
  89897. if (_this._captureSpritesRenderTime) {
  89898. _this._spritesRenderTime.fetchNewFrame();
  89899. }
  89900. if (_this._captureAnimationsTime) {
  89901. _this._animationsTime.beginMonitoring();
  89902. }
  89903. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89904. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89905. });
  89906. // After render
  89907. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89908. if (_this._captureFrameTime) {
  89909. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89910. _this._frameTime.endMonitoring();
  89911. }
  89912. if (_this._captureRenderTime) {
  89913. _this._renderTime.endMonitoring(false);
  89914. }
  89915. if (_this._captureInterFrameTime) {
  89916. _this._interFrameTime.beginMonitoring();
  89917. }
  89918. });
  89919. }
  89920. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89921. // Properties
  89922. /**
  89923. * Gets the perf counter used for active meshes evaluation time
  89924. */
  89925. get: function () {
  89926. return this._activeMeshesEvaluationTime;
  89927. },
  89928. enumerable: true,
  89929. configurable: true
  89930. });
  89931. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89932. /**
  89933. * Gets the active meshes evaluation time capture status
  89934. */
  89935. get: function () {
  89936. return this._captureActiveMeshesEvaluationTime;
  89937. },
  89938. /**
  89939. * Enable or disable the active meshes evaluation time capture
  89940. */
  89941. set: function (value) {
  89942. var _this = this;
  89943. if (value === this._captureActiveMeshesEvaluationTime) {
  89944. return;
  89945. }
  89946. this._captureActiveMeshesEvaluationTime = value;
  89947. if (value) {
  89948. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89949. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89950. _this._activeMeshesEvaluationTime.beginMonitoring();
  89951. });
  89952. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89953. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89954. _this._activeMeshesEvaluationTime.endMonitoring();
  89955. });
  89956. }
  89957. else {
  89958. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89959. this._onBeforeActiveMeshesEvaluationObserver = null;
  89960. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89961. this._onAfterActiveMeshesEvaluationObserver = null;
  89962. }
  89963. },
  89964. enumerable: true,
  89965. configurable: true
  89966. });
  89967. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89968. /**
  89969. * Gets the perf counter used for render targets render time
  89970. */
  89971. get: function () {
  89972. return this._renderTargetsRenderTime;
  89973. },
  89974. enumerable: true,
  89975. configurable: true
  89976. });
  89977. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89978. /**
  89979. * Gets the render targets render time capture status
  89980. */
  89981. get: function () {
  89982. return this._captureRenderTargetsRenderTime;
  89983. },
  89984. /**
  89985. * Enable or disable the render targets render time capture
  89986. */
  89987. set: function (value) {
  89988. var _this = this;
  89989. if (value === this._captureRenderTargetsRenderTime) {
  89990. return;
  89991. }
  89992. this._captureRenderTargetsRenderTime = value;
  89993. if (value) {
  89994. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89995. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89996. _this._renderTargetsRenderTime.beginMonitoring();
  89997. });
  89998. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89999. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90000. _this._renderTargetsRenderTime.endMonitoring(false);
  90001. });
  90002. }
  90003. else {
  90004. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90005. this._onBeforeRenderTargetsRenderObserver = null;
  90006. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90007. this._onAfterRenderTargetsRenderObserver = null;
  90008. }
  90009. },
  90010. enumerable: true,
  90011. configurable: true
  90012. });
  90013. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90014. /**
  90015. * Gets the perf counter used for particles render time
  90016. */
  90017. get: function () {
  90018. return this._particlesRenderTime;
  90019. },
  90020. enumerable: true,
  90021. configurable: true
  90022. });
  90023. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90024. /**
  90025. * Gets the particles render time capture status
  90026. */
  90027. get: function () {
  90028. return this._captureParticlesRenderTime;
  90029. },
  90030. /**
  90031. * Enable or disable the particles render time capture
  90032. */
  90033. set: function (value) {
  90034. var _this = this;
  90035. if (value === this._captureParticlesRenderTime) {
  90036. return;
  90037. }
  90038. this._captureParticlesRenderTime = value;
  90039. if (value) {
  90040. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90041. BABYLON.Tools.StartPerformanceCounter("Particles");
  90042. _this._particlesRenderTime.beginMonitoring();
  90043. });
  90044. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90045. BABYLON.Tools.EndPerformanceCounter("Particles");
  90046. _this._particlesRenderTime.endMonitoring(false);
  90047. });
  90048. }
  90049. else {
  90050. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90051. this._onBeforeParticlesRenderingObserver = null;
  90052. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90053. this._onAfterParticlesRenderingObserver = null;
  90054. }
  90055. },
  90056. enumerable: true,
  90057. configurable: true
  90058. });
  90059. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90060. /**
  90061. * Gets the perf counter used for sprites render time
  90062. */
  90063. get: function () {
  90064. return this._spritesRenderTime;
  90065. },
  90066. enumerable: true,
  90067. configurable: true
  90068. });
  90069. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90070. /**
  90071. * Gets the sprites render time capture status
  90072. */
  90073. get: function () {
  90074. return this._captureSpritesRenderTime;
  90075. },
  90076. /**
  90077. * Enable or disable the sprites render time capture
  90078. */
  90079. set: function (value) {
  90080. var _this = this;
  90081. if (value === this._captureSpritesRenderTime) {
  90082. return;
  90083. }
  90084. this._captureSpritesRenderTime = value;
  90085. if (value) {
  90086. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90087. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90088. _this._spritesRenderTime.beginMonitoring();
  90089. });
  90090. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90091. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90092. _this._spritesRenderTime.endMonitoring(false);
  90093. });
  90094. }
  90095. else {
  90096. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90097. this._onBeforeSpritesRenderingObserver = null;
  90098. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90099. this._onAfterSpritesRenderingObserver = null;
  90100. }
  90101. },
  90102. enumerable: true,
  90103. configurable: true
  90104. });
  90105. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90106. /**
  90107. * Gets the perf counter used for physics time
  90108. */
  90109. get: function () {
  90110. return this._physicsTime;
  90111. },
  90112. enumerable: true,
  90113. configurable: true
  90114. });
  90115. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90116. /**
  90117. * Gets the physics time capture status
  90118. */
  90119. get: function () {
  90120. return this._capturePhysicsTime;
  90121. },
  90122. /**
  90123. * Enable or disable the physics time capture
  90124. */
  90125. set: function (value) {
  90126. var _this = this;
  90127. if (value === this._capturePhysicsTime) {
  90128. return;
  90129. }
  90130. this._capturePhysicsTime = value;
  90131. if (value) {
  90132. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90133. BABYLON.Tools.StartPerformanceCounter("Physics");
  90134. _this._physicsTime.beginMonitoring();
  90135. });
  90136. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90137. BABYLON.Tools.EndPerformanceCounter("Physics");
  90138. _this._physicsTime.endMonitoring();
  90139. });
  90140. }
  90141. else {
  90142. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90143. this._onBeforePhysicsObserver = null;
  90144. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90145. this._onAfterPhysicsObserver = null;
  90146. }
  90147. },
  90148. enumerable: true,
  90149. configurable: true
  90150. });
  90151. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90152. /**
  90153. * Gets the perf counter used for animations time
  90154. */
  90155. get: function () {
  90156. return this._animationsTime;
  90157. },
  90158. enumerable: true,
  90159. configurable: true
  90160. });
  90161. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90162. /**
  90163. * Gets the animations time capture status
  90164. */
  90165. get: function () {
  90166. return this._captureAnimationsTime;
  90167. },
  90168. /**
  90169. * Enable or disable the animations time capture
  90170. */
  90171. set: function (value) {
  90172. var _this = this;
  90173. if (value === this._captureAnimationsTime) {
  90174. return;
  90175. }
  90176. this._captureAnimationsTime = value;
  90177. if (value) {
  90178. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90179. _this._animationsTime.endMonitoring();
  90180. });
  90181. }
  90182. else {
  90183. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90184. this._onAfterAnimationsObserver = null;
  90185. }
  90186. },
  90187. enumerable: true,
  90188. configurable: true
  90189. });
  90190. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90191. /**
  90192. * Gets the perf counter used for frame time capture
  90193. */
  90194. get: function () {
  90195. return this._frameTime;
  90196. },
  90197. enumerable: true,
  90198. configurable: true
  90199. });
  90200. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90201. /**
  90202. * Gets the frame time capture status
  90203. */
  90204. get: function () {
  90205. return this._captureFrameTime;
  90206. },
  90207. /**
  90208. * Enable or disable the frame time capture
  90209. */
  90210. set: function (value) {
  90211. this._captureFrameTime = value;
  90212. },
  90213. enumerable: true,
  90214. configurable: true
  90215. });
  90216. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90217. /**
  90218. * Gets the perf counter used for inter-frames time capture
  90219. */
  90220. get: function () {
  90221. return this._interFrameTime;
  90222. },
  90223. enumerable: true,
  90224. configurable: true
  90225. });
  90226. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90227. /**
  90228. * Gets the inter-frames time capture status
  90229. */
  90230. get: function () {
  90231. return this._captureInterFrameTime;
  90232. },
  90233. /**
  90234. * Enable or disable the inter-frames time capture
  90235. */
  90236. set: function (value) {
  90237. this._captureInterFrameTime = value;
  90238. },
  90239. enumerable: true,
  90240. configurable: true
  90241. });
  90242. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90243. /**
  90244. * Gets the perf counter used for render time capture
  90245. */
  90246. get: function () {
  90247. return this._renderTime;
  90248. },
  90249. enumerable: true,
  90250. configurable: true
  90251. });
  90252. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90253. /**
  90254. * Gets the render time capture status
  90255. */
  90256. get: function () {
  90257. return this._captureRenderTime;
  90258. },
  90259. /**
  90260. * Enable or disable the render time capture
  90261. */
  90262. set: function (value) {
  90263. var _this = this;
  90264. if (value === this._captureRenderTime) {
  90265. return;
  90266. }
  90267. this._captureRenderTime = value;
  90268. if (value) {
  90269. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90270. _this._renderTime.beginMonitoring();
  90271. BABYLON.Tools.StartPerformanceCounter("Main render");
  90272. });
  90273. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90274. _this._renderTime.endMonitoring(false);
  90275. BABYLON.Tools.EndPerformanceCounter("Main render");
  90276. });
  90277. }
  90278. else {
  90279. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90280. this._onBeforeDrawPhaseObserver = null;
  90281. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90282. this._onAfterDrawPhaseObserver = null;
  90283. }
  90284. },
  90285. enumerable: true,
  90286. configurable: true
  90287. });
  90288. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90289. /**
  90290. * Gets the perf counter used for draw calls
  90291. */
  90292. get: function () {
  90293. return this.scene.getEngine()._drawCalls;
  90294. },
  90295. enumerable: true,
  90296. configurable: true
  90297. });
  90298. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90299. /**
  90300. * Gets the perf counter used for texture collisions
  90301. */
  90302. get: function () {
  90303. return this.scene.getEngine()._textureCollisions;
  90304. },
  90305. enumerable: true,
  90306. configurable: true
  90307. });
  90308. SceneInstrumentation.prototype.dispose = function () {
  90309. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90310. this._onAfterRenderObserver = null;
  90311. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90312. this._onBeforeActiveMeshesEvaluationObserver = null;
  90313. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90314. this._onAfterActiveMeshesEvaluationObserver = null;
  90315. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90316. this._onBeforeRenderTargetsRenderObserver = null;
  90317. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90318. this._onAfterRenderTargetsRenderObserver = null;
  90319. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90320. this._onBeforeAnimationsObserver = null;
  90321. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90322. this._onBeforeParticlesRenderingObserver = null;
  90323. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90324. this._onAfterParticlesRenderingObserver = null;
  90325. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90326. this._onBeforeSpritesRenderingObserver = null;
  90327. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90328. this._onAfterSpritesRenderingObserver = null;
  90329. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90330. this._onBeforeDrawPhaseObserver = null;
  90331. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90332. this._onAfterDrawPhaseObserver = null;
  90333. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90334. this._onBeforePhysicsObserver = null;
  90335. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90336. this._onAfterPhysicsObserver = null;
  90337. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90338. this._onAfterAnimationsObserver = null;
  90339. this.scene = null;
  90340. };
  90341. return SceneInstrumentation;
  90342. }());
  90343. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90344. })(BABYLON || (BABYLON = {}));
  90345. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90346. var BABYLON;
  90347. (function (BABYLON) {
  90348. var _TimeToken = /** @class */ (function () {
  90349. function _TimeToken() {
  90350. this._timeElapsedQueryEnded = false;
  90351. }
  90352. return _TimeToken;
  90353. }());
  90354. BABYLON._TimeToken = _TimeToken;
  90355. })(BABYLON || (BABYLON = {}));
  90356. //# sourceMappingURL=babylon.timeToken.js.map
  90357. var BABYLON;
  90358. (function (BABYLON) {
  90359. /**
  90360. * Background material defines definition.
  90361. * @ignore Mainly internal Use
  90362. */
  90363. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  90364. __extends(BackgroundMaterialDefines, _super);
  90365. /**
  90366. * Constructor of the defines.
  90367. */
  90368. function BackgroundMaterialDefines() {
  90369. var _this = _super.call(this) || this;
  90370. /**
  90371. * True if the diffuse texture is in use.
  90372. */
  90373. _this.DIFFUSE = false;
  90374. /**
  90375. * The direct UV channel to use.
  90376. */
  90377. _this.DIFFUSEDIRECTUV = 0;
  90378. /**
  90379. * True if the diffuse texture is in gamma space.
  90380. */
  90381. _this.GAMMADIFFUSE = false;
  90382. /**
  90383. * True if the diffuse texture has opacity in the alpha channel.
  90384. */
  90385. _this.DIFFUSEHASALPHA = false;
  90386. /**
  90387. * True if you want the material to fade to transparent at grazing angle.
  90388. */
  90389. _this.OPACITYFRESNEL = false;
  90390. /**
  90391. * True if an extra blur needs to be added in the reflection.
  90392. */
  90393. _this.REFLECTIONBLUR = false;
  90394. /**
  90395. * True if you want the material to fade to reflection at grazing angle.
  90396. */
  90397. _this.REFLECTIONFRESNEL = false;
  90398. /**
  90399. * True if you want the material to falloff as far as you move away from the scene center.
  90400. */
  90401. _this.REFLECTIONFALLOFF = false;
  90402. /**
  90403. * False if the current Webgl implementation does not support the texture lod extension.
  90404. */
  90405. _this.TEXTURELODSUPPORT = false;
  90406. /**
  90407. * True to ensure the data are premultiplied.
  90408. */
  90409. _this.PREMULTIPLYALPHA = false;
  90410. /**
  90411. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  90412. */
  90413. _this.USERGBCOLOR = false;
  90414. /**
  90415. * True to add noise in order to reduce the banding effect.
  90416. */
  90417. _this.NOISE = false;
  90418. /**
  90419. * is the reflection texture in BGR color scheme?
  90420. * Mainly used to solve a bug in ios10 video tag
  90421. */
  90422. _this.REFLECTIONBGR = false;
  90423. _this.IMAGEPROCESSING = false;
  90424. _this.VIGNETTE = false;
  90425. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  90426. _this.VIGNETTEBLENDMODEOPAQUE = false;
  90427. _this.TONEMAPPING = false;
  90428. _this.CONTRAST = false;
  90429. _this.COLORCURVES = false;
  90430. _this.COLORGRADING = false;
  90431. _this.COLORGRADING3D = false;
  90432. _this.SAMPLER3DGREENDEPTH = false;
  90433. _this.SAMPLER3DBGRMAP = false;
  90434. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  90435. _this.EXPOSURE = false;
  90436. _this.GRAIN = false;
  90437. // Reflection.
  90438. _this.REFLECTION = false;
  90439. _this.REFLECTIONMAP_3D = false;
  90440. _this.REFLECTIONMAP_SPHERICAL = false;
  90441. _this.REFLECTIONMAP_PLANAR = false;
  90442. _this.REFLECTIONMAP_CUBIC = false;
  90443. _this.REFLECTIONMAP_PROJECTION = false;
  90444. _this.REFLECTIONMAP_SKYBOX = false;
  90445. _this.REFLECTIONMAP_EXPLICIT = false;
  90446. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90447. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90448. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90449. _this.INVERTCUBICMAP = false;
  90450. _this.REFLECTIONMAP_OPPOSITEZ = false;
  90451. _this.LODINREFLECTIONALPHA = false;
  90452. _this.GAMMAREFLECTION = false;
  90453. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  90454. // Default BJS.
  90455. _this.MAINUV1 = false;
  90456. _this.MAINUV2 = false;
  90457. _this.UV1 = false;
  90458. _this.UV2 = false;
  90459. _this.CLIPPLANE = false;
  90460. _this.POINTSIZE = false;
  90461. _this.FOG = false;
  90462. _this.NORMAL = false;
  90463. _this.NUM_BONE_INFLUENCERS = 0;
  90464. _this.BonesPerMesh = 0;
  90465. _this.INSTANCES = false;
  90466. _this.SHADOWFLOAT = false;
  90467. _this.rebuild();
  90468. return _this;
  90469. }
  90470. return BackgroundMaterialDefines;
  90471. }(BABYLON.MaterialDefines));
  90472. /**
  90473. * Background material used to create an efficient environement around your scene.
  90474. */
  90475. var BackgroundMaterial = /** @class */ (function (_super) {
  90476. __extends(BackgroundMaterial, _super);
  90477. /**
  90478. * Instantiates a Background Material in the given scene
  90479. * @param name The friendly name of the material
  90480. * @param scene The scene to add the material to
  90481. */
  90482. function BackgroundMaterial(name, scene) {
  90483. var _this = _super.call(this, name, scene) || this;
  90484. /**
  90485. * Key light Color (multiply against the R channel of the environement texture)
  90486. */
  90487. _this.primaryColor = BABYLON.Color3.White();
  90488. /**
  90489. * Key light Level (allowing HDR output of the background)
  90490. */
  90491. _this.primaryLevel = 1;
  90492. /**
  90493. * Secondary light Color (multiply against the G channel of the environement texture)
  90494. */
  90495. _this.secondaryColor = BABYLON.Color3.Gray();
  90496. /**
  90497. * Secondary light Level (allowing HDR output of the background)
  90498. */
  90499. _this.secondaryLevel = 1;
  90500. /**
  90501. * Tertiary light Color (multiply against the B channel of the environement texture)
  90502. */
  90503. _this.tertiaryColor = BABYLON.Color3.Black();
  90504. /**
  90505. * Tertiary light Level (allowing HDR output of the background)
  90506. */
  90507. _this.tertiaryLevel = 1;
  90508. /**
  90509. * Reflection Texture used in the material.
  90510. * Should be author in a specific way for the best result (refer to the documentation).
  90511. */
  90512. _this.reflectionTexture = null;
  90513. /**
  90514. * Reflection Texture level of blur.
  90515. *
  90516. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  90517. * texture twice.
  90518. */
  90519. _this.reflectionBlur = 0;
  90520. /**
  90521. * Diffuse Texture used in the material.
  90522. * Should be author in a specific way for the best result (refer to the documentation).
  90523. */
  90524. _this.diffuseTexture = null;
  90525. _this._shadowLights = null;
  90526. /**
  90527. * Specify the list of lights casting shadow on the material.
  90528. * All scene shadow lights will be included if null.
  90529. */
  90530. _this.shadowLights = null;
  90531. /**
  90532. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  90533. * soft lighting on the background.
  90534. */
  90535. _this.shadowBlurScale = 1;
  90536. /**
  90537. * Helps adjusting the shadow to a softer level if required.
  90538. * 0 means black shadows and 1 means no shadows.
  90539. */
  90540. _this.shadowLevel = 0;
  90541. /**
  90542. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  90543. * It is usually zero but might be interesting to modify according to your setup.
  90544. */
  90545. _this.sceneCenter = BABYLON.Vector3.Zero();
  90546. /**
  90547. * This helps specifying that the material is falling off to the sky box at grazing angle.
  90548. * This helps ensuring a nice transition when the camera goes under the ground.
  90549. */
  90550. _this.opacityFresnel = true;
  90551. /**
  90552. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  90553. * This helps adding a mirror texture on the ground.
  90554. */
  90555. _this.reflectionFresnel = false;
  90556. /**
  90557. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  90558. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  90559. */
  90560. _this.reflectionFalloffDistance = 0.0;
  90561. /**
  90562. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  90563. */
  90564. _this.reflectionAmount = 1.0;
  90565. /**
  90566. * This specifies the weight of the reflection at grazing angle.
  90567. */
  90568. _this.reflectionReflectance0 = 0.05;
  90569. /**
  90570. * This specifies the weight of the reflection at a perpendicular point of view.
  90571. */
  90572. _this.reflectionReflectance90 = 0.5;
  90573. /**
  90574. * Helps to directly use the maps channels instead of their level.
  90575. */
  90576. _this.useRGBColor = true;
  90577. /**
  90578. * This helps reducing the banding effect that could occur on the background.
  90579. */
  90580. _this.enableNoise = false;
  90581. _this._fovMultiplier = 1.0;
  90582. /**
  90583. * Enable the FOV adjustment feature controlled by fovMultiplier.
  90584. * @type {boolean}
  90585. */
  90586. _this.useEquirectangularFOV = false;
  90587. _this._maxSimultaneousLights = 4;
  90588. /**
  90589. * Number of Simultaneous lights allowed on the material.
  90590. */
  90591. _this.maxSimultaneousLights = 4;
  90592. /**
  90593. * Keep track of the image processing observer to allow dispose and replace.
  90594. */
  90595. _this._imageProcessingObserver = null;
  90596. /**
  90597. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  90598. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  90599. */
  90600. _this.switchToBGR = false;
  90601. // Temp values kept as cache in the material.
  90602. _this._renderTargets = new BABYLON.SmartArray(16);
  90603. _this._reflectionControls = BABYLON.Vector4.Zero();
  90604. // Setup the default processing configuration to the scene.
  90605. _this._attachImageProcessingConfiguration(null);
  90606. _this.getRenderTargetTextures = function () {
  90607. _this._renderTargets.reset();
  90608. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  90609. _this._renderTargets.push(_this._diffuseTexture);
  90610. }
  90611. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  90612. _this._renderTargets.push(_this._reflectionTexture);
  90613. }
  90614. return _this._renderTargets;
  90615. };
  90616. return _this;
  90617. }
  90618. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  90619. /**
  90620. * Sets the reflection reflectance fresnel values according to the default standard
  90621. * empirically know to work well :-)
  90622. */
  90623. set: function (value) {
  90624. var reflectionWeight = value;
  90625. if (reflectionWeight < 0.5) {
  90626. reflectionWeight = reflectionWeight * 2.0;
  90627. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90628. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90629. }
  90630. else {
  90631. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90632. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90633. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  90634. }
  90635. },
  90636. enumerable: true,
  90637. configurable: true
  90638. });
  90639. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  90640. /**
  90641. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90642. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  90643. * Recommended to be keep at 1.0 except for special cases.
  90644. */
  90645. get: function () {
  90646. return this._fovMultiplier;
  90647. },
  90648. set: function (value) {
  90649. if (isNaN(value)) {
  90650. value = 1.0;
  90651. }
  90652. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  90653. },
  90654. enumerable: true,
  90655. configurable: true
  90656. });
  90657. /**
  90658. * Attaches a new image processing configuration to the PBR Material.
  90659. * @param configuration (if null the scene configuration will be use)
  90660. */
  90661. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  90662. var _this = this;
  90663. if (configuration === this._imageProcessingConfiguration) {
  90664. return;
  90665. }
  90666. // Detaches observer.
  90667. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90668. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90669. }
  90670. // Pick the scene configuration if needed.
  90671. if (!configuration) {
  90672. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  90673. }
  90674. else {
  90675. this._imageProcessingConfiguration = configuration;
  90676. }
  90677. // Attaches observer.
  90678. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90679. _this._markAllSubMeshesAsImageProcessingDirty();
  90680. });
  90681. };
  90682. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  90683. /**
  90684. * Gets the image processing configuration used either in this material.
  90685. */
  90686. get: function () {
  90687. return this._imageProcessingConfiguration;
  90688. },
  90689. /**
  90690. * Sets the Default image processing configuration used either in the this material.
  90691. *
  90692. * If sets to null, the scene one is in use.
  90693. */
  90694. set: function (value) {
  90695. this._attachImageProcessingConfiguration(value);
  90696. // Ensure the effect will be rebuilt.
  90697. this._markAllSubMeshesAsTexturesDirty();
  90698. },
  90699. enumerable: true,
  90700. configurable: true
  90701. });
  90702. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  90703. /**
  90704. * Gets wether the color curves effect is enabled.
  90705. */
  90706. get: function () {
  90707. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90708. },
  90709. /**
  90710. * Sets wether the color curves effect is enabled.
  90711. */
  90712. set: function (value) {
  90713. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90714. },
  90715. enumerable: true,
  90716. configurable: true
  90717. });
  90718. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  90719. /**
  90720. * Gets wether the color grading effect is enabled.
  90721. */
  90722. get: function () {
  90723. return this.imageProcessingConfiguration.colorGradingEnabled;
  90724. },
  90725. /**
  90726. * Gets wether the color grading effect is enabled.
  90727. */
  90728. set: function (value) {
  90729. this.imageProcessingConfiguration.colorGradingEnabled = value;
  90730. },
  90731. enumerable: true,
  90732. configurable: true
  90733. });
  90734. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  90735. /**
  90736. * Gets wether tonemapping is enabled or not.
  90737. */
  90738. get: function () {
  90739. return this._imageProcessingConfiguration.toneMappingEnabled;
  90740. },
  90741. /**
  90742. * Sets wether tonemapping is enabled or not
  90743. */
  90744. set: function (value) {
  90745. this._imageProcessingConfiguration.toneMappingEnabled = value;
  90746. },
  90747. enumerable: true,
  90748. configurable: true
  90749. });
  90750. ;
  90751. ;
  90752. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  90753. /**
  90754. * The camera exposure used on this material.
  90755. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90756. * This corresponds to a photographic exposure.
  90757. */
  90758. get: function () {
  90759. return this._imageProcessingConfiguration.exposure;
  90760. },
  90761. /**
  90762. * The camera exposure used on this material.
  90763. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90764. * This corresponds to a photographic exposure.
  90765. */
  90766. set: function (value) {
  90767. this._imageProcessingConfiguration.exposure = value;
  90768. },
  90769. enumerable: true,
  90770. configurable: true
  90771. });
  90772. ;
  90773. ;
  90774. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  90775. /**
  90776. * Gets The camera contrast used on this material.
  90777. */
  90778. get: function () {
  90779. return this._imageProcessingConfiguration.contrast;
  90780. },
  90781. /**
  90782. * Sets The camera contrast used on this material.
  90783. */
  90784. set: function (value) {
  90785. this._imageProcessingConfiguration.contrast = value;
  90786. },
  90787. enumerable: true,
  90788. configurable: true
  90789. });
  90790. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  90791. /**
  90792. * Gets the Color Grading 2D Lookup Texture.
  90793. */
  90794. get: function () {
  90795. return this._imageProcessingConfiguration.colorGradingTexture;
  90796. },
  90797. /**
  90798. * Sets the Color Grading 2D Lookup Texture.
  90799. */
  90800. set: function (value) {
  90801. this.imageProcessingConfiguration.colorGradingTexture = value;
  90802. },
  90803. enumerable: true,
  90804. configurable: true
  90805. });
  90806. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  90807. /**
  90808. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90809. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90810. * 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;
  90811. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90812. */
  90813. get: function () {
  90814. return this.imageProcessingConfiguration.colorCurves;
  90815. },
  90816. /**
  90817. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90818. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90819. * 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;
  90820. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90821. */
  90822. set: function (value) {
  90823. this.imageProcessingConfiguration.colorCurves = value;
  90824. },
  90825. enumerable: true,
  90826. configurable: true
  90827. });
  90828. /**
  90829. * The entire material has been created in order to prevent overdraw.
  90830. * @returns false
  90831. */
  90832. BackgroundMaterial.prototype.needAlphaTesting = function () {
  90833. return true;
  90834. };
  90835. /**
  90836. * The entire material has been created in order to prevent overdraw.
  90837. * @returns true if blending is enable
  90838. */
  90839. BackgroundMaterial.prototype.needAlphaBlending = function () {
  90840. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  90841. };
  90842. /**
  90843. * Checks wether the material is ready to be rendered for a given mesh.
  90844. * @param mesh The mesh to render
  90845. * @param subMesh The submesh to check against
  90846. * @param useInstances Specify wether or not the material is used with instances
  90847. * @returns true if all the dependencies are ready (Textures, Effects...)
  90848. */
  90849. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90850. var _this = this;
  90851. if (useInstances === void 0) { useInstances = false; }
  90852. if (subMesh.effect && this.isFrozen) {
  90853. if (this._wasPreviouslyReady) {
  90854. return true;
  90855. }
  90856. }
  90857. if (!subMesh._materialDefines) {
  90858. subMesh._materialDefines = new BackgroundMaterialDefines();
  90859. }
  90860. var scene = this.getScene();
  90861. var defines = subMesh._materialDefines;
  90862. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90863. if (defines._renderId === scene.getRenderId()) {
  90864. return true;
  90865. }
  90866. }
  90867. var engine = scene.getEngine();
  90868. // Lights
  90869. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  90870. defines._needNormals = true;
  90871. // Textures
  90872. if (defines._areTexturesDirty) {
  90873. defines._needUVs = false;
  90874. if (scene.texturesEnabled) {
  90875. if (scene.getEngine().getCaps().textureLOD) {
  90876. defines.TEXTURELODSUPPORT = true;
  90877. }
  90878. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90879. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  90880. return false;
  90881. }
  90882. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  90883. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  90884. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  90885. defines.OPACITYFRESNEL = this._opacityFresnel;
  90886. }
  90887. else {
  90888. defines.DIFFUSE = false;
  90889. defines.DIFFUSEHASALPHA = false;
  90890. defines.GAMMADIFFUSE = false;
  90891. defines.OPACITYFRESNEL = false;
  90892. }
  90893. var reflectionTexture = this._reflectionTexture;
  90894. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90895. if (!reflectionTexture.isReadyOrNotBlocking()) {
  90896. return false;
  90897. }
  90898. defines.REFLECTION = true;
  90899. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  90900. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  90901. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90902. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90903. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90904. defines.REFLECTIONBGR = this.switchToBGR;
  90905. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90906. defines.INVERTCUBICMAP = true;
  90907. }
  90908. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90909. switch (reflectionTexture.coordinatesMode) {
  90910. case BABYLON.Texture.CUBIC_MODE:
  90911. case BABYLON.Texture.INVCUBIC_MODE:
  90912. defines.REFLECTIONMAP_CUBIC = true;
  90913. break;
  90914. case BABYLON.Texture.EXPLICIT_MODE:
  90915. defines.REFLECTIONMAP_EXPLICIT = true;
  90916. break;
  90917. case BABYLON.Texture.PLANAR_MODE:
  90918. defines.REFLECTIONMAP_PLANAR = true;
  90919. break;
  90920. case BABYLON.Texture.PROJECTION_MODE:
  90921. defines.REFLECTIONMAP_PROJECTION = true;
  90922. break;
  90923. case BABYLON.Texture.SKYBOX_MODE:
  90924. defines.REFLECTIONMAP_SKYBOX = true;
  90925. break;
  90926. case BABYLON.Texture.SPHERICAL_MODE:
  90927. defines.REFLECTIONMAP_SPHERICAL = true;
  90928. break;
  90929. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90930. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90931. break;
  90932. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90933. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90934. break;
  90935. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90936. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90937. break;
  90938. }
  90939. if (this.reflectionFresnel) {
  90940. defines.REFLECTIONFRESNEL = true;
  90941. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90942. this._reflectionControls.x = this.reflectionAmount;
  90943. this._reflectionControls.y = this.reflectionReflectance0;
  90944. this._reflectionControls.z = this.reflectionReflectance90;
  90945. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90946. }
  90947. else {
  90948. defines.REFLECTIONFRESNEL = false;
  90949. defines.REFLECTIONFALLOFF = false;
  90950. }
  90951. }
  90952. else {
  90953. defines.REFLECTION = false;
  90954. defines.REFLECTIONFALLOFF = false;
  90955. defines.REFLECTIONBLUR = false;
  90956. defines.REFLECTIONMAP_3D = false;
  90957. defines.REFLECTIONMAP_SPHERICAL = false;
  90958. defines.REFLECTIONMAP_PLANAR = false;
  90959. defines.REFLECTIONMAP_CUBIC = false;
  90960. defines.REFLECTIONMAP_PROJECTION = false;
  90961. defines.REFLECTIONMAP_SKYBOX = false;
  90962. defines.REFLECTIONMAP_EXPLICIT = false;
  90963. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90964. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90965. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90966. defines.INVERTCUBICMAP = false;
  90967. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90968. defines.LODINREFLECTIONALPHA = false;
  90969. defines.GAMMAREFLECTION = false;
  90970. }
  90971. }
  90972. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90973. defines.USERGBCOLOR = this._useRGBColor;
  90974. defines.NOISE = this._enableNoise;
  90975. }
  90976. if (defines._areImageProcessingDirty) {
  90977. if (!this._imageProcessingConfiguration.isReady()) {
  90978. return false;
  90979. }
  90980. this._imageProcessingConfiguration.prepareDefines(defines);
  90981. }
  90982. // Misc.
  90983. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90984. // Values that need to be evaluated on every frame
  90985. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90986. // Attribs
  90987. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90988. if (mesh) {
  90989. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90990. mesh.createNormals(true);
  90991. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90992. }
  90993. }
  90994. }
  90995. // Get correct effect
  90996. if (defines.isDirty) {
  90997. defines.markAsProcessed();
  90998. scene.resetCachedMaterial();
  90999. // Fallbacks
  91000. var fallbacks = new BABYLON.EffectFallbacks();
  91001. if (defines.FOG) {
  91002. fallbacks.addFallback(0, "FOG");
  91003. }
  91004. if (defines.POINTSIZE) {
  91005. fallbacks.addFallback(1, "POINTSIZE");
  91006. }
  91007. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91008. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91009. fallbacks.addCPUSkinningFallback(0, mesh);
  91010. }
  91011. //Attributes
  91012. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91013. if (defines.NORMAL) {
  91014. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91015. }
  91016. if (defines.UV1) {
  91017. attribs.push(BABYLON.VertexBuffer.UVKind);
  91018. }
  91019. if (defines.UV2) {
  91020. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91021. }
  91022. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91023. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91024. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91025. "vFogInfos", "vFogColor", "pointSize",
  91026. "vClipPlane", "mBones",
  91027. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91028. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91029. "shadowLevel", "alpha",
  91030. "vBackgroundCenter", "vReflectionControl",
  91031. "vDiffuseInfos", "diffuseMatrix",
  91032. ];
  91033. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91034. var uniformBuffers = ["Material", "Scene"];
  91035. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91036. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91037. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91038. uniformsNames: uniforms,
  91039. uniformBuffersNames: uniformBuffers,
  91040. samplers: samplers,
  91041. defines: defines,
  91042. maxSimultaneousLights: this._maxSimultaneousLights
  91043. });
  91044. var onCompiled = function (effect) {
  91045. if (_this.onCompiled) {
  91046. _this.onCompiled(effect);
  91047. }
  91048. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91049. };
  91050. var join = defines.toString();
  91051. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91052. attributes: attribs,
  91053. uniformsNames: uniforms,
  91054. uniformBuffersNames: uniformBuffers,
  91055. samplers: samplers,
  91056. defines: join,
  91057. fallbacks: fallbacks,
  91058. onCompiled: onCompiled,
  91059. onError: this.onError,
  91060. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91061. }, engine), defines);
  91062. this.buildUniformLayout();
  91063. }
  91064. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91065. return false;
  91066. }
  91067. defines._renderId = scene.getRenderId();
  91068. this._wasPreviouslyReady = true;
  91069. return true;
  91070. };
  91071. /**
  91072. * Build the uniform buffer used in the material.
  91073. */
  91074. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91075. // Order is important !
  91076. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91077. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91078. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91079. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91080. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91081. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91082. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91083. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91084. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91085. this._uniformBuffer.addUniform("pointSize", 1);
  91086. this._uniformBuffer.addUniform("shadowLevel", 1);
  91087. this._uniformBuffer.addUniform("alpha", 1);
  91088. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91089. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91090. this._uniformBuffer.create();
  91091. };
  91092. /**
  91093. * Unbind the material.
  91094. */
  91095. BackgroundMaterial.prototype.unbind = function () {
  91096. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91097. this._uniformBuffer.setTexture("diffuseSampler", null);
  91098. }
  91099. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91100. this._uniformBuffer.setTexture("reflectionSampler", null);
  91101. }
  91102. _super.prototype.unbind.call(this);
  91103. };
  91104. /**
  91105. * Bind only the world matrix to the material.
  91106. * @param world The world matrix to bind.
  91107. */
  91108. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91109. this._activeEffect.setMatrix("world", world);
  91110. };
  91111. /**
  91112. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91113. * @param world The world matrix to bind.
  91114. * @param subMesh The submesh to bind for.
  91115. */
  91116. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91117. var scene = this.getScene();
  91118. var defines = subMesh._materialDefines;
  91119. if (!defines) {
  91120. return;
  91121. }
  91122. var effect = subMesh.effect;
  91123. if (!effect) {
  91124. return;
  91125. }
  91126. this._activeEffect = effect;
  91127. // Matrices
  91128. this.bindOnlyWorldMatrix(world);
  91129. // Bones
  91130. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91131. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91132. if (mustRebind) {
  91133. this._uniformBuffer.bindToEffect(effect, "Material");
  91134. this.bindViewProjection(effect);
  91135. var reflectionTexture = this._reflectionTexture;
  91136. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91137. // Texture uniforms
  91138. if (scene.texturesEnabled) {
  91139. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91140. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91141. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91142. }
  91143. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91144. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91145. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91146. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91147. }
  91148. }
  91149. if (this.shadowLevel > 0) {
  91150. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91151. }
  91152. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91153. // Point size
  91154. if (this.pointsCloud) {
  91155. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91156. }
  91157. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91158. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91159. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91160. }
  91161. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91162. // Textures
  91163. if (scene.texturesEnabled) {
  91164. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91165. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91166. }
  91167. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91168. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91169. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91170. }
  91171. else if (!defines.REFLECTIONBLUR) {
  91172. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91173. }
  91174. else {
  91175. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91176. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91177. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91178. }
  91179. if (defines.REFLECTIONFRESNEL) {
  91180. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91181. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91182. }
  91183. }
  91184. }
  91185. // Clip plane
  91186. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91187. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91188. }
  91189. if (mustRebind || !this.isFrozen) {
  91190. if (scene.lightsEnabled) {
  91191. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91192. }
  91193. // View
  91194. this.bindView(effect);
  91195. // Fog
  91196. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91197. // image processing
  91198. this._imageProcessingConfiguration.bind(this._activeEffect);
  91199. }
  91200. this._uniformBuffer.update();
  91201. this._afterBind(mesh);
  91202. };
  91203. /**
  91204. * Dispose the material.
  91205. * @param forceDisposeEffect Force disposal of the associated effect.
  91206. * @param forceDisposeTextures Force disposal of the associated textures.
  91207. */
  91208. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91209. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91210. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91211. if (forceDisposeTextures) {
  91212. if (this.diffuseTexture) {
  91213. this.diffuseTexture.dispose();
  91214. }
  91215. if (this.reflectionTexture) {
  91216. this.reflectionTexture.dispose();
  91217. }
  91218. }
  91219. this._renderTargets.dispose();
  91220. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91221. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91222. }
  91223. _super.prototype.dispose.call(this, forceDisposeEffect);
  91224. };
  91225. /**
  91226. * Clones the material.
  91227. * @param name The cloned name.
  91228. * @returns The cloned material.
  91229. */
  91230. BackgroundMaterial.prototype.clone = function (name) {
  91231. var _this = this;
  91232. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91233. };
  91234. /**
  91235. * Serializes the current material to its JSON representation.
  91236. * @returns The JSON representation.
  91237. */
  91238. BackgroundMaterial.prototype.serialize = function () {
  91239. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91240. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91241. return serializationObject;
  91242. };
  91243. /**
  91244. * Gets the class name of the material
  91245. * @returns "BackgroundMaterial"
  91246. */
  91247. BackgroundMaterial.prototype.getClassName = function () {
  91248. return "BackgroundMaterial";
  91249. };
  91250. /**
  91251. * Parse a JSON input to create back a background material.
  91252. * @param source The JSON data to parse
  91253. * @param scene The scene to create the parsed material in
  91254. * @param rootUrl The root url of the assets the material depends upon
  91255. * @returns the instantiated BackgroundMaterial.
  91256. */
  91257. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91258. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91259. };
  91260. /**
  91261. * Standard reflectance value at parallel view angle.
  91262. */
  91263. BackgroundMaterial.StandardReflectance0 = 0.05;
  91264. /**
  91265. * Standard reflectance value at grazing angle.
  91266. */
  91267. BackgroundMaterial.StandardReflectance90 = 0.5;
  91268. __decorate([
  91269. BABYLON.serializeAsColor3()
  91270. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91271. __decorate([
  91272. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91273. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91274. __decorate([
  91275. BABYLON.serialize()
  91276. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91277. __decorate([
  91278. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91279. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91280. __decorate([
  91281. BABYLON.serializeAsColor3()
  91282. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91283. __decorate([
  91284. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91285. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91286. __decorate([
  91287. BABYLON.serialize()
  91288. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91289. __decorate([
  91290. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91291. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91292. __decorate([
  91293. BABYLON.serializeAsColor3()
  91294. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91295. __decorate([
  91296. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91297. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91298. __decorate([
  91299. BABYLON.serialize()
  91300. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91301. __decorate([
  91302. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91303. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91304. __decorate([
  91305. BABYLON.serializeAsTexture()
  91306. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91307. __decorate([
  91308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91309. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91310. __decorate([
  91311. BABYLON.serialize()
  91312. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91313. __decorate([
  91314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91315. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91316. __decorate([
  91317. BABYLON.serializeAsTexture()
  91318. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91319. __decorate([
  91320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91321. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91322. __decorate([
  91323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91324. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91325. __decorate([
  91326. BABYLON.serialize()
  91327. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91328. __decorate([
  91329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91330. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  91331. __decorate([
  91332. BABYLON.serialize()
  91333. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  91334. __decorate([
  91335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91336. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  91337. __decorate([
  91338. BABYLON.serializeAsVector3()
  91339. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91340. __decorate([
  91341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91342. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91343. __decorate([
  91344. BABYLON.serialize()
  91345. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91346. __decorate([
  91347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91348. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91349. __decorate([
  91350. BABYLON.serialize()
  91351. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91352. __decorate([
  91353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91354. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  91355. __decorate([
  91356. BABYLON.serialize()
  91357. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  91358. __decorate([
  91359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91360. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  91361. __decorate([
  91362. BABYLON.serialize()
  91363. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  91364. __decorate([
  91365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91366. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  91367. __decorate([
  91368. BABYLON.serialize()
  91369. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  91370. __decorate([
  91371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91372. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  91373. __decorate([
  91374. BABYLON.serialize()
  91375. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  91376. __decorate([
  91377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91378. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  91379. __decorate([
  91380. BABYLON.serialize()
  91381. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  91382. __decorate([
  91383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91384. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  91385. __decorate([
  91386. BABYLON.serialize()
  91387. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  91388. __decorate([
  91389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91390. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  91391. __decorate([
  91392. BABYLON.serialize()
  91393. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  91394. __decorate([
  91395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91396. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  91397. __decorate([
  91398. BABYLON.serializeAsImageProcessingConfiguration()
  91399. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  91400. return BackgroundMaterial;
  91401. }(BABYLON.PushMaterial));
  91402. BABYLON.BackgroundMaterial = BackgroundMaterial;
  91403. })(BABYLON || (BABYLON = {}));
  91404. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  91405. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91406. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91407. s = arguments[i];
  91408. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91409. t[p] = s[p];
  91410. }
  91411. return t;
  91412. };
  91413. var BABYLON;
  91414. (function (BABYLON) {
  91415. /**
  91416. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  91417. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  91418. * It also helps with the default setup of your imageProcessing configuration.
  91419. */
  91420. var EnvironmentHelper = /** @class */ (function () {
  91421. /**
  91422. * constructor
  91423. * @param options
  91424. * @param scene The scene to add the material to
  91425. */
  91426. function EnvironmentHelper(options, scene) {
  91427. var _this = this;
  91428. this._errorHandler = function (message, exception) {
  91429. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  91430. };
  91431. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  91432. this._scene = scene;
  91433. this.onErrorObservable = new BABYLON.Observable();
  91434. this._setupBackground();
  91435. this._setupImageProcessing();
  91436. }
  91437. /**
  91438. * Creates the default options for the helper.
  91439. */
  91440. EnvironmentHelper._getDefaultOptions = function () {
  91441. return {
  91442. createGround: true,
  91443. groundSize: 15,
  91444. groundTexture: this._groundTextureCDNUrl,
  91445. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91446. groundOpacity: 0.9,
  91447. enableGroundShadow: true,
  91448. groundShadowLevel: 0.5,
  91449. enableGroundMirror: false,
  91450. groundMirrorSizeRatio: 0.3,
  91451. groundMirrorBlurKernel: 64,
  91452. groundMirrorAmount: 1,
  91453. groundMirrorFresnelWeight: 1,
  91454. groundMirrorFallOffDistance: 0,
  91455. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  91456. groundYBias: 0.00001,
  91457. createSkybox: true,
  91458. skyboxSize: 20,
  91459. skyboxTexture: this._skyboxTextureCDNUrl,
  91460. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91461. backgroundYRotation: 0,
  91462. sizeAuto: true,
  91463. rootPosition: BABYLON.Vector3.Zero(),
  91464. setupImageProcessing: true,
  91465. environmentTexture: this._environmentTextureCDNUrl,
  91466. cameraExposure: 0.8,
  91467. cameraContrast: 1.2,
  91468. toneMappingEnabled: true,
  91469. };
  91470. };
  91471. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  91472. /**
  91473. * Gets the root mesh created by the helper.
  91474. */
  91475. get: function () {
  91476. return this._rootMesh;
  91477. },
  91478. enumerable: true,
  91479. configurable: true
  91480. });
  91481. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  91482. /**
  91483. * Gets the skybox created by the helper.
  91484. */
  91485. get: function () {
  91486. return this._skybox;
  91487. },
  91488. enumerable: true,
  91489. configurable: true
  91490. });
  91491. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  91492. /**
  91493. * Gets the skybox texture created by the helper.
  91494. */
  91495. get: function () {
  91496. return this._skyboxTexture;
  91497. },
  91498. enumerable: true,
  91499. configurable: true
  91500. });
  91501. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  91502. /**
  91503. * Gets the skybox material created by the helper.
  91504. */
  91505. get: function () {
  91506. return this._skyboxMaterial;
  91507. },
  91508. enumerable: true,
  91509. configurable: true
  91510. });
  91511. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  91512. /**
  91513. * Gets the ground mesh created by the helper.
  91514. */
  91515. get: function () {
  91516. return this._ground;
  91517. },
  91518. enumerable: true,
  91519. configurable: true
  91520. });
  91521. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  91522. /**
  91523. * Gets the ground texture created by the helper.
  91524. */
  91525. get: function () {
  91526. return this._groundTexture;
  91527. },
  91528. enumerable: true,
  91529. configurable: true
  91530. });
  91531. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  91532. /**
  91533. * Gets the ground mirror created by the helper.
  91534. */
  91535. get: function () {
  91536. return this._groundMirror;
  91537. },
  91538. enumerable: true,
  91539. configurable: true
  91540. });
  91541. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  91542. /**
  91543. * Gets the ground mirror render list to helps pushing the meshes
  91544. * you wish in the ground reflection.
  91545. */
  91546. get: function () {
  91547. if (this._groundMirror) {
  91548. return this._groundMirror.renderList;
  91549. }
  91550. return null;
  91551. },
  91552. enumerable: true,
  91553. configurable: true
  91554. });
  91555. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  91556. /**
  91557. * Gets the ground material created by the helper.
  91558. */
  91559. get: function () {
  91560. return this._groundMaterial;
  91561. },
  91562. enumerable: true,
  91563. configurable: true
  91564. });
  91565. /**
  91566. * Updates the background according to the new options
  91567. * @param options
  91568. */
  91569. EnvironmentHelper.prototype.updateOptions = function (options) {
  91570. var newOptions = __assign({}, this._options, options);
  91571. if (this._ground && !newOptions.createGround) {
  91572. this._ground.dispose();
  91573. this._ground = null;
  91574. }
  91575. if (this._groundMaterial && !newOptions.createGround) {
  91576. this._groundMaterial.dispose();
  91577. this._groundMaterial = null;
  91578. }
  91579. if (this._groundTexture) {
  91580. if (this._options.groundTexture != newOptions.groundTexture) {
  91581. this._groundTexture.dispose();
  91582. this._groundTexture = null;
  91583. }
  91584. }
  91585. if (this._skybox && !newOptions.createSkybox) {
  91586. this._skybox.dispose();
  91587. this._skybox = null;
  91588. }
  91589. if (this._skyboxMaterial && !newOptions.createSkybox) {
  91590. this._skyboxMaterial.dispose();
  91591. this._skyboxMaterial = null;
  91592. }
  91593. if (this._skyboxTexture) {
  91594. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  91595. this._skyboxTexture.dispose();
  91596. this._skyboxTexture = null;
  91597. }
  91598. }
  91599. if (this._groundMirror && !newOptions.enableGroundMirror) {
  91600. this._groundMirror.dispose();
  91601. this._groundMirror = null;
  91602. }
  91603. if (this._scene.environmentTexture) {
  91604. if (this._options.environmentTexture != newOptions.environmentTexture) {
  91605. this._scene.environmentTexture.dispose();
  91606. }
  91607. }
  91608. this._options = newOptions;
  91609. this._setupBackground();
  91610. this._setupImageProcessing();
  91611. };
  91612. /**
  91613. * Sets the primary color of all the available elements.
  91614. * @param color
  91615. */
  91616. EnvironmentHelper.prototype.setMainColor = function (color) {
  91617. if (this.groundMaterial) {
  91618. this.groundMaterial.primaryColor = color;
  91619. }
  91620. if (this.skyboxMaterial) {
  91621. this.skyboxMaterial.primaryColor = color;
  91622. }
  91623. if (this.groundMirror) {
  91624. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  91625. }
  91626. };
  91627. /**
  91628. * Setup the image processing according to the specified options.
  91629. */
  91630. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91631. if (this._options.setupImageProcessing) {
  91632. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  91633. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  91634. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  91635. this._setupEnvironmentTexture();
  91636. }
  91637. };
  91638. /**
  91639. * Setup the environment texture according to the specified options.
  91640. */
  91641. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  91642. if (this._scene.environmentTexture) {
  91643. return;
  91644. }
  91645. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  91646. this._scene.environmentTexture = this._options.environmentTexture;
  91647. return;
  91648. }
  91649. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  91650. this._scene.environmentTexture = environmentTexture;
  91651. };
  91652. /**
  91653. * Setup the background according to the specified options.
  91654. */
  91655. EnvironmentHelper.prototype._setupBackground = function () {
  91656. if (!this._rootMesh) {
  91657. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  91658. }
  91659. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  91660. var sceneSize = this._getSceneSize();
  91661. if (this._options.createGround) {
  91662. this._setupGround(sceneSize);
  91663. this._setupGroundMaterial();
  91664. this._setupGroundDiffuseTexture();
  91665. if (this._options.enableGroundMirror) {
  91666. this._setupGroundMirrorTexture(sceneSize);
  91667. }
  91668. this._setupMirrorInGroundMaterial();
  91669. }
  91670. if (this._options.createSkybox) {
  91671. this._setupSkybox(sceneSize);
  91672. this._setupSkyboxMaterial();
  91673. this._setupSkyboxReflectionTexture();
  91674. }
  91675. this._rootMesh.position.x = sceneSize.rootPosition.x;
  91676. this._rootMesh.position.z = sceneSize.rootPosition.z;
  91677. this._rootMesh.position.y = sceneSize.rootPosition.y;
  91678. };
  91679. /**
  91680. * Get the scene sizes according to the setup.
  91681. */
  91682. EnvironmentHelper.prototype._getSceneSize = function () {
  91683. var _this = this;
  91684. var groundSize = this._options.groundSize;
  91685. var skyboxSize = this._options.skyboxSize;
  91686. var rootPosition = this._options.rootPosition;
  91687. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  91688. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91689. }
  91690. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  91691. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  91692. });
  91693. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91694. if (this._options.sizeAuto) {
  91695. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  91696. this._scene.activeCamera.upperRadiusLimit) {
  91697. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  91698. skyboxSize = groundSize;
  91699. }
  91700. var sceneDiagonalLenght = sceneDiagonal.length();
  91701. if (sceneDiagonalLenght > groundSize) {
  91702. groundSize = sceneDiagonalLenght * 2;
  91703. skyboxSize = groundSize;
  91704. }
  91705. // 10 % bigger.
  91706. groundSize *= 1.1;
  91707. skyboxSize *= 1.5;
  91708. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  91709. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  91710. }
  91711. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91712. };
  91713. /**
  91714. * Setup the ground according to the specified options.
  91715. */
  91716. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  91717. var _this = this;
  91718. if (!this._ground) {
  91719. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  91720. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  91721. this._ground.parent = this._rootMesh;
  91722. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  91723. }
  91724. this._ground.receiveShadows = this._options.enableGroundShadow;
  91725. };
  91726. /**
  91727. * Setup the ground material according to the specified options.
  91728. */
  91729. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  91730. if (!this._groundMaterial) {
  91731. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  91732. }
  91733. this._groundMaterial.alpha = this._options.groundOpacity;
  91734. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  91735. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  91736. this._groundMaterial.primaryLevel = 1;
  91737. this._groundMaterial.primaryColor = this._options.groundColor;
  91738. this._groundMaterial.secondaryLevel = 0;
  91739. this._groundMaterial.tertiaryLevel = 0;
  91740. this._groundMaterial.useRGBColor = false;
  91741. this._groundMaterial.enableNoise = true;
  91742. if (this._ground) {
  91743. this._ground.material = this._groundMaterial;
  91744. }
  91745. };
  91746. /**
  91747. * Setup the ground diffuse texture according to the specified options.
  91748. */
  91749. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  91750. if (!this._groundMaterial) {
  91751. return;
  91752. }
  91753. if (this._groundTexture) {
  91754. return;
  91755. }
  91756. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  91757. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  91758. return;
  91759. }
  91760. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91761. diffuseTexture.gammaSpace = false;
  91762. diffuseTexture.hasAlpha = true;
  91763. this._groundMaterial.diffuseTexture = diffuseTexture;
  91764. };
  91765. /**
  91766. * Setup the ground mirror texture according to the specified options.
  91767. */
  91768. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  91769. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91770. if (!this._groundMirror) {
  91771. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  91772. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  91773. this._groundMirror.anisotropicFilteringLevel = 1;
  91774. this._groundMirror.wrapU = wrapping;
  91775. this._groundMirror.wrapV = wrapping;
  91776. this._groundMirror.gammaSpace = false;
  91777. if (this._groundMirror.renderList) {
  91778. for (var i = 0; i < this._scene.meshes.length; i++) {
  91779. var mesh = this._scene.meshes[i];
  91780. if (mesh !== this._ground &&
  91781. mesh !== this._skybox &&
  91782. mesh !== this._rootMesh) {
  91783. this._groundMirror.renderList.push(mesh);
  91784. }
  91785. }
  91786. }
  91787. }
  91788. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  91789. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  91790. };
  91791. /**
  91792. * Setup the ground to receive the mirror texture.
  91793. */
  91794. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  91795. if (this._groundMaterial) {
  91796. this._groundMaterial.reflectionTexture = this._groundMirror;
  91797. this._groundMaterial.reflectionFresnel = true;
  91798. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  91799. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  91800. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  91801. }
  91802. };
  91803. /**
  91804. * Setup the skybox according to the specified options.
  91805. */
  91806. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  91807. var _this = this;
  91808. if (!this._skybox) {
  91809. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  91810. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  91811. }
  91812. this._skybox.parent = this._rootMesh;
  91813. };
  91814. /**
  91815. * Setup the skybox material according to the specified options.
  91816. */
  91817. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  91818. if (!this._skybox) {
  91819. return;
  91820. }
  91821. if (!this._skyboxMaterial) {
  91822. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  91823. }
  91824. this._skyboxMaterial.useRGBColor = false;
  91825. this._skyboxMaterial.primaryLevel = 1;
  91826. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  91827. this._skyboxMaterial.secondaryLevel = 0;
  91828. this._skyboxMaterial.tertiaryLevel = 0;
  91829. this._skyboxMaterial.enableNoise = true;
  91830. this._skybox.material = this._skyboxMaterial;
  91831. };
  91832. /**
  91833. * Setup the skybox reflection texture according to the specified options.
  91834. */
  91835. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  91836. if (!this._skyboxMaterial) {
  91837. return;
  91838. }
  91839. if (this._skyboxTexture) {
  91840. return;
  91841. }
  91842. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  91843. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91844. return;
  91845. }
  91846. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91847. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  91848. this._skyboxTexture.gammaSpace = false;
  91849. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91850. };
  91851. /**
  91852. * Dispose all the elements created by the Helper.
  91853. */
  91854. EnvironmentHelper.prototype.dispose = function () {
  91855. if (this._groundMaterial) {
  91856. this._groundMaterial.dispose(true, true);
  91857. }
  91858. if (this._skyboxMaterial) {
  91859. this._skyboxMaterial.dispose(true, true);
  91860. }
  91861. this._rootMesh.dispose(false);
  91862. };
  91863. /**
  91864. * Default ground texture URL.
  91865. */
  91866. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  91867. /**
  91868. * Default skybox texture URL.
  91869. */
  91870. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  91871. /**
  91872. * Default environment texture URL.
  91873. */
  91874. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  91875. return EnvironmentHelper;
  91876. }());
  91877. BABYLON.EnvironmentHelper = EnvironmentHelper;
  91878. })(BABYLON || (BABYLON = {}));
  91879. //# sourceMappingURL=babylon.environmentHelper.js.map
  91880. var BABYLON;
  91881. (function (BABYLON) {
  91882. /**
  91883. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  91884. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  91885. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  91886. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  91887. */
  91888. var VideoDome = /** @class */ (function (_super) {
  91889. __extends(VideoDome, _super);
  91890. /**
  91891. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  91892. * @param name Element's name, child elements will append suffixes for their own names.
  91893. * @param urlsOrVideo
  91894. * @param options An object containing optional or exposed sub element properties:
  91895. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  91896. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  91897. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  91898. * @param options **loop=true** Automatically loop video on end.
  91899. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  91900. */
  91901. function VideoDome(name, urlsOrVideo, options, scene) {
  91902. var _this = _super.call(this, name, scene) || this;
  91903. // set defaults and manage values
  91904. name = name || "videoDome";
  91905. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  91906. options.clickToPlay = Boolean(options.clickToPlay);
  91907. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  91908. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  91909. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  91910. // create
  91911. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  91912. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  91913. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  91914. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  91915. flat: false,
  91916. radius: options.size,
  91917. subdivisions: options.resolution,
  91918. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  91919. }, scene);
  91920. // configure material
  91921. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  91922. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  91923. material.reflectionTexture = _this._videoTexture;
  91924. material.useEquirectangularFOV = true;
  91925. material.fovMultiplier = 1.0;
  91926. // configure mesh
  91927. _this._mesh.material = material;
  91928. _this._mesh.parent = _this;
  91929. // optional configuration
  91930. if (options.clickToPlay) {
  91931. scene.onPointerUp = function () {
  91932. _this._videoTexture.video.play();
  91933. };
  91934. }
  91935. return _this;
  91936. }
  91937. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  91938. /**
  91939. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91940. * Also see the options.resolution property.
  91941. */
  91942. get: function () {
  91943. return this._material.fovMultiplier;
  91944. },
  91945. set: function (value) {
  91946. this._material.fovMultiplier = value;
  91947. },
  91948. enumerable: true,
  91949. configurable: true
  91950. });
  91951. /**
  91952. * Releases resources associated with this node.
  91953. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  91954. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  91955. */
  91956. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  91957. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  91958. this._videoTexture.dispose();
  91959. this._mesh.dispose();
  91960. this._material.dispose();
  91961. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  91962. };
  91963. return VideoDome;
  91964. }(BABYLON.Node));
  91965. BABYLON.VideoDome = VideoDome;
  91966. })(BABYLON || (BABYLON = {}));
  91967. //# sourceMappingURL=babylon.videoDome.js.map
  91968. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\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#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\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);\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(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\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\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#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\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 radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\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}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\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#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\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\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\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#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\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#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\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#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  91969. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=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=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,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#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\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}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\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 fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  91970. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  91971. globalObject["BABYLON"] = BABYLON
  91972. return BABYLON;
  91973. });
  91974. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)))
  91975. /***/ }),
  91976. /* 1 */
  91977. /***/ (function(module, exports, __webpack_require__) {
  91978. "use strict";
  91979. Object.defineProperty(exports, "__esModule", { value: true });
  91980. var babylonjs_1 = __webpack_require__(0);
  91981. var helper_1 = __webpack_require__(2);
  91982. var HTMLMapper = (function () {
  91983. function HTMLMapper() {
  91984. }
  91985. HTMLMapper.prototype.map = function (element) {
  91986. var config = {};
  91987. var _loop_1 = function (attrIdx) {
  91988. var attr = element.attributes.item(attrIdx);
  91989. var split = attr.nodeName.split('.');
  91990. split.reduce(function (currentConfig, key, idx) {
  91991. var camelKey = helper_1.kebabToCamel(key);
  91992. if (idx === split.length - 1) {
  91993. var val = attr.nodeValue;
  91994. if (val === "true") {
  91995. val = true;
  91996. }
  91997. else if (val === "false") {
  91998. val = false;
  91999. }
  92000. else {
  92001. var isnum = /^\d+$/.test(val);
  92002. if (isnum) {
  92003. var number = parseFloat(val);
  92004. if (!isNaN(number)) {
  92005. val = number;
  92006. }
  92007. }
  92008. }
  92009. currentConfig[camelKey] = val;
  92010. }
  92011. else {
  92012. currentConfig[camelKey] = currentConfig[camelKey] || {};
  92013. }
  92014. return currentConfig[camelKey];
  92015. }, config);
  92016. };
  92017. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  92018. _loop_1(attrIdx);
  92019. }
  92020. return config;
  92021. };
  92022. return HTMLMapper;
  92023. }());
  92024. var JSONMapper = (function () {
  92025. function JSONMapper() {
  92026. }
  92027. JSONMapper.prototype.map = function (rawSource) {
  92028. return JSON.parse(rawSource);
  92029. };
  92030. return JSONMapper;
  92031. }());
  92032. var DOMMapper = (function () {
  92033. function DOMMapper() {
  92034. }
  92035. DOMMapper.prototype.map = function (baseElement) {
  92036. var htmlMapper = new HTMLMapper();
  92037. var config = htmlMapper.map(baseElement);
  92038. var traverseChildren = function (element, partConfig) {
  92039. var children = element.children;
  92040. if (children.length) {
  92041. for (var i = 0; i < children.length; ++i) {
  92042. var item = children.item(i);
  92043. var configMapped = htmlMapper.map(item);
  92044. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  92045. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  92046. partConfig[key] = [];
  92047. }
  92048. else {
  92049. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  92050. partConfig.push(configMapped);
  92051. }
  92052. else if (partConfig[key]) {
  92053. element.setAttribute('array', 'true');
  92054. var oldItem = partConfig[key];
  92055. partConfig = [oldItem, configMapped];
  92056. }
  92057. else {
  92058. partConfig[key] = configMapped;
  92059. }
  92060. }
  92061. traverseChildren(item, partConfig[key] || configMapped);
  92062. }
  92063. }
  92064. return partConfig;
  92065. };
  92066. traverseChildren(baseElement, config);
  92067. return config;
  92068. };
  92069. return DOMMapper;
  92070. }());
  92071. var MapperManager = (function () {
  92072. function MapperManager() {
  92073. this.mappers = {
  92074. "html": new HTMLMapper(),
  92075. "json": new JSONMapper(),
  92076. "dom": new DOMMapper()
  92077. };
  92078. }
  92079. MapperManager.prototype.getMapper = function (type) {
  92080. if (!this.mappers[type]) {
  92081. babylonjs_1.Tools.Error("No mapper defined for " + type);
  92082. }
  92083. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  92084. };
  92085. MapperManager.prototype.registerMapper = function (type, mapper) {
  92086. this.mappers[type] = mapper;
  92087. };
  92088. MapperManager.DefaultMapper = 'json';
  92089. return MapperManager;
  92090. }());
  92091. exports.MapperManager = MapperManager;
  92092. exports.mapperManager = new MapperManager();
  92093. /***/ }),
  92094. /* 2 */
  92095. /***/ (function(module, exports, __webpack_require__) {
  92096. "use strict";
  92097. Object.defineProperty(exports, "__esModule", { value: true });
  92098. function isUrl(urlToCheck) {
  92099. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  92100. return true;
  92101. }
  92102. return false;
  92103. }
  92104. exports.isUrl = isUrl;
  92105. function kebabToCamel(s) {
  92106. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  92107. }
  92108. exports.kebabToCamel = kebabToCamel;
  92109. function camelToKebab(str) {
  92110. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  92111. }
  92112. exports.camelToKebab = camelToKebab;
  92113. /***/ }),
  92114. /* 3 */
  92115. /***/ (function(module, exports, __webpack_require__) {
  92116. "use strict";
  92117. Object.defineProperty(exports, "__esModule", { value: true });
  92118. var babylonjs_1 = __webpack_require__(0);
  92119. var ViewerManager = (function () {
  92120. function ViewerManager() {
  92121. this.viewers = {};
  92122. this.onViewerAddedObservable = new babylonjs_1.Observable();
  92123. }
  92124. ViewerManager.prototype.addViewer = function (viewer) {
  92125. this.viewers[viewer.getBaseId()] = viewer;
  92126. this._onViewerAdded(viewer);
  92127. };
  92128. ViewerManager.prototype.getViewerById = function (id) {
  92129. return this.viewers[id];
  92130. };
  92131. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  92132. for (var id in this.viewers) {
  92133. if (this.viewers[id].containerElement === element) {
  92134. return this.getViewerById(id);
  92135. }
  92136. }
  92137. };
  92138. ViewerManager.prototype.getViewerPromiseById = function (id) {
  92139. var _this = this;
  92140. return new Promise(function (resolve, reject) {
  92141. var localViewer = _this.getViewerById(id);
  92142. if (localViewer) {
  92143. return resolve(localViewer);
  92144. }
  92145. var viewerFunction = function (viewer) {
  92146. if (viewer.getBaseId() === id) {
  92147. resolve(viewer);
  92148. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  92149. }
  92150. };
  92151. _this.onViewerAddedObservable.add(viewerFunction);
  92152. });
  92153. };
  92154. ViewerManager.prototype._onViewerAdded = function (viewer) {
  92155. this.onViewerAdded && this.onViewerAdded(viewer);
  92156. this.onViewerAddedObservable.notifyObservers(viewer);
  92157. };
  92158. return ViewerManager;
  92159. }());
  92160. exports.ViewerManager = ViewerManager;
  92161. exports.viewerManager = new ViewerManager();
  92162. /***/ }),
  92163. /* 4 */
  92164. /***/ (function(module, exports, __webpack_require__) {
  92165. "use strict";
  92166. var __extends = (this && this.__extends) || (function () {
  92167. var extendStatics = Object.setPrototypeOf ||
  92168. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  92169. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  92170. return function (d, b) {
  92171. extendStatics(d, b);
  92172. function __() { this.constructor = d; }
  92173. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  92174. };
  92175. })();
  92176. Object.defineProperty(exports, "__esModule", { value: true });
  92177. var viewer_1 = __webpack_require__(5);
  92178. var babylonjs_1 = __webpack_require__(0);
  92179. var DefaultViewer = (function (_super) {
  92180. __extends(DefaultViewer, _super);
  92181. function DefaultViewer(containerElement, initialConfiguration) {
  92182. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  92183. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  92184. _this.containerElement = containerElement;
  92185. _this.onModelLoaded = function (model) {
  92186. var hideLoadingDelay = 500;
  92187. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  92188. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  92189. }
  92190. setTimeout(function () {
  92191. _this.hideLoadingScreen();
  92192. }, hideLoadingDelay);
  92193. return;
  92194. };
  92195. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  92196. return _this;
  92197. }
  92198. DefaultViewer.prototype.initScene = function () {
  92199. var _this = this;
  92200. return _super.prototype.initScene.call(this).then(function () {
  92201. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  92202. return _this.scene;
  92203. });
  92204. };
  92205. DefaultViewer.prototype.onTemplatesLoaded = function () {
  92206. var _this = this;
  92207. this.showLoadingScreen();
  92208. this.initNavbar();
  92209. var closeButton = document.getElementById('close-button');
  92210. if (closeButton) {
  92211. closeButton.addEventListener('pointerdown', function () {
  92212. _this.hideOverlayScreen();
  92213. });
  92214. }
  92215. return _super.prototype.onTemplatesLoaded.call(this);
  92216. };
  92217. DefaultViewer.prototype.initNavbar = function () {
  92218. var navbar = this.templateManager.getTemplate('navBar');
  92219. if (navbar) {
  92220. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  92221. var navbarShown_1 = true;
  92222. var timeoutCancel_1;
  92223. var triggerNavbar = function (show, evt) {
  92224. if (show === void 0) { show = false; }
  92225. if (!navbar || evt.button > 0)
  92226. return;
  92227. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  92228. if (show === navbarShown_1)
  92229. return;
  92230. if (show) {
  92231. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  92232. navbarShown_1 = show;
  92233. }
  92234. else {
  92235. var visibilityTimeout = 2000;
  92236. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  92237. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  92238. }
  92239. timeoutCancel_1 = setTimeout(function () {
  92240. if (navbar) {
  92241. navbar.parent.style.bottom = '-' + navbarHeight_1;
  92242. }
  92243. navbarShown_1 = show;
  92244. }, visibilityTimeout);
  92245. }
  92246. };
  92247. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  92248. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  92249. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  92250. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  92251. var viewerTemplate = this.templateManager.getTemplate('viewer');
  92252. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  92253. var triggerFullscren = function (eventData) {
  92254. if (viewerElement_1) {
  92255. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  92256. if (!fullscreenElement) {
  92257. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  92258. requestFullScreen.call(viewerElement_1);
  92259. }
  92260. else {
  92261. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  92262. exitFullscreen.call(document);
  92263. }
  92264. }
  92265. };
  92266. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  92267. }
  92268. };
  92269. DefaultViewer.prototype.prepareContainerElement = function () {
  92270. this.containerElement.style.position = 'relative';
  92271. this.containerElement.style.display = 'flex';
  92272. };
  92273. DefaultViewer.prototype.configureModel = function (modelConfiguration, model) {
  92274. _super.prototype.configureModel.call(this, modelConfiguration, model);
  92275. var navbar = this.templateManager.getTemplate('navBar');
  92276. if (!navbar)
  92277. return;
  92278. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  92279. if (metadataContainer) {
  92280. if (modelConfiguration.title !== undefined) {
  92281. var element = metadataContainer.querySelector('span.model-title');
  92282. if (element) {
  92283. element.innerHTML = modelConfiguration.title;
  92284. }
  92285. }
  92286. if (modelConfiguration.subtitle !== undefined) {
  92287. var element = metadataContainer.querySelector('span.model-subtitle');
  92288. if (element) {
  92289. element.innerHTML = modelConfiguration.subtitle;
  92290. }
  92291. }
  92292. if (modelConfiguration.thumbnail !== undefined) {
  92293. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  92294. }
  92295. }
  92296. };
  92297. DefaultViewer.prototype.loadModel = function (model) {
  92298. var _this = this;
  92299. if (model === void 0) { model = this.configuration.model; }
  92300. this.showLoadingScreen();
  92301. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  92302. console.log(error);
  92303. _this.hideLoadingScreen();
  92304. _this.showOverlayScreen('error');
  92305. return Promise.reject(error);
  92306. });
  92307. };
  92308. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  92309. var _this = this;
  92310. var template = this.templateManager.getTemplate('overlay');
  92311. if (!template)
  92312. return Promise.resolve('Overlay template not found');
  92313. return template.show((function (template) {
  92314. var canvasRect = _this.containerElement.getBoundingClientRect();
  92315. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  92316. template.parent.style.display = 'flex';
  92317. template.parent.style.width = canvasRect.width + "px";
  92318. template.parent.style.height = canvasRect.height + "px";
  92319. template.parent.style.opacity = "1";
  92320. var subTemplate = _this.templateManager.getTemplate(subScreen);
  92321. if (!subTemplate) {
  92322. return Promise.reject(subScreen + ' template not found');
  92323. }
  92324. return subTemplate.show((function (template) {
  92325. template.parent.style.display = 'flex';
  92326. return Promise.resolve(template);
  92327. }));
  92328. }));
  92329. };
  92330. DefaultViewer.prototype.hideOverlayScreen = function () {
  92331. var template = this.templateManager.getTemplate('overlay');
  92332. if (!template)
  92333. return Promise.resolve('Overlay template not found');
  92334. return template.hide((function (template) {
  92335. template.parent.style.opacity = "0";
  92336. var onTransitionEnd = function () {
  92337. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92338. template.parent.style.display = 'none';
  92339. };
  92340. template.parent.addEventListener("transitionend", onTransitionEnd);
  92341. var overlays = template.parent.querySelectorAll('.overlay');
  92342. if (overlays) {
  92343. for (var i = 0; i < overlays.length; ++i) {
  92344. var htmlElement = overlays.item(i);
  92345. htmlElement.style.display = 'none';
  92346. }
  92347. }
  92348. return Promise.resolve(template);
  92349. }));
  92350. };
  92351. DefaultViewer.prototype.showLoadingScreen = function () {
  92352. var _this = this;
  92353. var template = this.templateManager.getTemplate('loadingScreen');
  92354. if (!template)
  92355. return Promise.resolve('Loading Screen template not found');
  92356. return template.show((function (template) {
  92357. var canvasRect = _this.containerElement.getBoundingClientRect();
  92358. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  92359. template.parent.style.display = 'flex';
  92360. template.parent.style.width = canvasRect.width + "px";
  92361. template.parent.style.height = canvasRect.height + "px";
  92362. template.parent.style.opacity = "1";
  92363. template.parent.style.backgroundColor = "black";
  92364. return Promise.resolve(template);
  92365. }));
  92366. };
  92367. DefaultViewer.prototype.hideLoadingScreen = function () {
  92368. var template = this.templateManager.getTemplate('loadingScreen');
  92369. if (!template)
  92370. return Promise.resolve('Loading Screen template not found');
  92371. return template.hide((function (template) {
  92372. template.parent.style.opacity = "0";
  92373. var onTransitionEnd = function () {
  92374. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92375. template.parent.style.display = 'none';
  92376. };
  92377. template.parent.addEventListener("transitionend", onTransitionEnd);
  92378. return Promise.resolve(template);
  92379. }));
  92380. };
  92381. DefaultViewer.prototype.configureLights = function (lightsConfiguration, model) {
  92382. var _this = this;
  92383. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92384. _super.prototype.configureLights.call(this, lightsConfiguration, model);
  92385. if (this.configuration.lab && this.configuration.lab.flashlight) {
  92386. var pointerPosition = BABYLON.Vector3.Zero();
  92387. var lightTarget_1;
  92388. var angle = 0.5;
  92389. var exponent = Math.PI / 2;
  92390. if (typeof this.configuration.lab.flashlight === "object") {
  92391. exponent = this.configuration.lab.flashlight.exponent || exponent;
  92392. angle = this.configuration.lab.flashlight.angle || angle;
  92393. }
  92394. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  92395. if (typeof this.configuration.lab.flashlight === "object") {
  92396. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  92397. if (this.configuration.lab.flashlight.diffuse) {
  92398. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  92399. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  92400. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  92401. }
  92402. if (this.configuration.lab.flashlight.specular) {
  92403. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  92404. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  92405. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  92406. }
  92407. }
  92408. this.scene.constantlyUpdateMeshUnderPointer = true;
  92409. this.scene.onPointerObservable.add(function (eventData, eventState) {
  92410. if (eventData.type === 4 && eventData.pickInfo) {
  92411. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  92412. }
  92413. else {
  92414. lightTarget_1 = undefined;
  92415. }
  92416. });
  92417. var updateFlashlightFunction = function () {
  92418. if (_this.camera && flashlight) {
  92419. flashlight.position.copyFrom(_this.camera.position);
  92420. if (lightTarget_1) {
  92421. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  92422. }
  92423. }
  92424. };
  92425. this.scene.registerBeforeRender(updateFlashlightFunction);
  92426. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  92427. }
  92428. };
  92429. return DefaultViewer;
  92430. }(viewer_1.AbstractViewer));
  92431. exports.DefaultViewer = DefaultViewer;
  92432. /***/ }),
  92433. /* 5 */
  92434. /***/ (function(module, exports, __webpack_require__) {
  92435. "use strict";
  92436. Object.defineProperty(exports, "__esModule", { value: true });
  92437. var viewerManager_1 = __webpack_require__(3);
  92438. var templateManager_1 = __webpack_require__(19);
  92439. var loader_1 = __webpack_require__(22);
  92440. var babylonjs_1 = __webpack_require__(0);
  92441. var deepmerge = __webpack_require__(13);
  92442. var viewerModel_1 = __webpack_require__(30);
  92443. var AbstractViewer = (function () {
  92444. function AbstractViewer(containerElement, initialConfiguration) {
  92445. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  92446. var _this = this;
  92447. this.containerElement = containerElement;
  92448. this.resize = function () {
  92449. if (!_this.isCanvasInDOM()) {
  92450. return;
  92451. }
  92452. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  92453. return;
  92454. }
  92455. _this.engine.resize();
  92456. };
  92457. this.render = function () {
  92458. _this.scene && _this.scene.activeCamera && _this.scene.render();
  92459. };
  92460. if (containerElement.id) {
  92461. this.baseId = containerElement.id;
  92462. }
  92463. else {
  92464. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  92465. }
  92466. this.onSceneInitObservable = new babylonjs_1.Observable();
  92467. this.onEngineInitObservable = new babylonjs_1.Observable();
  92468. this.onModelLoadedObservable = new babylonjs_1.Observable();
  92469. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  92470. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  92471. this.onInitDoneObservable = new babylonjs_1.Observable();
  92472. this.onLoaderInitObservable = new babylonjs_1.Observable();
  92473. this.registeredOnBeforerenderFunctions = [];
  92474. this.models = [];
  92475. viewerManager_1.viewerManager.addViewer(this);
  92476. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  92477. this.prepareContainerElement();
  92478. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  92479. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  92480. if (_this.configuration.observers) {
  92481. _this.configureObservers(_this.configuration.observers);
  92482. }
  92483. var templateConfiguration = _this.configuration.templates || {};
  92484. _this.templateManager.initTemplate(templateConfiguration);
  92485. _this.templateManager.onAllLoaded.add(function () {
  92486. var canvas = _this.templateManager.getCanvas();
  92487. if (canvas) {
  92488. _this.canvas = canvas;
  92489. }
  92490. _this._onTemplateLoaded();
  92491. });
  92492. });
  92493. }
  92494. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  92495. get: function () {
  92496. return this._hdrSupport;
  92497. },
  92498. enumerable: true,
  92499. configurable: true
  92500. });
  92501. AbstractViewer.prototype.getBaseId = function () {
  92502. return this.baseId;
  92503. };
  92504. AbstractViewer.prototype.isCanvasInDOM = function () {
  92505. return !!this.canvas && !!this.canvas.parentElement;
  92506. };
  92507. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  92508. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  92509. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  92510. if (newConfiguration.scene) {
  92511. this.configureScene(newConfiguration.scene);
  92512. }
  92513. if (newConfiguration.optimizer) {
  92514. this.configureOptimizer(newConfiguration.optimizer);
  92515. }
  92516. if (newConfiguration.observers) {
  92517. this.configureObservers(newConfiguration.observers);
  92518. }
  92519. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  92520. this.configureModel(newConfiguration.model);
  92521. }
  92522. if (newConfiguration.lights) {
  92523. this.configureLights(newConfiguration.lights);
  92524. }
  92525. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  92526. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  92527. }
  92528. if (newConfiguration.camera) {
  92529. this.configureCamera(newConfiguration.camera);
  92530. }
  92531. };
  92532. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  92533. if (!skyboxConifguration && !groundConfiguration) {
  92534. if (this.environmentHelper) {
  92535. this.environmentHelper.dispose();
  92536. delete this.environmentHelper;
  92537. }
  92538. ;
  92539. return Promise.resolve(this.scene);
  92540. }
  92541. var options = {
  92542. createGround: !!groundConfiguration,
  92543. createSkybox: !!skyboxConifguration,
  92544. setupImageProcessing: false
  92545. };
  92546. if (groundConfiguration) {
  92547. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  92548. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  92549. if (groundSize) {
  92550. options.groundSize = groundSize;
  92551. }
  92552. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  92553. if (groundConfig.shadowLevel !== undefined) {
  92554. options.groundShadowLevel = groundConfig.shadowLevel;
  92555. }
  92556. options.enableGroundMirror = !!groundConfig.mirror;
  92557. if (groundConfig.texture) {
  92558. options.groundTexture = groundConfig.texture;
  92559. }
  92560. if (groundConfig.color) {
  92561. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  92562. }
  92563. if (groundConfig.opacity !== undefined) {
  92564. options.groundOpacity = groundConfig.opacity;
  92565. }
  92566. if (groundConfig.mirror) {
  92567. options.enableGroundMirror = true;
  92568. if (typeof groundConfig.mirror === "object") {
  92569. if (groundConfig.mirror.amount !== undefined)
  92570. options.groundMirrorAmount = groundConfig.mirror.amount;
  92571. if (groundConfig.mirror.sizeRatio !== undefined)
  92572. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  92573. if (groundConfig.mirror.blurKernel !== undefined)
  92574. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  92575. if (groundConfig.mirror.fresnelWeight !== undefined)
  92576. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  92577. if (groundConfig.mirror.fallOffDistance !== undefined)
  92578. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  92579. if (this.defaultPipelineTextureType !== undefined)
  92580. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  92581. }
  92582. }
  92583. }
  92584. var postInitSkyboxMaterial = false;
  92585. if (skyboxConifguration) {
  92586. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  92587. if (conf.material && conf.material.imageProcessingConfiguration) {
  92588. options.setupImageProcessing = false;
  92589. }
  92590. var skyboxSize = conf.scale;
  92591. if (skyboxSize) {
  92592. options.skyboxSize = skyboxSize;
  92593. }
  92594. options.sizeAuto = !options.skyboxSize;
  92595. if (conf.color) {
  92596. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  92597. }
  92598. if (conf.cubeTexture && conf.cubeTexture.url) {
  92599. if (typeof conf.cubeTexture.url === "string") {
  92600. options.skyboxTexture = conf.cubeTexture.url;
  92601. }
  92602. else {
  92603. postInitSkyboxMaterial = true;
  92604. }
  92605. }
  92606. if (conf.material && conf.material.imageProcessingConfiguration) {
  92607. postInitSkyboxMaterial = true;
  92608. }
  92609. }
  92610. options.setupImageProcessing = false;
  92611. if (!this.environmentHelper) {
  92612. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  92613. }
  92614. else {
  92615. var scene = this.environmentHelper.rootMesh.getScene();
  92616. if (scene !== this.scene) {
  92617. this.environmentHelper.dispose();
  92618. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  92619. }
  92620. else {
  92621. this.environmentHelper.updateOptions(options);
  92622. }
  92623. }
  92624. if (postInitSkyboxMaterial) {
  92625. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  92626. if (skyboxMaterial) {
  92627. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  92628. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  92629. }
  92630. }
  92631. }
  92632. };
  92633. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  92634. if (!this.scene) {
  92635. return;
  92636. }
  92637. if (sceneConfig.debug) {
  92638. this.scene.debugLayer.show();
  92639. }
  92640. else {
  92641. if (this.scene.debugLayer.isVisible()) {
  92642. this.scene.debugLayer.hide();
  92643. }
  92644. }
  92645. if (sceneConfig.clearColor) {
  92646. var cc = sceneConfig.clearColor;
  92647. var oldcc = this.scene.clearColor;
  92648. if (cc.r !== undefined) {
  92649. oldcc.r = cc.r;
  92650. }
  92651. if (cc.g !== undefined) {
  92652. oldcc.g = cc.g;
  92653. }
  92654. if (cc.b !== undefined) {
  92655. oldcc.b = cc.b;
  92656. }
  92657. if (cc.a !== undefined) {
  92658. oldcc.a = cc.a;
  92659. }
  92660. }
  92661. if (sceneConfig.imageProcessingConfiguration) {
  92662. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  92663. }
  92664. if (sceneConfig.environmentTexture) {
  92665. if (this.scene.environmentTexture) {
  92666. this.scene.environmentTexture.dispose();
  92667. }
  92668. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  92669. this.scene.environmentTexture = environmentTexture;
  92670. }
  92671. if (sceneConfig.autoRotate) {
  92672. this.camera.useAutoRotationBehavior = true;
  92673. }
  92674. };
  92675. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  92676. if (typeof optimizerConfig === 'boolean') {
  92677. if (this.sceneOptimizer) {
  92678. this.sceneOptimizer.stop();
  92679. this.sceneOptimizer.dispose();
  92680. delete this.sceneOptimizer;
  92681. }
  92682. if (optimizerConfig) {
  92683. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  92684. this.sceneOptimizer.start();
  92685. }
  92686. }
  92687. else {
  92688. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  92689. if (optimizerConfig.degradation) {
  92690. switch (optimizerConfig.degradation) {
  92691. case "low":
  92692. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  92693. break;
  92694. case "moderate":
  92695. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  92696. break;
  92697. case "hight":
  92698. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  92699. break;
  92700. }
  92701. }
  92702. if (this.sceneOptimizer) {
  92703. this.sceneOptimizer.stop();
  92704. this.sceneOptimizer.dispose();
  92705. }
  92706. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  92707. this.sceneOptimizer.start();
  92708. }
  92709. };
  92710. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  92711. if (observersConfiguration.onEngineInit) {
  92712. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  92713. }
  92714. else {
  92715. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  92716. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  92717. }
  92718. }
  92719. if (observersConfiguration.onSceneInit) {
  92720. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  92721. }
  92722. else {
  92723. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  92724. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  92725. }
  92726. }
  92727. if (observersConfiguration.onModelLoaded) {
  92728. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  92729. }
  92730. else {
  92731. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  92732. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  92733. }
  92734. }
  92735. };
  92736. AbstractViewer.prototype.configureCamera = function (cameraConfig, model) {
  92737. var _this = this;
  92738. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92739. if (!this.scene.activeCamera) {
  92740. this.scene.createDefaultCamera(true, true, true);
  92741. this.camera = this.scene.activeCamera;
  92742. }
  92743. if (cameraConfig.position) {
  92744. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  92745. }
  92746. if (cameraConfig.rotation) {
  92747. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  92748. }
  92749. this.extendClassWithConfig(this.camera, cameraConfig);
  92750. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  92751. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  92752. if (cameraConfig.behaviors) {
  92753. for (var name_1 in cameraConfig.behaviors) {
  92754. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  92755. }
  92756. }
  92757. ;
  92758. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  92759. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  92760. });
  92761. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92762. var sceneDiagonalLenght = sceneDiagonal.length();
  92763. if (isFinite(sceneDiagonalLenght))
  92764. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  92765. };
  92766. AbstractViewer.prototype.configureLights = function (lightsConfiguration, model) {
  92767. var _this = this;
  92768. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92769. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92770. if (!Object.keys(lightsConfiguration).length)
  92771. return;
  92772. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  92773. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  92774. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  92775. lightsAvailable.forEach(function (lName) {
  92776. if (lightsToConfigure.indexOf(lName) === -1) {
  92777. _this.scene.getLightByName(lName).dispose();
  92778. }
  92779. });
  92780. }
  92781. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  92782. var lightConfig = { type: 0 };
  92783. if (typeof lightsConfiguration[name] === 'object') {
  92784. lightConfig = lightsConfiguration[name];
  92785. }
  92786. lightConfig.name = name;
  92787. var light;
  92788. if (lightsAvailable.indexOf(name) === -1) {
  92789. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92790. if (!constructor)
  92791. return;
  92792. light = constructor();
  92793. }
  92794. else {
  92795. light = _this.scene.getLightByName(name);
  92796. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  92797. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  92798. light.dispose();
  92799. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92800. if (!constructor)
  92801. return;
  92802. light = constructor();
  92803. }
  92804. }
  92805. if (lightsConfiguration[name] === false) {
  92806. light.dispose();
  92807. return;
  92808. }
  92809. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  92810. light.setEnabled(enabled);
  92811. _this.extendClassWithConfig(light, lightConfig);
  92812. if (light instanceof babylonjs_1.ShadowLight) {
  92813. if (lightConfig.target) {
  92814. if (light.setDirectionToTarget) {
  92815. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  92816. light.setDirectionToTarget(target);
  92817. }
  92818. }
  92819. else if (lightConfig.direction) {
  92820. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  92821. light.direction = direction;
  92822. }
  92823. var shadowGenerator = light.getShadowGenerator();
  92824. if (lightConfig.shadowEnabled && _this.maxShadows) {
  92825. if (!shadowGenerator) {
  92826. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  92827. }
  92828. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  92829. var shadownMap = shadowGenerator.getShadowMap();
  92830. if (!shadownMap)
  92831. return;
  92832. var renderList = shadownMap.renderList;
  92833. for (var index = 0; index < focusMeshes.length; index++) {
  92834. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  92835. renderList && renderList.push(focusMeshes[index]);
  92836. }
  92837. }
  92838. }
  92839. else if (shadowGenerator) {
  92840. shadowGenerator.dispose();
  92841. }
  92842. }
  92843. });
  92844. };
  92845. AbstractViewer.prototype.configureModel = function (modelConfiguration, model) {
  92846. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92847. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  92848. var updateMeshesWithNoParent = function (variable, value, param) {
  92849. meshesWithNoParent.forEach(function (mesh) {
  92850. if (param) {
  92851. mesh[variable][param] = value;
  92852. }
  92853. else {
  92854. mesh[variable] = value;
  92855. }
  92856. });
  92857. };
  92858. var updateXYZ = function (variable, configValues) {
  92859. if (configValues.x !== undefined) {
  92860. updateMeshesWithNoParent(variable, configValues.x, 'x');
  92861. }
  92862. if (configValues.y !== undefined) {
  92863. updateMeshesWithNoParent(variable, configValues.y, 'y');
  92864. }
  92865. if (configValues.z !== undefined) {
  92866. updateMeshesWithNoParent(variable, configValues.z, 'z');
  92867. }
  92868. if (configValues.w !== undefined) {
  92869. updateMeshesWithNoParent(variable, configValues.w, 'w');
  92870. }
  92871. };
  92872. if (modelConfiguration.position) {
  92873. updateXYZ('position', modelConfiguration.position);
  92874. }
  92875. if (modelConfiguration.rotation) {
  92876. if (modelConfiguration.rotation.w) {
  92877. meshesWithNoParent.forEach(function (mesh) {
  92878. if (!mesh.rotationQuaternion) {
  92879. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  92880. }
  92881. });
  92882. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  92883. }
  92884. else {
  92885. updateXYZ('rotation', modelConfiguration.rotation);
  92886. }
  92887. }
  92888. if (modelConfiguration.scaling) {
  92889. updateXYZ('scaling', modelConfiguration.scaling);
  92890. }
  92891. if (modelConfiguration.castShadow) {
  92892. focusMeshes.forEach(function (mesh) {
  92893. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  92894. });
  92895. }
  92896. if (modelConfiguration.normalize) {
  92897. var center = false;
  92898. var unitSize = false;
  92899. var parentIndex = void 0;
  92900. if (modelConfiguration.normalize === true) {
  92901. center = true;
  92902. unitSize = true;
  92903. parentIndex = 0;
  92904. }
  92905. else {
  92906. center = !!modelConfiguration.normalize.center;
  92907. unitSize = !!modelConfiguration.normalize.unitSize;
  92908. parentIndex = modelConfiguration.normalize.parentIndex;
  92909. }
  92910. var meshesToNormalize = [];
  92911. if (parentIndex !== undefined) {
  92912. meshesToNormalize.push(focusMeshes[parentIndex]);
  92913. }
  92914. else {
  92915. meshesToNormalize = meshesWithNoParent;
  92916. }
  92917. if (unitSize) {
  92918. meshesToNormalize.forEach(function (mesh) {
  92919. mesh.normalizeToUnitCube(true);
  92920. mesh.computeWorldMatrix(true);
  92921. });
  92922. }
  92923. if (center) {
  92924. meshesToNormalize.forEach(function (mesh) {
  92925. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  92926. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  92927. var halfSizeVec = sizeVec.scale(0.5);
  92928. var center = boundingInfo.min.add(halfSizeVec);
  92929. mesh.position = center.scale(-1);
  92930. mesh.position.y += halfSizeVec.y;
  92931. mesh.computeWorldMatrix(true);
  92932. });
  92933. }
  92934. }
  92935. };
  92936. AbstractViewer.prototype.dispose = function () {
  92937. window.removeEventListener('resize', this.resize);
  92938. if (this.sceneOptimizer) {
  92939. this.sceneOptimizer.stop();
  92940. this.sceneOptimizer.dispose();
  92941. }
  92942. if (this.scene.activeCamera) {
  92943. this.scene.activeCamera.detachControl(this.canvas);
  92944. }
  92945. this.scene.dispose();
  92946. this.engine.dispose();
  92947. this.templateManager.dispose();
  92948. };
  92949. AbstractViewer.prototype.onTemplatesLoaded = function () {
  92950. return Promise.resolve(this);
  92951. };
  92952. AbstractViewer.prototype._onTemplateLoaded = function () {
  92953. var _this = this;
  92954. return this.onTemplatesLoaded().then(function () {
  92955. var autoLoadModel = !!_this.configuration.model;
  92956. return _this.initEngine().then(function (engine) {
  92957. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  92958. }).then(function () {
  92959. if (autoLoadModel) {
  92960. return _this.loadModel().then(function () { return _this.scene; });
  92961. }
  92962. else {
  92963. return _this.scene || _this.initScene();
  92964. }
  92965. }).then(function (scene) {
  92966. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  92967. }).then(function () {
  92968. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  92969. });
  92970. });
  92971. };
  92972. AbstractViewer.prototype.initEngine = function () {
  92973. this.injectCustomShaders();
  92974. var canvasElement = this.templateManager.getCanvas();
  92975. if (!canvasElement) {
  92976. return Promise.reject('Canvas element not found!');
  92977. }
  92978. var config = this.configuration.engine || {};
  92979. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  92980. babylonjs_1.Database.IDBStorageEnabled = false;
  92981. if (!config.disableResize) {
  92982. window.addEventListener('resize', this.resize);
  92983. }
  92984. this.engine.runRenderLoop(this.render);
  92985. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  92986. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  92987. this.engine.setHardwareScalingLevel(scale);
  92988. }
  92989. this.handleHardwareLimitations();
  92990. return Promise.resolve(this.engine);
  92991. };
  92992. AbstractViewer.prototype.initScene = function () {
  92993. if (this.scene) {
  92994. this.scene.dispose();
  92995. }
  92996. this.scene = new babylonjs_1.Scene(this.engine);
  92997. this.scene.createDefaultLight(true);
  92998. if (this.configuration.scene) {
  92999. this.configureScene(this.configuration.scene);
  93000. if (this.configuration.optimizer) {
  93001. this.configureOptimizer(this.configuration.optimizer);
  93002. }
  93003. }
  93004. return Promise.resolve(this.scene);
  93005. };
  93006. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  93007. var _this = this;
  93008. if (modelConfig === void 0) { modelConfig = this.configuration.model; }
  93009. if (clearScene === void 0) { clearScene = true; }
  93010. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  93011. if (!modelUrl) {
  93012. return Promise.reject("no model configuration found");
  93013. }
  93014. if (this.isLoading) {
  93015. return Promise.reject("sanother model is curently being loaded.");
  93016. }
  93017. this.isLoading = true;
  93018. if ((typeof modelConfig === 'string')) {
  93019. if (this.configuration.model && typeof this.configuration.model === 'object') {
  93020. this.configuration.model.url = modelConfig;
  93021. }
  93022. }
  93023. else {
  93024. if (this.configuration.model) {
  93025. deepmerge(this.configuration.model, modelConfig);
  93026. }
  93027. else {
  93028. this.configuration.model = modelConfig;
  93029. }
  93030. }
  93031. return Promise.resolve(this.scene).then(function (scene) {
  93032. if (!scene)
  93033. return _this.initScene();
  93034. if (clearScene) {
  93035. _this.models.forEach(function (m) { return m.dispose(); });
  93036. _this.models.length = 0;
  93037. }
  93038. return scene;
  93039. }).then(function () {
  93040. return new Promise(function (resolve, reject) {
  93041. var model = new viewerModel_1.ViewerModel(_this.configuration.model, _this.scene);
  93042. _this.models.push(model);
  93043. _this.lastUsedLoader = model.loader;
  93044. model.onLoadedObservable.add(function (model) {
  93045. resolve(model);
  93046. });
  93047. model.onLoadErrorObservable.add(function (errorObject) {
  93048. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject).then(function () {
  93049. reject(errorObject.exception);
  93050. });
  93051. });
  93052. model.onLoadProgressObservable.add(function (progressEvent) {
  93053. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  93054. });
  93055. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  93056. });
  93057. }).then(function (model) {
  93058. return _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  93059. .then(function () {
  93060. _this.configureModel(_this.configuration.model || modelConfig, model);
  93061. _this.configureLights(_this.configuration.lights);
  93062. if (_this.configuration.camera) {
  93063. _this.configureCamera(_this.configuration.camera, model);
  93064. }
  93065. return _this.initEnvironment(model);
  93066. }).then(function () {
  93067. _this.isLoading = false;
  93068. return model;
  93069. });
  93070. });
  93071. };
  93072. AbstractViewer.prototype.initEnvironment = function (model) {
  93073. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  93074. return Promise.resolve(this.scene);
  93075. };
  93076. AbstractViewer.prototype.handleHardwareLimitations = function () {
  93077. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  93078. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  93079. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  93080. this.maxShadows = 0;
  93081. }
  93082. else {
  93083. this.maxShadows = 3;
  93084. }
  93085. var caps = this.engine.getCaps();
  93086. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  93087. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  93088. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  93089. if (linearHalfFloatTargets) {
  93090. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  93091. this.shadowGeneratorBias = 0.002;
  93092. }
  93093. else if (linearFloatTargets) {
  93094. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  93095. this.shadowGeneratorBias = 0.001;
  93096. }
  93097. else {
  93098. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  93099. this.shadowGeneratorBias = 0.001;
  93100. }
  93101. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  93102. };
  93103. AbstractViewer.prototype.injectCustomShaders = function () {
  93104. var customShaders = this.configuration.customShaders;
  93105. if (!customShaders) {
  93106. return;
  93107. }
  93108. if (customShaders.shaders) {
  93109. Object.keys(customShaders.shaders).forEach(function (key) {
  93110. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  93111. });
  93112. }
  93113. if (customShaders.includes) {
  93114. Object.keys(customShaders.includes).forEach(function (key) {
  93115. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  93116. });
  93117. }
  93118. };
  93119. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  93120. var _this = this;
  93121. if (!config)
  93122. return;
  93123. Object.keys(config).forEach(function (key) {
  93124. if (key in object && typeof object[key] !== 'function') {
  93125. if (typeof object[key] === 'object') {
  93126. _this.extendClassWithConfig(object[key], config[key]);
  93127. }
  93128. else {
  93129. if (config[key] !== undefined) {
  93130. object[key] = config[key];
  93131. }
  93132. }
  93133. }
  93134. });
  93135. };
  93136. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  93137. var behavior;
  93138. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  93139. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  93140. switch (type) {
  93141. case 0:
  93142. this.camera.useAutoRotationBehavior = true;
  93143. behavior = this.camera.autoRotationBehavior;
  93144. break;
  93145. case 1:
  93146. this.camera.useBouncingBehavior = true;
  93147. behavior = this.camera.bouncingBehavior;
  93148. break;
  93149. case 2:
  93150. this.camera.useFramingBehavior = true;
  93151. behavior = this.camera.framingBehavior;
  93152. break;
  93153. default:
  93154. behavior = null;
  93155. break;
  93156. }
  93157. if (behavior) {
  93158. if (typeof behaviorConfig === "object") {
  93159. this.extendClassWithConfig(behavior, behaviorConfig);
  93160. }
  93161. }
  93162. switch (type) {
  93163. case 0:
  93164. break;
  93165. case 1:
  93166. break;
  93167. case 2:
  93168. if (config.zoomOnBoundingInfo) {
  93169. var meshes = payload;
  93170. var bounding = meshes[0].getHierarchyBoundingVectors();
  93171. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  93172. }
  93173. break;
  93174. }
  93175. };
  93176. return AbstractViewer;
  93177. }());
  93178. exports.AbstractViewer = AbstractViewer;
  93179. /***/ }),
  93180. /* 6 */
  93181. /***/ (function(module, exports) {
  93182. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  93183. /***/ }),
  93184. /* 7 */
  93185. /***/ (function(module, exports) {
  93186. module.exports = "<style>loading-screen{position:absolute;left:0;z-index:100;opacity:1;pointer-events:none;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 2s ease;-moz-transition:opacity 2s ease;transition:opacity 2s ease}img.loading-image{-webkit-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style> <img class=loading-image src={{loadingImage}}>";
  93187. /***/ }),
  93188. /* 8 */
  93189. /***/ (function(module, exports) {
  93190. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz8BV2tWcQpEDR5eR7mPjGTmP98ssvEyra5N1CnZNZBL+Dp9mUF7A2a0W7u6dlE8/E82Ve0zVlCHz3HhFtnGAmfJWPC5Nm4pfSO6YLWIdVee/bOiFTiz1A/zL9xSpJqjLmpGHJZHJW9sDlvB/yul7gHlze4sY0Wr7UQLrwierA5fJf7eISrcaE9jHuh/TXsLk3j0aj81dbepRbUkXND40Gz7Hx1/SdaIRcz9BCxjDHh/A4nlMAxvjbKa0wZGaDKmeCO5nLAQoQOzs7fa86pVKpOfj2lSDsdc60N5Reat380uD5DfuyZ5KBwGzOc0jNiWCvet1QfONH+ushcz/M6AoqIUojapgWzgauBTEfiP6QzS+ix/E0qW6CB9MFCL7/G5Pd1DGd+uyz8SHmKB0eVPC9KAvwA3iK56Py6fTasVhseoMnVuMrs6h0seWelFnI9PqgIG+DTT2dSSsFsgw3+1z1ZpUsyyzOMrz7+QgH77+CB9gAp/HTWqFQaEqZMMOp4hKMd7hN1DcgxfMzLiLfsZFlMf7mScngA9Gfqp7w3XffuSe6WCi8Y9WufUYwsUKZY0EVVA5FoB3wR3MZNquTg3mxMNvSXw0+Bn1OrgBcid+ds9IxkHc51ljWJuNDAPsb67I/j5O5EfKaGkeyaSZ5hEktdEhxZrGs3GqMfxKL9aYCPJCtYqET4BIep6zQzI9N1L20rIA02geiO5HhYKunZ5JKdtgpNThSCzGpt+2z3YN0N8rkOaoW1K7Iicy9Gfs2HeuBrM+ytWuh3WiULvQxn2d90uh2OmUIkzpp8MZ+ayj4lcFvl6ZiznRxbRKTEe0j3JdizPkYb3fGvUim1n1FzptG4XP3rjQQ03tgWeW/oFBlPv8s8h6tG6GO1tBOKYoeKkFt4HmdhbI7V+F7Rk9P2traJlKRoZTP6x7WOeAl5tFZJyXOt3Xm/eabb47nwkWuCl4YHQf8nheh4BkgQpfWGrjxwdOAlEsNvR/sh6ldsJbXShlrXDbSyfV8tmznse/SL+ZCrnGUSvJ3X/6toUAaeowIVbXNa1rQ78IcfaCc1s+bkWj+ijKvCvjoj6Sf0Mm/5jOZbXinrc4PLdJQfbdSKzeuxkjFTSdJbs43qw2QtFNtX7mrTmr+c1+5OMIYz5VLRfj/2XnvlQa4ypMBCi6nMW7hwmFdI553VDXpB1wQHKyEYL0DZrHvLJ8LXnbjK2WmdCb9iMOF88+cK2D1d8MD96Kqm5+ZAlgHKBZ5Q8rHml3i6VRJGlfJDUI7Oo/4UAG7tdx4mPhlHSpy9Ub0oA4/qvGryrsVlOmuG/37IDniiZy4HOkPC9nsTm4miXlcrZIJ4X82gaA/2zvneNmdHoz/bNu2bdu2bdu2bdu2bdu2fbz3zfe9+eOizelMs93uns7n08uz0+48nUzwJPnFyQO2QAZi/IXNwgGTdXlTgFrfMnH4P9mRS6m18GgWFio/7xFVWiJAS59aHu5Tj7MMBQyxbIktFo1d0kS86mmMtZsmNGYOlknB6wkCTA8mWS5EtPz888+cxXc6vfkPmAqYcsAMxbFUmvZX77wzlhF82SqU4Pf++++PmjeqhBg4OS1QYCldAs4NTgvzrTzDWuxY435wwPYtMweMNXdk3NjzYd8GTHRWyhyE1xboxUzaS47JLieHwhmcvb0oYIvJz35Z0nP4o14YNxcEznenGVXKCTAi5VYCC3CnrXOS//dKJiP4j7entxCk/Bzet1rJAL463D9h42K9LSdmnUhE3yuWSNFA/f6WQsROh9HoyAHbRz1glptzh/JkKdqAqFfrjZD5RFrtZ+3glcNlvX1mCIA3GvYegQ54TM85Ltg9YsNNZu0KAXmz8uzgrtMss0/W7z8v64YdvKQHwElaL1xiK4dJFv2RvPYrURe513dynfYtgXD/8Kj7YFM5BoG6xEs2kyXvx8k6IYFzWcRxEjIKt0/5eezgqSzxqYVRahFsymc06jKHIaJLCLC94zr//XcBXno3F3I/IbOxYHkMalnk2SzfMp4t68yBSmP5lTVH6HUB9VxscXljxzGwLDXA7DjJJZ7F6znVmTRsb1/+qTwA828Z+FjbWvYrGQcDShICFPLw10C9wSHDbrchbBqArR3HZtk2cL779aOmAnJ/1gnZjSbAtv16ouWDVc7WHvIzM1iaeCsDjIYduIOvyPLl9wh4wF0Tio1NEVCt5lZxYY5arzpZcovV5Zq8rAALlfZdi9pDFC3whdktyw7ekLWPnZBzNDDm+xxi12FXjkbylizKkfLnxwZgTy5R4h18fy9YvB8yn4j0DTMFkUkBzaLN4hjxyJTAr2x5ogwxPp0sws4Q/nCypzxzmQG+1yHjxNCJjBik/PDFGWT+fV6pMMpEWNPSsDUBey2lv3xoBhHKDzAb5AS7XEaQRdPz66+/Tpp5dzwnpK/u7p7HI0QMouWDyDf6scQXpn+Nj5fCmZSl38G7eWV94meIKB3YDwf9s4HsSgC+JeYLy+e+I7nK1iZbB2Ap/radEQGbP3Dt3o4uwZvmK64JFQd6pxcgmgg+Qh8BmO87vaFg7Ro41zl5CppN2dNT+96w43wA1vn6EMDTegX6SYTLaVeS61r7KQu7Um52pifAHW1tJ7cawCiIkn4ygbGDbwqcb+nsaBrnAmJ0EHblwoaLzQNg5tu6BQH+2DERoSbYLBiUfZDmK2Yi3j7/BTRF9Ip9CWAUTfn/DwLm+o30o6BkNHKG0/KP2jq6t+Kl0cmXcwT4b1HaxuoLAFPawTEODCtmhKD0TBK7RI0/PM3b1dnZvSM7OSFNggdcIfaLy73nbH2AbaqOUpjbA+Z6MCoZTQt0pXqXNCfojATTas5IdgZn+mJ9ZAefYYRLlwt8We4MhBfwOm8bIBd4rbSzuo00CUvEOAAiZZKWazWAKfriFc4kyz9XicP+jS+6Vg34rCvAYoot0GoAW1Qd6EeBO3iXGJNop0GZGAT4iwPY4Iq1AMBSI3Mhr0C/YDVvzA6eNYngJl4tRLI5cF/KGfO9IyBjtRLAOIgsogME/ZD5BJNpggHmQykP959c0+WqGGAHrTdtOYDDqTofhSTJx1CaACiVmaEPMJU3wPo2Ht/qAFvsR0zQkNojYFGXGpY8BEEIb4ApJ9jqAFtUHanDOXkIN7ynq+uaaIDxtvTyJn6QlqcrovYOLwcA+a5yr7+bGWCtoUU9MbrQLO4U6AeDs/Ls4LMy3OBjkrttdmY+gHGZQnZvNoAV1E9kjc6jQFyGemI4OZYOtIHXjQZYPnxQxrfoLbp9ebQKAGBb5JcZYC3P39PzBlWFtIDZUHVusbBEIQRxrVc1Ql8EWIn8b9IEC8J+niq6pO6EBGfylGTCVFoy8IvejPqfI4aL0X53MwDM4mrVm508a1ozp3e9svBsQ/umt5LhB98oCuD29rfKCrD65R+mRieZE57Vc2uSXgvHO6CuGEfjO5izeQCGm/tv6EJop7SZPQPhnZ0d9xcNcK3/+EELr64FqJ5FVXEmAaoIeM3E8DO37OGgvVJ63hFgRP5ZRQGsvQavFY12JepcOye+TUoNbfn9BUDNGZE6x+OBHi+eymJrl94Aaz3mD4hty6Kt4pkQp1ki0xLxYS0B1ZU473DoH9mqAJMNoHlYmDPh/ly7itDMslP3o/J8LlDt9N1V/FvftQDA+NFlvnm1iq3LoPEmJSQE1MPpy1iTUTyvOmLwlmTl+cr4yuGhO+67777R/AH2HzgxKFkhgB4TkAzn1joQgmJhre+0edW4ohG+m/fhP/3008kSCAg7lwFgCIk07+LokuvdRhRW0w42l7n1GeLNzLLznn766THFszKjgPyTt+gRE2XDRgGMKEf8yqIeX8RONepmP6/tDsb27g72cpaHkMJdU+nPL8Bb5gkw/1YkwLhdaXujlerfb9BORbt/n3omBmsj/yDCgRcnABjs1o1565oJYJwPKn5P1CZa3Q3s+X8Jz2Jo975Dazz2hACjBn1XmQHWvhLzyoIeS3y7iJ1q+LZvo8oBzTfrCqZBJTkzBBit93F22QBWX/lSBN8bulO1kRat6SS3aLzi0LSTwV8KAYa+wFqQNPMQhWr9pNL2eQCmtyANl2lxC1GtwU2z3tR48cwR+tDwHX//PXNAnDmcbSkPl9iSXTTotQ0x+EwA8W6HQed4/fXXJ470iZ+tjSl/LkT82r0GLxSrZIGYeDFVeeXIO1S1+Hvr3cp8Wbk6E2K5OxsPODH+3lgfqzg/EKse3VuKtldvr0mTENI7I9Z5XMS3xp07jIp2/ucxiWehzm91EX4bDnBxncod7dXdJHth7BgRLEfJalQBxFsVsj7u7VxpsBF4Y0Q8u//vpgXYtldPoK1cjM0NKY+MQ/oRZwgTLlOUZj0KpkXom6U1JNuaHWC1Vy+CXBdjr2rA/2BAlaun0CBDgEiZEgUiVHRQQcDol7tXWQFWe/VW+eMaFKAJPdrQRQTUrRDjkY2hvyq8NT5Bcs0+vCThv4c0amKekqTZtv377/Up93m3gabNk/Qb/O6778aNad9L02iZ4344bjnTXj50BS9gRx4u5XHvShFFU6SxHeQztw36JVLm4R6PNMBePepvsTtjzlWZY0FKAnva3dQQbQjAGN7yhu+SIloBcYyUlnej0kUzC5kMznRR9iolo2JEIbxo+iLXy0OGS3WIRo201Ayp1PIeIKa0vQO48eXBv2kQwCza/+3V7nh7dXL57E4yhw/nymZ5LjZE2YZU67lHF/LWNBebiMFZ8TYVBbDaq8/J7xvHdOZGwULRkjnuqHdzavQbuQ987JU0F7iBwwBGz7VT08jaND7my9QLYOxVje0eGGOv0otJRPeisCkwkQoIRKADHGk/a4kAZtRkiEZ5jGEbbk32QIoWfUZsa3WaZckf5yD4EXGuTq89nb50az5t94G6VV6khQs3h7zSUMnAs6q7S87xRoiiBH/2UYF+YMjra8ifR40IjeLc30vmeAlxXoAn7AV6L9r9K0oOcELVnhUD51k5w1mForNtjB8YjV4WeWOZ4yG52gryhF0K30uPraYciNZT076gXFPnSWfVanxvYK/WpElHxMs3IpXlWOgi4sQ8L1IBp4laFc0/iO/WZKR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  93191. /***/ }),
  93192. /* 9 */
  93193. /***/ (function(module, exports) {
  93194. module.exports = "<style>viewer{position:relative;overflow:hidden;flex:1;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas id={{canvasId}}> </canvas> <nav-bar></nav-bar>";
  93195. /***/ }),
  93196. /* 10 */
  93197. /***/ (function(module, exports) {
  93198. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}.overlay-item{width:100%;height:100%;display:none;align-items:center;justify-content:center;background-color:rgba(121,121,121,.3)}error.overlay-item{background-color:rgba(121,121,121,1)}div#close-button{position:absolute;top:10px;right:10px;width:30px;height:30px;cursor:pointer}div#close-button img{width:100%}</style> <div id=close-button> <img src={{closeImage}} alt={{closeText}}> </div> <help class=overlay-item></help> <error class=overlay-item></error> <share class=overlay-item></share>";
  93199. /***/ }),
  93200. /* 11 */
  93201. /***/ (function(module, exports) {
  93202. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  93203. /***/ }),
  93204. /* 12 */
  93205. /***/ (function(module, exports) {
  93206. module.exports = "Error loading the model";
  93207. /***/ }),
  93208. /* 13 */
  93209. /***/ (function(module, exports, __webpack_require__) {
  93210. (function (global, factory) {
  93211. true ? module.exports = factory() :
  93212. typeof define === 'function' && define.amd ? define(factory) :
  93213. (global.deepmerge = factory());
  93214. }(this, (function () { 'use strict';
  93215. var isMergeableObject = function isMergeableObject(value) {
  93216. return isNonNullObject(value)
  93217. && !isSpecial(value)
  93218. };
  93219. function isNonNullObject(value) {
  93220. return !!value && typeof value === 'object'
  93221. }
  93222. function isSpecial(value) {
  93223. var stringValue = Object.prototype.toString.call(value);
  93224. return stringValue === '[object RegExp]'
  93225. || stringValue === '[object Date]'
  93226. || isReactElement(value)
  93227. }
  93228. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  93229. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  93230. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  93231. function isReactElement(value) {
  93232. return value.$$typeof === REACT_ELEMENT_TYPE
  93233. }
  93234. function emptyTarget(val) {
  93235. return Array.isArray(val) ? [] : {}
  93236. }
  93237. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  93238. var clone = !optionsArgument || optionsArgument.clone !== false;
  93239. return (clone && isMergeableObject(value))
  93240. ? deepmerge(emptyTarget(value), value, optionsArgument)
  93241. : value
  93242. }
  93243. function defaultArrayMerge(target, source, optionsArgument) {
  93244. return target.concat(source).map(function(element) {
  93245. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  93246. })
  93247. }
  93248. function mergeObject(target, source, optionsArgument) {
  93249. var destination = {};
  93250. if (isMergeableObject(target)) {
  93251. Object.keys(target).forEach(function(key) {
  93252. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  93253. });
  93254. }
  93255. Object.keys(source).forEach(function(key) {
  93256. if (!isMergeableObject(source[key]) || !target[key]) {
  93257. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  93258. } else {
  93259. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  93260. }
  93261. });
  93262. return destination
  93263. }
  93264. function deepmerge(target, source, optionsArgument) {
  93265. var sourceIsArray = Array.isArray(source);
  93266. var targetIsArray = Array.isArray(target);
  93267. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  93268. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  93269. if (!sourceAndTargetTypesMatch) {
  93270. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  93271. } else if (sourceIsArray) {
  93272. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  93273. return arrayMerge(target, source, optionsArgument)
  93274. } else {
  93275. return mergeObject(target, source, optionsArgument)
  93276. }
  93277. }
  93278. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  93279. if (!Array.isArray(array)) {
  93280. throw new Error('first argument should be an array')
  93281. }
  93282. return array.reduce(function(prev, next) {
  93283. return deepmerge(prev, next, optionsArgument)
  93284. }, {})
  93285. };
  93286. var deepmerge_1 = deepmerge;
  93287. return deepmerge_1;
  93288. })));
  93289. /***/ }),
  93290. /* 14 */
  93291. /***/ (function(module, exports, __webpack_require__) {
  93292. module.exports = __webpack_require__(15);
  93293. /***/ }),
  93294. /* 15 */
  93295. /***/ (function(module, exports, __webpack_require__) {
  93296. "use strict";
  93297. Object.defineProperty(exports, "__esModule", { value: true });
  93298. var mappers_1 = __webpack_require__(1);
  93299. exports.mapperManager = mappers_1.mapperManager;
  93300. var viewerManager_1 = __webpack_require__(3);
  93301. exports.viewerManager = viewerManager_1.viewerManager;
  93302. var defaultViewer_1 = __webpack_require__(4);
  93303. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  93304. var viewer_1 = __webpack_require__(5);
  93305. exports.AbstractViewer = viewer_1.AbstractViewer;
  93306. var babylonjs_1 = __webpack_require__(0);
  93307. __webpack_require__(32);
  93308. __webpack_require__(33);
  93309. var initializer_1 = __webpack_require__(34);
  93310. exports.InitTags = initializer_1.InitTags;
  93311. babylonjs_1.PromisePolyfill.Apply();
  93312. exports.disableInit = false;
  93313. document.addEventListener("DOMContentLoaded", function (event) {
  93314. if (exports.disableInit)
  93315. return;
  93316. initializer_1.InitTags();
  93317. });
  93318. /***/ }),
  93319. /* 16 */
  93320. /***/ (function(module, exports) {
  93321. var g;
  93322. // This works in non-strict mode
  93323. g = (function() {
  93324. return this;
  93325. })();
  93326. try {
  93327. // This works if eval is allowed (see CSP)
  93328. g = g || Function("return this")() || (1,eval)("this");
  93329. } catch(e) {
  93330. // This works if the window reference is available
  93331. if(typeof window === "object")
  93332. g = window;
  93333. }
  93334. // g can still be undefined, but nothing to do about it...
  93335. // We return undefined, instead of nothing here, so it's
  93336. // easier to handle this case. if(!global) { ...}
  93337. module.exports = g;
  93338. /***/ }),
  93339. /* 17 */
  93340. /***/ (function(module, exports) {
  93341. module.exports = cannon;
  93342. /***/ }),
  93343. /* 18 */
  93344. /***/ (function(module, exports, __webpack_require__) {
  93345. /**
  93346. * from OimoPhysics DEV 1.1.0a AS3
  93347. * @author Saharan / http://el-ement.com/
  93348. *
  93349. * to Oimo.js 2015 JAVASCRIPT
  93350. * @author LoTh / http://lo-th.github.io/labs/
  93351. */
  93352. var OIMO = {
  93353. REVISION: "1.2",
  93354. // Global identification of next shape.
  93355. // This will be incremented every time a shape is created.
  93356. nextID: 0,
  93357. proxyID: 0,
  93358. // BroadPhase
  93359. BR_NULL: 0,
  93360. BR_BRUTE_FORCE: 1,
  93361. BR_SWEEP_AND_PRUNE: 2,
  93362. BR_BOUNDING_VOLUME_TREE: 3,
  93363. // body type
  93364. BODY_NULL: 0,
  93365. BODY_DYNAMIC: 1,
  93366. BODY_STATIC: 2,
  93367. // shape type
  93368. SHAPE_NULL: 0,
  93369. SHAPE_SPHERE: 1,
  93370. SHAPE_BOX: 2,
  93371. SHAPE_CYLINDER: 3,
  93372. SHAPE_TETRA: 4,
  93373. // joint type
  93374. JOINT_NULL: 0,
  93375. JOINT_DISTANCE: 1,
  93376. JOINT_BALL_AND_SOCKET: 2,
  93377. JOINT_HINGE: 3,
  93378. JOINT_WHEEL: 4,
  93379. JOINT_SLIDER: 5,
  93380. JOINT_PRISMATIC: 6,
  93381. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  93382. // scale all by 100 so object is between 10 to 10000 three unit.
  93383. WORLD_SCALE: 100,
  93384. INV_SCALE: 0.01,
  93385. // AABB aproximation
  93386. AABB_PROX: 0.005,
  93387. // Math function
  93388. sqrt: Math.sqrt,
  93389. abs: Math.abs,
  93390. floor: Math.floor,
  93391. cos: Math.cos,
  93392. sin: Math.sin,
  93393. acos: Math.acos,
  93394. asin: Math.asin,
  93395. atan2: Math.atan2,
  93396. round: Math.round,
  93397. pow: Math.pow,
  93398. max: Math.max,
  93399. min: Math.min,
  93400. random: Math.random,
  93401. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  93402. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  93403. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  93404. int: function (x) { return ~~x; },
  93405. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  93406. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  93407. degtorad: 0.0174532925199432957,
  93408. radtodeg: 57.295779513082320876,
  93409. PI: 3.141592653589793,
  93410. TwoPI: 6.283185307179586,
  93411. PI90: 1.570796326794896,
  93412. PI270: 4.712388980384689,
  93413. CustomError: null,
  93414. Error: function (Class, Msg) {
  93415. if (OIMO.CustomError == null) console.error(Class, Msg);
  93416. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  93417. }
  93418. };
  93419. var OIMO_ARRAY_TYPE;
  93420. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  93421. try {
  93422. (function (w) {
  93423. var perfNow;
  93424. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  93425. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  93426. var n = perfNowNames[i];
  93427. if (!!w['performance'][n]) {
  93428. perfNow = function () { return w['performance'][n]() };
  93429. break;
  93430. }
  93431. }
  93432. if (!perfNow) perfNow = Date.now;
  93433. //w.perfNow = perfNow;
  93434. OIMO.now = perfNow;
  93435. })(window);
  93436. } catch (e) { OIMO.now = function () { return 0; }; }
  93437. /**
  93438. * The class of physical computing world.
  93439. * You must be added to the world physical all computing objects
  93440. * @author saharan
  93441. * @author lo-th
  93442. */
  93443. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  93444. // The time between each step
  93445. this.timeStep = TimeStep || 0.01666; // 1/60;
  93446. // The number of iterations for constraint solvers.
  93447. this.numIterations = Iterations || 8;
  93448. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  93449. switch (BroadPhaseType || 2) {
  93450. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  93451. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  93452. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  93453. }
  93454. // This is the detailed information of the performance.
  93455. this.performance = null;
  93456. this.isNoStat = NoStat || false;
  93457. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  93458. // Whether the constraints randomizer is enabled or not.
  93459. this.enableRandomizer = true;
  93460. // The rigid body list
  93461. this.rigidBodies = null;
  93462. // number of rigid body
  93463. this.numRigidBodies = 0;
  93464. // The contact list
  93465. this.contacts = null;
  93466. this.unusedContacts = null;
  93467. // The number of contact
  93468. this.numContacts = 0;
  93469. // The number of contact points
  93470. this.numContactPoints = 0;
  93471. // The joint list
  93472. this.joints = null;
  93473. // The number of joints.
  93474. this.numJoints = 0;
  93475. // The number of simulation islands.
  93476. this.numIslands = 0;
  93477. // The gravity in the world.
  93478. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  93479. var numShapeTypes = 5;//4;//3;
  93480. this.detectors = [];
  93481. this.detectors.length = numShapeTypes;
  93482. var i = numShapeTypes;
  93483. while (i--) {
  93484. this.detectors[i] = [];
  93485. this.detectors[i].length = numShapeTypes;
  93486. }
  93487. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  93488. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  93489. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  93490. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  93491. // CYLINDER add
  93492. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  93493. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  93494. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  93495. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  93496. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  93497. // TETRA add
  93498. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  93499. this.randX = 65535;
  93500. this.randA = 98765;
  93501. this.randB = 123456789;
  93502. //this.maxIslandRigidBodies = 64;
  93503. this.islandRigidBodies = [];
  93504. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  93505. this.islandStack = [];
  93506. //this.islandStack.length = this.maxIslandRigidBodies;
  93507. //this.maxIslandConstraints = 128;
  93508. this.islandConstraints = [];
  93509. //this.islandConstraints.length = this.maxIslandConstraints;
  93510. };
  93511. OIMO.World.prototype = {
  93512. constructor: OIMO.World,
  93513. /**
  93514. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  93515. */
  93516. clear: function () {
  93517. this.randX = 65535;
  93518. while (this.joints !== null) {
  93519. this.removeJoint(this.joints);
  93520. }
  93521. while (this.contacts !== null) {
  93522. this.removeContact(this.contacts);
  93523. }
  93524. while (this.rigidBodies !== null) {
  93525. this.removeRigidBody(this.rigidBodies);
  93526. }
  93527. OIMO.nextID = 0;
  93528. OIMO.proxyID = 0;
  93529. },
  93530. /**
  93531. * I'll add a rigid body to the world.
  93532. * Rigid body that has been added will be the operands of each step.
  93533. * @param rigidBody Rigid body that you want to add
  93534. */
  93535. addRigidBody: function (rigidBody) {
  93536. if (rigidBody.parent) {
  93537. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  93538. }
  93539. rigidBody.parent = this;
  93540. rigidBody.awake();
  93541. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  93542. this.addShape(shape);
  93543. }
  93544. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  93545. this.rigidBodies = rigidBody;
  93546. this.numRigidBodies++;
  93547. },
  93548. /**
  93549. * I will remove the rigid body from the world.
  93550. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  93551. * @param rigidBody Rigid body to be removed
  93552. */
  93553. removeRigidBody: function (rigidBody) {
  93554. var remove = rigidBody;
  93555. if (remove.parent !== this) return;
  93556. remove.awake();
  93557. var js = remove.jointLink;
  93558. while (js != null) {
  93559. var joint = js.joint;
  93560. js = js.next;
  93561. this.removeJoint(joint);
  93562. }
  93563. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  93564. this.removeShape(shape);
  93565. }
  93566. var prev = remove.prev;
  93567. var next = remove.next;
  93568. if (prev !== null) prev.next = next;
  93569. if (next !== null) next.prev = prev;
  93570. if (this.rigidBodies == remove) this.rigidBodies = next;
  93571. remove.prev = null;
  93572. remove.next = null;
  93573. remove.parent = null;
  93574. this.numRigidBodies--;
  93575. },
  93576. getByName: function (name) {
  93577. var result = null;
  93578. var body = this.rigidBodies;
  93579. while (body !== null) {
  93580. if (body.name !== " " && body.name === name) result = body;
  93581. body = body.next;
  93582. }
  93583. var joint = this.joints;
  93584. while (joint !== null) {
  93585. if (joint.name !== "" && joint.name === name) result = joint;
  93586. joint = joint.next;
  93587. }
  93588. return result;
  93589. },
  93590. /**
  93591. * I'll add a shape to the world..
  93592. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  93593. * Shape will be added to the world automatically, please do not call from outside this method.
  93594. * @param shape Shape you want to add
  93595. */
  93596. addShape: function (shape) {
  93597. if (!shape.parent || !shape.parent.parent) {
  93598. OIMO.Error("World", "It is not possible to be added alone to shape world");
  93599. }
  93600. shape.proxy = this.broadPhase.createProxy(shape);
  93601. shape.updateProxy();
  93602. this.broadPhase.addProxy(shape.proxy);
  93603. },
  93604. /**
  93605. * I will remove the shape from the world.
  93606. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  93607. * Shape will be added to the world automatically, please do not call from outside this method.
  93608. * @param shape Shape you want to delete
  93609. */
  93610. removeShape: function (shape) {
  93611. this.broadPhase.removeProxy(shape.proxy);
  93612. shape.proxy = null;
  93613. },
  93614. /**
  93615. * I'll add a joint to the world.
  93616. * Joint that has been added will be the operands of each step.
  93617. * @param shape Joint to be added
  93618. */
  93619. addJoint: function (joint) {
  93620. if (joint.parent) {
  93621. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  93622. }
  93623. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  93624. this.joints = joint;
  93625. joint.parent = this;
  93626. this.numJoints++;
  93627. joint.awake();
  93628. joint.attach();
  93629. },
  93630. /**
  93631. * I will remove the joint from the world.
  93632. * Joint that has been added will be the operands of each step.
  93633. * @param shape Joint to be deleted
  93634. */
  93635. removeJoint: function (joint) {
  93636. var remove = joint;
  93637. var prev = remove.prev;
  93638. var next = remove.next;
  93639. if (prev !== null) prev.next = next;
  93640. if (next !== null) next.prev = prev;
  93641. if (this.joints == remove) this.joints = next;
  93642. remove.prev = null;
  93643. remove.next = null;
  93644. this.numJoints--;
  93645. remove.awake();
  93646. remove.detach();
  93647. remove.parent = null;
  93648. },
  93649. worldscale: function (scale) {
  93650. OIMO.WORLD_SCALE = scale || 100;
  93651. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  93652. },
  93653. addContact: function (s1, s2) {
  93654. var newContact;
  93655. if (this.unusedContacts !== null) {
  93656. newContact = this.unusedContacts;
  93657. this.unusedContacts = this.unusedContacts.next;
  93658. } else {
  93659. newContact = new OIMO.Contact();
  93660. }
  93661. newContact.attach(s1, s2);
  93662. newContact.detector = this.detectors[s1.type][s2.type];
  93663. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  93664. this.contacts = newContact;
  93665. this.numContacts++;
  93666. },
  93667. removeContact: function (contact) {
  93668. var prev = contact.prev;
  93669. var next = contact.next;
  93670. if (next) next.prev = prev;
  93671. if (prev) prev.next = next;
  93672. if (this.contacts == contact) this.contacts = next;
  93673. contact.prev = null;
  93674. contact.next = null;
  93675. contact.detach();
  93676. contact.next = this.unusedContacts;
  93677. this.unusedContacts = contact;
  93678. this.numContacts--;
  93679. },
  93680. checkContact: function (name1, name2) {
  93681. var n1, n2;
  93682. var contact = this.contacts;
  93683. while (contact !== null) {
  93684. n1 = contact.body1.name || ' ';
  93685. n2 = contact.body2.name || ' ';
  93686. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  93687. else contact = contact.next;
  93688. }
  93689. return false;
  93690. },
  93691. callSleep: function (body) {
  93692. if (!body.allowSleep) return false;
  93693. if (body.linearVelocity.lengthSq() > 0.04) return false;
  93694. if (body.angularVelocity.lengthSq() > 0.25) return false;
  93695. return true;
  93696. },
  93697. /**
  93698. * I will proceed only time step seconds time of World.
  93699. */
  93700. step: function () {
  93701. var time0, time1, time2, time3;
  93702. var stat = !this.isNoStat ? true : false;
  93703. if (stat) time0 = OIMO.now();
  93704. var body = this.rigidBodies;
  93705. while (body !== null) {
  93706. body.addedToIsland = false;
  93707. if (body.sleeping) {
  93708. if (
  93709. body.linearVelocity.testZero() ||
  93710. body.angularVelocity.testZero() ||
  93711. body.position.testDiff(body.sleepPosition) ||
  93712. body.orientation.testDiff(body.sleepOrientation)
  93713. ) body.awake(); // awake the body
  93714. }
  93715. body = body.next;
  93716. }
  93717. //------------------------------------------------------
  93718. // UPDATE CONTACT
  93719. //------------------------------------------------------
  93720. // broad phase
  93721. if (stat) time1 = OIMO.now();
  93722. this.broadPhase.detectPairs();
  93723. var pairs = this.broadPhase.pairs;
  93724. var i = this.broadPhase.numPairs;
  93725. //do{
  93726. while (i--) {
  93727. //for(var i=0, l=numPairs; i<l; i++){
  93728. var pair = pairs[i];
  93729. var s1;
  93730. var s2;
  93731. if (pair.shape1.id < pair.shape2.id) {
  93732. s1 = pair.shape1;
  93733. s2 = pair.shape2;
  93734. } else {
  93735. s1 = pair.shape2;
  93736. s2 = pair.shape1;
  93737. }
  93738. var link;
  93739. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  93740. else link = s2.contactLink;
  93741. var exists = false;
  93742. while (link) {
  93743. var contact = link.contact;
  93744. if (contact.shape1 == s1 && contact.shape2 == s2) {
  93745. contact.persisting = true;
  93746. exists = true;// contact already exists
  93747. break;
  93748. }
  93749. link = link.next;
  93750. }
  93751. if (!exists) {
  93752. this.addContact(s1, s2);
  93753. }
  93754. }// while(i-- >0);
  93755. if (stat) {
  93756. time2 = OIMO.now();
  93757. this.performance.broadPhaseTime = time2 - time1;
  93758. }
  93759. // update & narrow phase
  93760. this.numContactPoints = 0;
  93761. contact = this.contacts;
  93762. while (contact !== null) {
  93763. if (!contact.persisting) {
  93764. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  93765. /*var aabb1=contact.shape1.aabb;
  93766. var aabb2=contact.shape2.aabb;
  93767. if(
  93768. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  93769. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  93770. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  93771. ){*/
  93772. var next = contact.next;
  93773. this.removeContact(contact);
  93774. contact = next;
  93775. continue;
  93776. }
  93777. }
  93778. var b1 = contact.body1;
  93779. var b2 = contact.body2;
  93780. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  93781. contact.updateManifold();
  93782. }
  93783. this.numContactPoints += contact.manifold.numPoints;
  93784. contact.persisting = false;
  93785. contact.constraint.addedToIsland = false;
  93786. contact = contact.next;
  93787. }
  93788. if (stat) {
  93789. time3 = OIMO.now();
  93790. this.performance.narrowPhaseTime = time3 - time2;
  93791. }
  93792. //------------------------------------------------------
  93793. // SOLVE ISLANDS
  93794. //------------------------------------------------------
  93795. var invTimeStep = 1 / this.timeStep;
  93796. //var body;
  93797. var joint;
  93798. var constraint;
  93799. //var num;
  93800. for (joint = this.joints; joint !== null; joint = joint.next) {
  93801. joint.addedToIsland = false;
  93802. }
  93803. // clear old island array
  93804. this.islandRigidBodies = [];
  93805. this.islandConstraints = [];
  93806. this.islandStack = [];
  93807. // expand island buffers
  93808. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  93809. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  93810. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  93811. this.islandRigidBodies=[];
  93812. this.islandStack=[];
  93813. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  93814. this.islandStack.length = this.maxIslandRigidBodies;
  93815. }
  93816. var numConstraints=this.numJoints+this.numContacts;
  93817. if(this.maxIslandConstraints<numConstraints){
  93818. this.maxIslandConstraints=numConstraints<<1;
  93819. //this.maxIslandConstraints=numConstraints*2;
  93820. this.islandConstraints=[];
  93821. this.islandConstraints.length = this.maxIslandConstraints;
  93822. }*/
  93823. time1 = OIMO.now();
  93824. this.numIslands = 0;
  93825. // build and solve simulation islands
  93826. for (var base = this.rigidBodies; base !== null; base = base.next) {
  93827. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  93828. if (base.isLonely()) {// update single body
  93829. if (base.isDynamic) {
  93830. base.linearVelocity.addTime(this.gravity, this.timeStep);
  93831. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  93832. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  93833. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  93834. }
  93835. if (this.callSleep(base)) {
  93836. base.sleepTime += this.timeStep;
  93837. if (base.sleepTime > 0.5) base.sleep();
  93838. else base.updatePosition(this.timeStep);
  93839. } else {
  93840. base.sleepTime = 0;
  93841. base.updatePosition(this.timeStep);
  93842. }
  93843. this.numIslands++;
  93844. continue;
  93845. }
  93846. var islandNumRigidBodies = 0;
  93847. var islandNumConstraints = 0;
  93848. var stackCount = 1;
  93849. // add rigid body to stack
  93850. this.islandStack[0] = base;
  93851. base.addedToIsland = true;
  93852. // build an island
  93853. do {
  93854. // get rigid body from stack
  93855. body = this.islandStack[--stackCount];
  93856. this.islandStack[stackCount] = null;
  93857. body.sleeping = false;
  93858. // add rigid body to the island
  93859. this.islandRigidBodies[islandNumRigidBodies++] = body;
  93860. if (body.isStatic) continue;
  93861. // search connections
  93862. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  93863. var contact = cs.contact;
  93864. constraint = contact.constraint;
  93865. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  93866. // add constraint to the island
  93867. this.islandConstraints[islandNumConstraints++] = constraint;
  93868. constraint.addedToIsland = true;
  93869. var next = cs.body;
  93870. if (next.addedToIsland) continue;
  93871. // add rigid body to stack
  93872. this.islandStack[stackCount++] = next;
  93873. next.addedToIsland = true;
  93874. }
  93875. for (var js = body.jointLink; js !== null; js = js.next) {
  93876. constraint = js.joint;
  93877. if (constraint.addedToIsland) continue;// ignore
  93878. // add constraint to the island
  93879. this.islandConstraints[islandNumConstraints++] = constraint;
  93880. constraint.addedToIsland = true;
  93881. next = js.body;
  93882. if (next.addedToIsland || !next.isDynamic) continue;
  93883. // add rigid body to stack
  93884. this.islandStack[stackCount++] = next;
  93885. next.addedToIsland = true;
  93886. }
  93887. } while (stackCount != 0);
  93888. // update velocities
  93889. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  93890. /*var gx=this.gravity.x*this.timeStep;
  93891. var gy=this.gravity.y*this.timeStep;
  93892. var gz=this.gravity.z*this.timeStep;*/
  93893. var j = islandNumRigidBodies;
  93894. while (j--) {
  93895. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  93896. body = this.islandRigidBodies[j];
  93897. if (body.isDynamic) {
  93898. body.linearVelocity.addEqual(gVel);
  93899. /*body.linearVelocity.x+=gx;
  93900. body.linearVelocity.y+=gy;
  93901. body.linearVelocity.z+=gz;*/
  93902. }
  93903. }
  93904. // randomizing order
  93905. if (this.enableRandomizer) {
  93906. //for(var j=1, l=islandNumConstraints; j<l; j++){
  93907. j = islandNumConstraints;
  93908. while (j--) {
  93909. if (j !== 0) {
  93910. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  93911. constraint = this.islandConstraints[j];
  93912. this.islandConstraints[j] = this.islandConstraints[swap];
  93913. this.islandConstraints[swap] = constraint;
  93914. }
  93915. }
  93916. }
  93917. // solve contraints
  93918. j = islandNumConstraints;
  93919. while (j--) {
  93920. //for(j=0, l=islandNumConstraints; j<l; j++){
  93921. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  93922. }
  93923. var k = this.numIterations;
  93924. while (k--) {
  93925. //for(var k=0, l=this.numIterations; k<l; k++){
  93926. j = islandNumConstraints;
  93927. while (j--) {
  93928. //for(j=0, m=islandNumConstraints; j<m; j++){
  93929. this.islandConstraints[j].solve();// main-solve
  93930. }
  93931. }
  93932. j = islandNumConstraints;
  93933. while (j--) {
  93934. //for(j=0, l=islandNumConstraints; j<l; j++){
  93935. this.islandConstraints[j].postSolve();// post-solve
  93936. this.islandConstraints[j] = null;// gc
  93937. }
  93938. // sleeping check
  93939. var sleepTime = 10;
  93940. j = islandNumRigidBodies;
  93941. while (j--) {
  93942. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93943. body = this.islandRigidBodies[j];
  93944. if (this.callSleep(body)) {
  93945. body.sleepTime += this.timeStep;
  93946. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  93947. } else {
  93948. body.sleepTime = 0;
  93949. sleepTime = 0;
  93950. continue;
  93951. }
  93952. }
  93953. if (sleepTime > 0.5) {
  93954. // sleep the island
  93955. j = islandNumRigidBodies;
  93956. while (j--) {
  93957. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93958. this.islandRigidBodies[j].sleep();
  93959. this.islandRigidBodies[j] = null;// gc
  93960. }
  93961. } else {
  93962. // update positions
  93963. j = islandNumRigidBodies;
  93964. while (j--) {
  93965. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93966. this.islandRigidBodies[j].updatePosition(this.timeStep);
  93967. this.islandRigidBodies[j] = null;// gc
  93968. }
  93969. }
  93970. this.numIslands++;
  93971. }
  93972. if (stat) {
  93973. time2 = OIMO.now();
  93974. this.performance.solvingTime = time2 - time1;
  93975. //------------------------------------------------------
  93976. // END SIMULATION
  93977. //------------------------------------------------------
  93978. time2 = OIMO.now();
  93979. // fps update
  93980. this.performance.upfps();
  93981. this.performance.totalTime = time2 - time0;
  93982. }
  93983. }
  93984. }
  93985. /**
  93986. * The class of rigid body.
  93987. * Rigid body has the shape of a single or multiple collision processing,
  93988. * I can set the parameters individually.
  93989. * @author saharan
  93990. */
  93991. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  93992. this.name = " ";
  93993. // The maximum number of shapes that can be added to a one rigid.
  93994. this.MAX_SHAPES = 64;//64;
  93995. this.prev = null;
  93996. this.next = null;
  93997. // I represent the kind of rigid body.
  93998. // Please do not change from the outside this variable.
  93999. // If you want to change the type of rigid body, always
  94000. // Please specify the type you want to set the arguments of setupMass method.
  94001. this.type = OIMO.BODY_NULL;
  94002. this.massInfo = new OIMO.MassInfo();
  94003. // It is the world coordinate of the center of gravity.
  94004. this.position = new OIMO.Vec3(x, y, z);
  94005. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  94006. this.newPosition = new OIMO.Vec3();
  94007. this.controlPos = false;
  94008. this.newOrientation = new OIMO.Quat();
  94009. this.newRotation = new OIMO.Vec3();
  94010. this.currentRotation = new OIMO.Vec3();
  94011. this.controlRot = false;
  94012. this.controlRotInTime = false;
  94013. // Is the translational velocity.
  94014. this.linearVelocity = new OIMO.Vec3();
  94015. // Is the angular velocity.
  94016. this.angularVelocity = new OIMO.Vec3();
  94017. // return matrix for three.js
  94018. this.matrix = new OIMO.Mat44();
  94019. //--------------------------------------------
  94020. // Please do not change from the outside this variables.
  94021. //--------------------------------------------
  94022. // It is a world that rigid body has been added.
  94023. this.parent = null;
  94024. this.contactLink = null;
  94025. this.numContacts = 0;
  94026. // An array of shapes that are included in the rigid body.
  94027. this.shapes = null;
  94028. // The number of shapes that are included in the rigid body.
  94029. this.numShapes = 0;
  94030. // It is the link array of joint that is connected to the rigid body.
  94031. this.jointLink = null;
  94032. // The number of joints that are connected to the rigid body.
  94033. this.numJoints = 0;
  94034. // It is the world coordinate of the center of gravity in the sleep just before.
  94035. this.sleepPosition = new OIMO.Vec3();
  94036. // It is a quaternion that represents the attitude of sleep just before.
  94037. this.sleepOrientation = new OIMO.Quat();
  94038. // I will show this rigid body to determine whether it is a rigid body static.
  94039. this.isStatic = false;
  94040. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  94041. this.isDynamic = false;
  94042. // It is a rotation matrix representing the orientation.
  94043. this.rotation = new OIMO.Mat33();
  94044. //--------------------------------------------
  94045. // It will be recalculated automatically from the shape, which is included.
  94046. //--------------------------------------------
  94047. // This is the weight.
  94048. this.mass = NaN;
  94049. // It is the reciprocal of the mass.
  94050. this.inverseMass = NaN;
  94051. // It is the inverse of the inertia tensor in the world system.
  94052. this.inverseInertia = new OIMO.Mat33();
  94053. // It is the inertia tensor in the initial state.
  94054. this.localInertia = new OIMO.Mat33();
  94055. // It is the inverse of the inertia tensor in the initial state.
  94056. this.inverseLocalInertia = new OIMO.Mat33();
  94057. // I indicates rigid body whether it has been added to the simulation Island.
  94058. this.addedToIsland = false;
  94059. // It shows how to sleep rigid body.
  94060. this.allowSleep = true;
  94061. // This is the time from when the rigid body at rest.
  94062. this.sleepTime = 0;
  94063. // I shows rigid body to determine whether it is a sleep state.
  94064. this.sleeping = false;
  94065. };
  94066. OIMO.RigidBody.prototype = {
  94067. constructor: OIMO.RigidBody,
  94068. /**
  94069. * I'll add a shape to rigid body.
  94070. * If you add a shape, please call the setupMass method to step up to the start of the next.
  94071. * @param shape shape to Add
  94072. */
  94073. addShape: function (shape) {
  94074. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  94075. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  94076. this.shapes = shape;
  94077. shape.parent = this;
  94078. if (this.parent) this.parent.addShape(shape);
  94079. this.numShapes++;
  94080. },
  94081. /**
  94082. * I will delete the shape from the rigid body.
  94083. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  94084. * @param shape shape to Delete
  94085. */
  94086. removeShape: function (shape) {
  94087. var remove = shape;
  94088. if (remove.parent != this) return;
  94089. var prev = remove.prev;
  94090. var next = remove.next;
  94091. if (prev != null) prev.next = next;
  94092. if (next != null) next.prev = prev;
  94093. if (this.shapes == remove) this.shapes = next;
  94094. remove.prev = null;
  94095. remove.next = null;
  94096. remove.parent = null;
  94097. if (this.parent) this.parent.removeShape(remove);
  94098. this.numShapes--;
  94099. },
  94100. remove: function () {
  94101. this.dispose();
  94102. },
  94103. dispose: function () {
  94104. this.parent.removeRigidBody(this);
  94105. },
  94106. checkContact: function (name) {
  94107. this.parent.checkContact(this.name, name);
  94108. },
  94109. /**
  94110. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  94111. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  94112. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  94113. * the rigid body's position will be adjusted to the center of gravity.
  94114. * @param type
  94115. * @param adjustPosition
  94116. */
  94117. setupMass: function (type, AdjustPosition) {
  94118. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  94119. this.type = type || OIMO.BODY_DYNAMIC;
  94120. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  94121. this.isStatic = this.type == OIMO.BODY_STATIC;
  94122. this.mass = 0;
  94123. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  94124. var te = this.localInertia.elements;
  94125. //
  94126. var tmpM = new OIMO.Mat33();
  94127. var tmpV = new OIMO.Vec3();
  94128. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94129. shape.calculateMassInfo(this.massInfo);
  94130. var shapeMass = this.massInfo.mass;
  94131. var relX = shape.relativePosition.x;
  94132. var relY = shape.relativePosition.y;
  94133. var relZ = shape.relativePosition.z;
  94134. /*tmpV.x+=relX*shapeMass;
  94135. tmpV.y+=relY*shapeMass;
  94136. tmpV.z+=relZ*shapeMass;*/
  94137. tmpV.addScale(shape.relativePosition, shapeMass);
  94138. this.mass += shapeMass;
  94139. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  94140. this.localInertia.addEqual(tmpM);
  94141. // add offset inertia
  94142. te[0] += shapeMass * (relY * relY + relZ * relZ);
  94143. te[4] += shapeMass * (relX * relX + relZ * relZ);
  94144. te[8] += shapeMass * (relX * relX + relY * relY);
  94145. var xy = shapeMass * relX * relY;
  94146. var yz = shapeMass * relY * relZ;
  94147. var zx = shapeMass * relZ * relX;
  94148. te[1] -= xy;
  94149. te[3] -= xy;
  94150. te[2] -= yz;
  94151. te[6] -= yz;
  94152. te[5] -= zx;
  94153. te[7] -= zx;
  94154. }
  94155. this.inverseMass = 1 / this.mass;
  94156. tmpV.scaleEqual(this.inverseMass);
  94157. if (adjustPosition) {
  94158. this.position.addEqual(tmpV);
  94159. for (shape = this.shapes; shape != null; shape = shape.next) {
  94160. shape.relativePosition.subEqual(tmpV);
  94161. }
  94162. // subtract offset inertia
  94163. relX = tmpV.x;
  94164. relY = tmpV.y;
  94165. relZ = tmpV.z;
  94166. //var te = this.localInertia.elements;
  94167. te[0] -= this.mass * (relY * relY + relZ * relZ);
  94168. te[4] -= this.mass * (relX * relX + relZ * relZ);
  94169. te[8] -= this.mass * (relX * relX + relY * relY);
  94170. xy = this.mass * relX * relY;
  94171. yz = this.mass * relY * relZ;
  94172. zx = this.mass * relZ * relX;
  94173. te[1] += xy;
  94174. te[3] += xy;
  94175. te[2] += yz;
  94176. te[6] += yz;
  94177. te[5] += zx;
  94178. te[7] += zx;
  94179. }
  94180. this.inverseLocalInertia.invert(this.localInertia);
  94181. if (this.type == OIMO.BODY_STATIC) {
  94182. this.inverseMass = 0;
  94183. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  94184. }
  94185. this.syncShapes();
  94186. this.awake();
  94187. },
  94188. /**
  94189. * Awake the rigid body.
  94190. */
  94191. awake: function () {
  94192. if (!this.allowSleep || !this.sleeping) return;
  94193. this.sleeping = false;
  94194. this.sleepTime = 0;
  94195. // awake connected constraints
  94196. var cs = this.contactLink;
  94197. while (cs != null) {
  94198. cs.body.sleepTime = 0;
  94199. cs.body.sleeping = false;
  94200. cs = cs.next;
  94201. }
  94202. var js = this.jointLink;
  94203. while (js != null) {
  94204. js.body.sleepTime = 0;
  94205. js.body.sleeping = false;
  94206. js = js.next;
  94207. }
  94208. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94209. shape.updateProxy();
  94210. }
  94211. },
  94212. /**
  94213. * Sleep the rigid body.
  94214. */
  94215. sleep: function () {
  94216. if (!this.allowSleep || this.sleeping) return;
  94217. this.linearVelocity.set(0, 0, 0);
  94218. this.angularVelocity.set(0, 0, 0);
  94219. this.sleepPosition.copy(this.position);
  94220. this.sleepOrientation.copy(this.orientation);
  94221. /*this.linearVelocity.x=0;
  94222. this.linearVelocity.y=0;
  94223. this.linearVelocity.z=0;
  94224. this.angularVelocity.x=0;
  94225. this.angularVelocity.y=0;
  94226. this.angularVelocity.z=0;
  94227. this.sleepPosition.x=this.position.x;
  94228. this.sleepPosition.y=this.position.y;
  94229. this.sleepPosition.z=this.position.z;*/
  94230. /*this.sleepOrientation.s=this.orientation.s;
  94231. this.sleepOrientation.x=this.orientation.x;
  94232. this.sleepOrientation.y=this.orientation.y;
  94233. this.sleepOrientation.z=this.orientation.z;*/
  94234. this.sleepTime = 0;
  94235. this.sleeping = true;
  94236. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94237. shape.updateProxy();
  94238. }
  94239. },
  94240. /**
  94241. * Get whether the rigid body has not any connection with others.
  94242. * @return
  94243. */
  94244. isLonely: function () {
  94245. return this.numJoints == 0 && this.numContacts == 0;
  94246. },
  94247. /**
  94248. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  94249. * This method is invoked automatically when calling the step of the World,
  94250. * There is no need to call from outside usually.
  94251. * @param timeStep time
  94252. */
  94253. updatePosition: function (timeStep) {
  94254. switch (this.type) {
  94255. case OIMO.BODY_STATIC:
  94256. this.linearVelocity.set(0, 0, 0);
  94257. this.angularVelocity.set(0, 0, 0);
  94258. // ONLY FOR TEST
  94259. if (this.controlPos) {
  94260. this.position.copy(this.newPosition);
  94261. this.controlPos = false;
  94262. }
  94263. if (this.controlRot) {
  94264. this.orientation.copy(this.newOrientation);
  94265. this.controlRot = false;
  94266. }
  94267. /*this.linearVelocity.x=0;
  94268. this.linearVelocity.y=0;
  94269. this.linearVelocity.z=0;
  94270. this.angularVelocity.x=0;
  94271. this.angularVelocity.y=0;
  94272. this.angularVelocity.z=0;*/
  94273. break;
  94274. case OIMO.BODY_DYNAMIC:
  94275. if (this.controlPos) {
  94276. this.angularVelocity.set(0, 0, 0);
  94277. this.linearVelocity.set(0, 0, 0);
  94278. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  94279. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  94280. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  94281. this.controlPos = false;
  94282. }
  94283. if (this.controlRot) {
  94284. this.angularVelocity.set(0, 0, 0);
  94285. this.orientation.copy(this.newOrientation);
  94286. //var t=timeStep//*0.5;
  94287. //var q = new OIMO.Quat();
  94288. //q.sub(this.newOrientation, this.orientation);
  94289. //q.normalize(q);
  94290. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  94291. q.x = (this.newOrientation.x - this.orientation.x)/t;
  94292. q.y = (this.newOrientation.y - this.orientation.y)/t;
  94293. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  94294. //this.angularVelocity.applyQuaternion(q);
  94295. //this.angularVelocity.x = this.angularVelocity.x/t;
  94296. //this.angularVelocity.y = this.angularVelocity.y/t;
  94297. //this.angularVelocity.z = this.angularVelocity.z/t;
  94298. this.controlRot = false;
  94299. }
  94300. this.position.addTime(this.linearVelocity, timeStep);
  94301. this.orientation.addTime(this.angularVelocity, timeStep);
  94302. break;
  94303. default: OIMO.Error("RigidBody", "Invalid type.");
  94304. }
  94305. this.syncShapes();
  94306. },
  94307. rotateInertia: function (rot, inertia, out) {
  94308. var tm1 = rot.elements;
  94309. var tm2 = inertia.elements;
  94310. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  94311. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  94312. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  94313. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  94314. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  94315. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  94316. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  94317. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  94318. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  94319. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  94320. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  94321. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  94322. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  94323. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  94324. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  94325. var oe = out.elements;
  94326. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  94327. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  94328. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  94329. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  94330. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  94331. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  94332. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  94333. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  94334. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  94335. },
  94336. syncShapes: function () {
  94337. var s = this.orientation.s;
  94338. var x = this.orientation.x;
  94339. var y = this.orientation.y;
  94340. var z = this.orientation.z;
  94341. var x2 = 2 * x;
  94342. var y2 = 2 * y;
  94343. var z2 = 2 * z;
  94344. var xx = x * x2;
  94345. var yy = y * y2;
  94346. var zz = z * z2;
  94347. var xy = x * y2;
  94348. var yz = y * z2;
  94349. var xz = x * z2;
  94350. var sx = s * x2;
  94351. var sy = s * y2;
  94352. var sz = s * z2;
  94353. var tr = this.rotation.elements;
  94354. tr[0] = 1 - yy - zz;
  94355. tr[1] = xy - sz;
  94356. tr[2] = xz + sy;
  94357. tr[3] = xy + sz;
  94358. tr[4] = 1 - xx - zz;
  94359. tr[5] = yz - sx;
  94360. tr[6] = xz - sy;
  94361. tr[7] = yz + sx;
  94362. tr[8] = 1 - xx - yy;
  94363. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  94364. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94365. //var relPos=shape.relativePosition;
  94366. //var relRot=shape.relativeRotation;
  94367. //var rot=shape.rotation;
  94368. /*var lx=relPos.x;
  94369. var ly=relPos.y;
  94370. var lz=relPos.z;
  94371. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  94372. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  94373. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  94374. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  94375. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  94376. // add by QuaziKb
  94377. shape.rotation.mul(this.rotation, shape.relativeRotation);
  94378. shape.updateProxy();
  94379. }
  94380. },
  94381. applyImpulse: function (position, force) {
  94382. this.linearVelocity.addScale(force, this.inverseMass);
  94383. /*this.linearVelocity.x+=force.x*this.inverseMass;
  94384. this.linearVelocity.y+=force.y*this.inverseMass;
  94385. this.linearVelocity.z+=force.z*this.inverseMass;*/
  94386. var rel = new OIMO.Vec3();
  94387. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  94388. this.angularVelocity.addEqual(rel);
  94389. /*this.angularVelocity.x+=rel.x;
  94390. this.angularVelocity.y+=rel.y;
  94391. this.angularVelocity.z+=rel.z;*/
  94392. },
  94393. //---------------------------------------------
  94394. //
  94395. // FOR THREE JS
  94396. //
  94397. //---------------------------------------------
  94398. rotationVectToQuad: function (rot) {
  94399. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  94400. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  94401. },
  94402. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  94403. var len = ax * ax + ay * ay + az * az;
  94404. if (len > 0) {
  94405. len = 1 / OIMO.sqrt(len);
  94406. ax *= len;
  94407. ay *= len;
  94408. az *= len;
  94409. }
  94410. var sin = OIMO.sin(rad * 0.5);
  94411. var cos = OIMO.cos(rad * 0.5);
  94412. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  94413. },
  94414. //---------------------------------------------
  94415. // SET DYNAMIQUE POSITION AND ROTATION
  94416. //---------------------------------------------
  94417. setPosition: function (pos) {
  94418. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  94419. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  94420. this.controlPos = true;
  94421. },
  94422. setQuaternion: function (q) {
  94423. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  94424. this.newOrientation.set(q.x, q.y, q.z, q.w);
  94425. this.controlRot = true;
  94426. },
  94427. setRotation: function (rot) {
  94428. this.newOrientation = this.rotationVectToQuad(rot);
  94429. this.controlRot = true;
  94430. },
  94431. //---------------------------------------------
  94432. // RESET DYNAMIQUE POSITION AND ROTATION
  94433. //---------------------------------------------
  94434. resetPosition: function (x, y, z) {
  94435. this.linearVelocity.set(0, 0, 0);
  94436. this.angularVelocity.set(0, 0, 0);
  94437. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  94438. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  94439. this.awake();
  94440. },
  94441. resetQuaternion: function (q) {
  94442. this.angularVelocity.set(0, 0, 0);
  94443. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  94444. this.awake();
  94445. },
  94446. resetRotation: function (x, y, z) {
  94447. this.angularVelocity.set(0, 0, 0);
  94448. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  94449. this.awake();
  94450. },
  94451. //---------------------------------------------
  94452. // GET POSITION AND ROTATION
  94453. //---------------------------------------------
  94454. getPosition: function () {
  94455. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  94456. },
  94457. getRotation: function () {
  94458. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  94459. },
  94460. getQuaternion: function () {
  94461. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  94462. },
  94463. getMatrix: function () {
  94464. var m = this.matrix.elements;
  94465. var r, p;
  94466. if (!this.sleeping) {
  94467. // rotation matrix
  94468. r = this.rotation.elements;
  94469. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  94470. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  94471. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  94472. // position matrix
  94473. p = this.position;
  94474. m[12] = p.x * OIMO.WORLD_SCALE;
  94475. m[13] = p.y * OIMO.WORLD_SCALE;
  94476. m[14] = p.z * OIMO.WORLD_SCALE;
  94477. // sleep or not ?
  94478. m[15] = 0;
  94479. } else {
  94480. m[15] = 1;
  94481. }
  94482. return m;
  94483. }
  94484. };
  94485. /**
  94486. * The main class of body.
  94487. * is for simplify creation process and data access of rigidRody
  94488. * Rigid body has the shape of a single or multiple collision processing,
  94489. * all setting in object
  94490. *
  94491. * @author loth
  94492. */
  94493. OIMO.Body = function (Obj) {
  94494. var obj = Obj || {};
  94495. if (!obj.world) return;
  94496. if (obj.type === undefined) obj.type = "box";
  94497. this.name = obj.name || '';
  94498. // obsolete use world.add(obj)
  94499. this.body = obj.world.add(obj);
  94500. /*
  94501. // the world where i am
  94502. this.parent = obj.world;
  94503. // Yep my name
  94504. this.name = obj.name || '';
  94505. // I'm dynamique or not
  94506. var move = obj.move || false;
  94507. // I can sleep or not
  94508. var noSleep = obj.noSleep || false;
  94509. // My start position
  94510. var p = obj.pos || [0,0,0];
  94511. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  94512. // My size
  94513. var s = obj.size || [1,1,1];
  94514. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  94515. // My rotation in degre
  94516. var rot = obj.rot || [0,0,0];
  94517. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  94518. var r = [];
  94519. for (var i=0; i<rot.length/3; i++){
  94520. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  94521. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  94522. }
  94523. // My physics setting
  94524. var sc = obj.sc || new OIMO.ShapeConfig();
  94525. if(obj.config){
  94526. // The density of the shape.
  94527. sc.density = obj.config[0] || 1;
  94528. // The coefficient of friction of the shape.
  94529. sc.friction = obj.config[1] || 0.4;
  94530. // The coefficient of restitution of the shape.
  94531. sc.restitution = obj.config[2] || 0.2;
  94532. // The bits of the collision groups to which the shape belongs.
  94533. sc.belongsTo = obj.config[3] || 1;
  94534. // The bits of the collision groups with which the shape collides.
  94535. sc.collidesWith = obj.config[4] || 0xffffffff;
  94536. }
  94537. if(obj.massPos){
  94538. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  94539. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  94540. }
  94541. if(obj.massRot){
  94542. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  94543. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  94544. }
  94545. // My rigidbody
  94546. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  94547. // My shapes
  94548. var shapes = [];
  94549. var type = obj.type || "box";
  94550. if( typeof type === 'string' ) type = [type];// single shape
  94551. var n, n2;
  94552. for(var i=0; i<type.length; i++){
  94553. n = i*3;
  94554. n2 = i*4;
  94555. switch(type[i]){
  94556. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  94557. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  94558. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  94559. }
  94560. this.body.addShape(shapes[i]);
  94561. if(i>0){
  94562. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  94563. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  94564. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  94565. }
  94566. }
  94567. // I'm static or i move
  94568. if(move){
  94569. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  94570. else this.body.setupMass(0x1, true);
  94571. if(noSleep) this.body.allowSleep = false;
  94572. else this.body.allowSleep = true;
  94573. } else {
  94574. this.body.setupMass(0x2);
  94575. }
  94576. this.body.name = this.name;
  94577. this.sleeping = this.body.sleeping;
  94578. // finaly add to physics world
  94579. this.parent.addRigidBody(this.body);*/
  94580. }
  94581. OIMO.Body.prototype = {
  94582. constructor: OIMO.Body,
  94583. // SET
  94584. setPosition: function (pos) {
  94585. this.body.setPosition(pos);
  94586. },
  94587. setQuaternion: function (q) {
  94588. this.body.setQuaternion(q);
  94589. },
  94590. setRotation: function (rot) {
  94591. this.body.setRotation(rot);
  94592. },
  94593. // GET
  94594. getPosition: function () {
  94595. return this.body.getPosition();
  94596. },
  94597. getRotation: function () {
  94598. return this.body.getRotation();
  94599. },
  94600. getQuaternion: function () {
  94601. return this.body.getQuaternion();
  94602. },
  94603. getMatrix: function () {
  94604. return this.body.getMatrix();
  94605. },
  94606. getSleep: function () {
  94607. return this.body.sleeping;
  94608. },
  94609. // RESET
  94610. resetPosition: function (x, y, z) {
  94611. this.body.resetPosition(x, y, z);
  94612. },
  94613. resetRotation: function (x, y, z) {
  94614. this.body.resetRotation(x, y, z);
  94615. },
  94616. // force wakeup
  94617. awake: function () {
  94618. this.body.awake();
  94619. },
  94620. // remove rigidbody
  94621. remove: function () {
  94622. this.body.dispose();
  94623. //this.parent.removeRigidBody(this.body);
  94624. },
  94625. // test if this object hit another
  94626. checkContact: function (name) {
  94627. this.body.checkContact(name);
  94628. //this.parent.checkContact(this.name, name);
  94629. }
  94630. }
  94631. /**
  94632. * The main class of link.
  94633. * is for simplify creation process and data access of Joint
  94634. * all setting in object
  94635. *
  94636. * @author loth
  94637. */
  94638. OIMO.Link = function (Obj) {
  94639. var obj = Obj || {};
  94640. if (!obj.world) return;
  94641. if (obj.type === undefined) obj.type = "jointHinge";
  94642. this.name = obj.name || '';
  94643. // obsolete use world.add(obj)
  94644. this.joint = obj.world.add(obj);
  94645. // the world where i am
  94646. /*this.parent = obj.world;
  94647. this.name = obj.name || '';
  94648. var type = obj.type || "jointHinge";
  94649. var axe1 = obj.axe1 || [1,0,0];
  94650. var axe2 = obj.axe2 || [1,0,0];
  94651. var pos1 = obj.pos1 || [0,0,0];
  94652. var pos2 = obj.pos2 || [0,0,0];
  94653. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  94654. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  94655. var min, max;
  94656. if(type==="jointDistance"){
  94657. min = obj.min || 0;
  94658. max = obj.max || 10;
  94659. min = min*OIMO.INV_SCALE;
  94660. max = max*OIMO.INV_SCALE;
  94661. }else{
  94662. min = obj.min || 57.29578;
  94663. max = obj.max || 0;
  94664. min = min*OIMO.TO_RAD;
  94665. max = max*OIMO.TO_RAD;
  94666. }
  94667. var limit = obj.limit || null;
  94668. var spring = obj.spring || null;
  94669. var motor = obj.motor || null;
  94670. // joint setting
  94671. var jc = new OIMO.JointConfig();
  94672. jc.allowCollision = obj.collision || false;;
  94673. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  94674. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  94675. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  94676. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  94677. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  94678. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  94679. jc.body1 = obj.body1;
  94680. jc.body2 = obj.body2;
  94681. switch(type){
  94682. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  94683. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  94684. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  94685. break;
  94686. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  94687. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  94688. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  94689. break;
  94690. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  94691. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  94692. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  94693. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  94694. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  94695. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  94696. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  94697. break;
  94698. }
  94699. this.joint.name = this.name;
  94700. // finaly add to physics world
  94701. this.parent.addJoint(this.joint);*/
  94702. }
  94703. OIMO.Link.prototype = {
  94704. constructor: OIMO.Link,
  94705. getPosition: function () {
  94706. // array of two vect3 [point1, point2]
  94707. return this.joint.getPosition();
  94708. },
  94709. getMatrix: function () {
  94710. return this.joint.getMatrix();
  94711. },
  94712. // remove joint
  94713. remove: function () {
  94714. this.joint.dispose();
  94715. //this.parent.removeJoint(this.joint);
  94716. },
  94717. // force wakeup linked body
  94718. awake: function () {
  94719. this.joint.awake();
  94720. }
  94721. }
  94722. /**
  94723. * The Dictionary class for testing
  94724. * @author lo-th
  94725. */
  94726. OIMO.Dictionary = function () {
  94727. this.data = {};
  94728. this.keys = [];
  94729. };
  94730. OIMO.Dictionary.prototype = {
  94731. constructor: OIMO.Dictionary,
  94732. set: function (value) {
  94733. var key = value.id;
  94734. if (!this.get[key]) this.keys.push(key);
  94735. this.data[key] = value;
  94736. },
  94737. get: function (id) {
  94738. return this.data[id];
  94739. },
  94740. del: function (value) {
  94741. var k = this.keys;
  94742. var n = k.indexOf(value.id);
  94743. if (n > -1) {
  94744. delete this.data[k[n]];
  94745. k.splice(n, 1);
  94746. }
  94747. },
  94748. reset: function () {
  94749. var data = this.data, keys = this.keys, key;
  94750. while (keys.length > 0) {
  94751. key = keys.pop();
  94752. delete data[key];
  94753. }
  94754. }
  94755. };
  94756. OIMO.Performance = function (world) {
  94757. this.parent = world;
  94758. this.infos = new OIMO_ARRAY_TYPE(13);
  94759. this.f = [0, 0, 0];
  94760. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  94761. this.broadPhase = this.types[this.parent.broadPhase.types];
  94762. this.version = OIMO.REVISION;
  94763. this.fps = 0;
  94764. this.broadPhaseTime = 0;
  94765. this.narrowPhaseTime = 0;
  94766. this.solvingTime = 0;
  94767. //this.updatingTime = 0;
  94768. this.totalTime = 0;
  94769. };
  94770. OIMO.Performance.prototype = {
  94771. upfps: function () {
  94772. this.f[1] = Date.now();
  94773. if (this.f[1] - 1000 > this.f[0]) { this.f[0] = this.f[1]; this.fps = this.f[2]; this.f[2] = 0; } this.f[2]++;
  94774. },
  94775. updatingTime: function () {
  94776. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  94777. },
  94778. show: function () {
  94779. var info = [
  94780. "Oimo.js " + this.version + "<br>",
  94781. this.broadPhase + "<br><br>",
  94782. "FPS: " + this.fps + " fps<br><br>",
  94783. "rigidbody " + this.parent.numRigidBodies + "<br>",
  94784. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  94785. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  94786. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  94787. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  94788. "Time in milliseconde<br><br>",
  94789. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  94790. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  94791. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  94792. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  94793. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  94794. ].join("\n");
  94795. return info;
  94796. },
  94797. toArray: function () {
  94798. this.infos[0] = this.parent.broadPhase.types;
  94799. this.infos[1] = this.parent.numRigidBodies;
  94800. this.infos[2] = this.parent.numContacts;
  94801. this.infos[3] = this.parent.broadPhase.numPairChecks;
  94802. this.infos[4] = this.parent.numContactPoints;
  94803. this.infos[5] = this.parent.numIslands;
  94804. this.infos[6] = this.broadPhaseTime;
  94805. this.infos[7] = this.narrowPhaseTime;
  94806. this.infos[8] = this.solvingTime;
  94807. this.infos[9] = this.updatingTime();
  94808. this.infos[10] = this.totalTime;
  94809. this.infos[11] = this.fps;
  94810. return this.infos;
  94811. }
  94812. };
  94813. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94814. this.elements = new OIMO_ARRAY_TYPE(16);
  94815. var te = this.elements;
  94816. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  94817. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  94818. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  94819. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  94820. };
  94821. OIMO.Mat44.prototype = {
  94822. constructor: OIMO.Mat44,
  94823. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94824. var te = this.elements;
  94825. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  94826. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  94827. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  94828. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  94829. return this;
  94830. }/*,
  94831. extractRotation: function () {
  94832. var v1 = new THREE.Vector3();
  94833. return function ( m ) {
  94834. var te = this.elements;
  94835. var me = m.elements;
  94836. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  94837. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  94838. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  94839. te[ 0 ] = me[ 0 ] * scaleX;
  94840. te[ 1 ] = me[ 1 ] * scaleX;
  94841. te[ 2 ] = me[ 2 ] * scaleX;
  94842. te[ 4 ] = me[ 4 ] * scaleY;
  94843. te[ 5 ] = me[ 5 ] * scaleY;
  94844. te[ 6 ] = me[ 6 ] * scaleY;
  94845. te[ 8 ] = me[ 8 ] * scaleZ;
  94846. te[ 9 ] = me[ 9 ] * scaleZ;
  94847. te[ 10 ] = me[ 10 ] * scaleZ;
  94848. return this;
  94849. };
  94850. }() */
  94851. }
  94852. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94853. this.elements = new OIMO_ARRAY_TYPE(9);
  94854. var te = this.elements;
  94855. this.init(
  94856. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  94857. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  94858. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  94859. );
  94860. };
  94861. OIMO.Mat33.prototype = {
  94862. constructor: OIMO.Mat33,
  94863. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94864. var te = this.elements;
  94865. te[0] = e00; te[1] = e01; te[2] = e02;
  94866. te[3] = e10; te[4] = e11; te[5] = e12;
  94867. te[6] = e20; te[7] = e21; te[8] = e22;
  94868. return this;
  94869. },
  94870. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94871. var te = this.elements;
  94872. te[0] = e00; te[1] = e01; te[2] = e02;
  94873. te[3] = e10; te[4] = e11; te[5] = e12;
  94874. te[6] = e20; te[7] = e21; te[8] = e22;
  94875. return this;
  94876. },
  94877. multiply: function (s) {
  94878. var te = this.elements;
  94879. te[0] *= s; te[1] *= s; te[2] *= s;
  94880. te[3] *= s; te[4] *= s; te[5] *= s;
  94881. te[6] *= s; te[7] *= s; te[8] *= s;
  94882. return this;
  94883. },
  94884. add: function (m1, m2) {
  94885. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94886. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  94887. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  94888. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  94889. return this;
  94890. },
  94891. addEqual: function (m) {
  94892. var te = this.elements, tem = m.elements;
  94893. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  94894. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  94895. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  94896. return this;
  94897. },
  94898. sub: function (m1, m2) {
  94899. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94900. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  94901. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  94902. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  94903. return this;
  94904. },
  94905. subEqual: function (m) {
  94906. var te = this.elements, tem = m.elements;
  94907. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  94908. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  94909. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  94910. return this;
  94911. },
  94912. scale: function (m, s) {
  94913. var te = this.elements, tm = m.elements;
  94914. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  94915. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  94916. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  94917. return this;
  94918. },
  94919. scaleEqual: function (s) {
  94920. var te = this.elements;
  94921. te[0] *= s; te[1] *= s; te[2] *= s;
  94922. te[3] *= s; te[4] *= s; te[5] *= s;
  94923. te[6] *= s; te[7] *= s; te[8] *= s;
  94924. return this;
  94925. },
  94926. mul: function (m1, m2) {
  94927. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  94928. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  94929. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  94930. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  94931. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  94932. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  94933. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  94934. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  94935. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  94936. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  94937. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  94938. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  94939. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  94940. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  94941. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  94942. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  94943. return this;
  94944. },
  94945. mulScale: function (m, sx, sy, sz, Prepend) {
  94946. var prepend = Prepend || false;
  94947. var te = this.elements, tm = m.elements;
  94948. if (prepend) {
  94949. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  94950. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  94951. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  94952. } else {
  94953. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  94954. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  94955. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  94956. }
  94957. return this;
  94958. },
  94959. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  94960. var prepend = Prepend || false;
  94961. var s = OIMO.sin(rad);
  94962. var c = OIMO.cos(rad);
  94963. var c1 = 1 - c;
  94964. var r00 = ax * ax * c1 + c;
  94965. var r01 = ax * ay * c1 - az * s;
  94966. var r02 = ax * az * c1 + ay * s;
  94967. var r10 = ay * ax * c1 + az * s;
  94968. var r11 = ay * ay * c1 + c;
  94969. var r12 = ay * az * c1 - ax * s;
  94970. var r20 = az * ax * c1 - ay * s;
  94971. var r21 = az * ay * c1 + ax * s;
  94972. var r22 = az * az * c1 + c;
  94973. var tm = m.elements;
  94974. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  94975. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  94976. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  94977. var te = this.elements;
  94978. if (prepend) {
  94979. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  94980. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  94981. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  94982. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  94983. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  94984. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  94985. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  94986. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  94987. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  94988. } else {
  94989. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  94990. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  94991. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  94992. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  94993. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  94994. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  94995. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  94996. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  94997. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  94998. }
  94999. return this;
  95000. },
  95001. transpose: function (m) {
  95002. var te = this.elements, tm = m.elements;
  95003. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  95004. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  95005. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  95006. return this;
  95007. },
  95008. setQuat: function (q) {
  95009. var te = this.elements,
  95010. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  95011. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  95012. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  95013. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  95014. te[0] = 1 - yy - zz;
  95015. te[1] = xy - sz;
  95016. te[2] = xz + sy;
  95017. te[3] = xy + sz;
  95018. te[4] = 1 - xx - zz;
  95019. te[5] = yz - sx;
  95020. te[6] = xz - sy;
  95021. te[7] = yz + sx;
  95022. te[8] = 1 - xx - yy;
  95023. return this;
  95024. },
  95025. invert: function (m) {
  95026. var te = this.elements, tm = m.elements,
  95027. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  95028. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  95029. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  95030. b01 = a4 * a8 - a7 * a5,
  95031. b11 = a7 * a2 - a1 * a8,
  95032. b21 = a1 * a5 - a4 * a2,
  95033. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  95034. if (dt != 0) { dt = 1.0 / dt; }
  95035. te[0] = dt * b01;//(a4*a8 - a5*a7);
  95036. te[1] = dt * b11;//(a2*a7 - a1*a8);
  95037. te[2] = dt * b21;//(a1*a5 - a2*a4);
  95038. te[3] = dt * (a5 * a6 - a3 * a8);
  95039. te[4] = dt * (a0 * a8 - a2 * a6);
  95040. te[5] = dt * (a2 * a3 - a0 * a5);
  95041. te[6] = dt * (a3 * a7 - a4 * a6);
  95042. te[7] = dt * (a1 * a6 - a0 * a7);
  95043. te[8] = dt * (a0 * a4 - a1 * a3);
  95044. return this;
  95045. },
  95046. /*copy: function(m){
  95047. var te = this.elements, tem = m.elements;
  95048. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  95049. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  95050. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  95051. return this;
  95052. },*/
  95053. toEuler: function () { // not work !!
  95054. function clamp(x) {
  95055. return OIMO.min(OIMO.max(x, -1), 1);
  95056. }
  95057. var te = this.elements;
  95058. var m11 = te[0], m12 = te[3], m13 = te[6];
  95059. var m21 = te[1], m22 = te[4], m23 = te[7];
  95060. var m31 = te[2], m32 = te[5], m33 = te[8];
  95061. var p = new OIMO.Vec3();
  95062. var d = new OIMO.Quat();
  95063. var s;
  95064. p.y = OIMO.asin(clamp(m13));
  95065. if (OIMO.abs(m13) < 0.99999) {
  95066. p.x = OIMO.atan2(-m23, m33);
  95067. p.z = OIMO.atan2(-m12, m11);
  95068. } else {
  95069. p.x = OIMO.atan2(m32, m22);
  95070. p.z = 0;
  95071. }
  95072. return p;
  95073. },
  95074. /*clone: function(){
  95075. var te = this.elements;
  95076. return new OIMO.Mat33(
  95077. te[0], te[1], te[2],
  95078. te[3], te[4], te[5],
  95079. te[6], te[7], te[8]
  95080. );
  95081. },*/
  95082. toString: function () {
  95083. var te = this.elements;
  95084. var text =
  95085. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  95086. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  95087. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  95088. return text;
  95089. },
  95090. // OK
  95091. multiplyScalar: function (s) {
  95092. var te = this.elements;
  95093. te[0] *= s; te[3] *= s; te[6] *= s;
  95094. te[1] *= s; te[4] *= s; te[7] *= s;
  95095. te[2] *= s; te[5] *= s; te[8] *= s;
  95096. return this;
  95097. },
  95098. identity: function () {
  95099. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  95100. return this;
  95101. },
  95102. clone: function () {
  95103. return new this.constructor().fromArray(this.elements);
  95104. },
  95105. copy: function (m) {
  95106. var me = m.elements;
  95107. this.set(
  95108. me[0], me[3], me[6],
  95109. me[1], me[4], me[7],
  95110. me[2], me[5], me[8]
  95111. );
  95112. return this;
  95113. },
  95114. fromArray: function (array) {
  95115. this.elements.set(array);
  95116. return this;
  95117. },
  95118. toArray: function () {
  95119. var te = this.elements;
  95120. return [
  95121. te[0], te[1], te[2],
  95122. te[3], te[4], te[5],
  95123. te[6], te[7], te[8]
  95124. ];
  95125. }
  95126. };
  95127. OIMO.Quat = function (s, x, y, z) {
  95128. this.s = (s !== undefined) ? s : 1;
  95129. this.x = x || 0;
  95130. this.y = y || 0;
  95131. this.z = z || 0;
  95132. };
  95133. OIMO.Quat.prototype = {
  95134. constructor: OIMO.Quat,
  95135. set: function (x, y, z, w) {
  95136. this.x = x;
  95137. this.y = y;
  95138. this.z = z;
  95139. this.s = w;
  95140. return this;
  95141. },
  95142. init: function (s, x, y, z) {
  95143. this.s = (s !== undefined) ? s : 1;
  95144. this.x = x || 0;
  95145. this.y = y || 0;
  95146. this.z = z || 0;
  95147. return this;
  95148. },
  95149. add: function (q1, q2) {
  95150. this.s = q1.s + q2.s;
  95151. this.x = q1.x + q2.x;
  95152. this.y = q1.y + q2.y;
  95153. this.z = q1.z + q2.z;
  95154. return this;
  95155. },
  95156. addTime: function (v, t) {
  95157. var x = v.x;
  95158. var y = v.y;
  95159. var z = v.z;
  95160. var qs = this.s;
  95161. var qx = this.x;
  95162. var qy = this.y;
  95163. var qz = this.z;
  95164. t *= 0.5;
  95165. var ns = (-x * qx - y * qy - z * qz) * t;
  95166. var nx = (x * qs + y * qz - z * qy) * t;
  95167. var ny = (-x * qz + y * qs + z * qx) * t;
  95168. var nz = (x * qy - y * qx + z * qs) * t;
  95169. qs += ns;
  95170. qx += nx;
  95171. qy += ny;
  95172. qz += nz;
  95173. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  95174. this.s = qs * s;
  95175. this.x = qx * s;
  95176. this.y = qy * s;
  95177. this.z = qz * s;
  95178. return this;
  95179. },
  95180. sub: function (q1, q2) {
  95181. this.s = q1.s - q2.s;
  95182. this.x = q1.x - q2.x;
  95183. this.y = q1.y - q2.y;
  95184. this.z = q1.z - q2.z;
  95185. return this;
  95186. },
  95187. scale: function (q, s) {
  95188. this.s = q.s * s;
  95189. this.x = q.x * s;
  95190. this.y = q.y * s;
  95191. this.z = q.z * s;
  95192. return this;
  95193. },
  95194. mul: function (q1, q2) {
  95195. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  95196. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  95197. this.x = ax * bs + as * bx + ay * bz - az * by;
  95198. this.y = ay * bs + as * by + az * bx - ax * bz;
  95199. this.z = az * bs + as * bz + ax * by - ay * bx;
  95200. this.s = as * bs - ax * bx - ay * by - az * bz;
  95201. return this;
  95202. },
  95203. arc: function (v1, v2) {
  95204. var x1 = v1.x;
  95205. var y1 = v1.y;
  95206. var z1 = v1.z;
  95207. var x2 = v2.x;
  95208. var y2 = v2.y;
  95209. var z2 = v2.z;
  95210. var d = x1 * x2 + y1 * y2 + z1 * z2;
  95211. if (d == -1) {
  95212. x2 = y1 * x1 - z1 * z1;
  95213. y2 = -z1 * y1 - x1 * x1;
  95214. z2 = x1 * z1 + y1 * y1;
  95215. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  95216. this.s = 0;
  95217. this.x = x2 * d;
  95218. this.y = y2 * d;
  95219. this.z = z2 * d;
  95220. return this;
  95221. }
  95222. var cx = y1 * z2 - z1 * y2;
  95223. var cy = z1 * x2 - x1 * z2;
  95224. var cz = x1 * y2 - y1 * x2;
  95225. this.s = OIMO.sqrt((1 + d) * 0.5);
  95226. d = 0.5 / this.s;
  95227. this.x = cx * d;
  95228. this.y = cy * d;
  95229. this.z = cz * d;
  95230. return this;
  95231. },
  95232. normalize: function (q) {
  95233. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  95234. if (len > 0) { len = 1 / len; }
  95235. this.s = q.s * len;
  95236. this.x = q.x * len;
  95237. this.y = q.y * len;
  95238. this.z = q.z * len;
  95239. return this;
  95240. },
  95241. invert: function (q) {
  95242. this.s = q.s;
  95243. this.x = -q.x;
  95244. this.y = -q.y;
  95245. this.z = -q.z;
  95246. return this;
  95247. },
  95248. length: function () {
  95249. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  95250. },
  95251. copy: function (q) {
  95252. this.s = q.s;
  95253. this.x = q.x;
  95254. this.y = q.y;
  95255. this.z = q.z;
  95256. return this;
  95257. },
  95258. testDiff: function (q) {
  95259. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  95260. else return false;
  95261. },
  95262. clone: function (q) {
  95263. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  95264. },
  95265. toString: function () {
  95266. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  95267. }
  95268. }
  95269. // for three easy export
  95270. OIMO.Quaternion = function (x, y, z, w) {
  95271. this.x = x || 0;
  95272. this.y = y || 0;
  95273. this.z = z || 0;
  95274. this.w = (w !== undefined) ? w : 1;
  95275. };
  95276. OIMO.Quaternion.prototype = {
  95277. constructor: OIMO.Quaternion,
  95278. setFromRotationMatrix: function (m) {
  95279. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  95280. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  95281. var te = m.elements,
  95282. m11 = te[0], m12 = te[1], m13 = te[2],
  95283. m21 = te[3], m22 = te[4], m23 = te[5],
  95284. m31 = te[6], m32 = te[7], m33 = te[8],
  95285. trace = m11 + m22 + m33,
  95286. s;
  95287. if (trace > 0) {
  95288. s = 0.5 / OIMO.sqrt(trace + 1.0);
  95289. this.w = 0.25 / s;
  95290. this.x = (m32 - m23) * s;
  95291. this.y = (m13 - m31) * s;
  95292. this.z = (m21 - m12) * s;
  95293. } else if (m11 > m22 && m11 > m33) {
  95294. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  95295. this.w = (m32 - m23) / s;
  95296. this.x = 0.25 * s;
  95297. this.y = (m12 + m21) / s;
  95298. this.z = (m13 + m31) / s;
  95299. } else if (m22 > m33) {
  95300. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  95301. this.w = (m13 - m31) / s;
  95302. this.x = (m12 + m21) / s;
  95303. this.y = 0.25 * s;
  95304. this.z = (m23 + m32) / s;
  95305. } else {
  95306. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  95307. this.w = (m21 - m12) / s;
  95308. this.x = (m13 + m31) / s;
  95309. this.y = (m23 + m32) / s;
  95310. this.z = 0.25 * s;
  95311. }
  95312. //this.onChangeCallback();
  95313. return this;
  95314. }
  95315. }
  95316. OIMO.Vec3 = function (x, y, z) {
  95317. this.x = x || 0;
  95318. this.y = y || 0;
  95319. this.z = z || 0;
  95320. };
  95321. OIMO.Vec3.prototype = {
  95322. constructor: OIMO.Vec3,
  95323. init: function (x, y, z) {
  95324. this.x = x || 0;
  95325. this.y = y || 0;
  95326. this.z = z || 0;
  95327. return this;
  95328. },
  95329. set: function (x, y, z) {
  95330. this.x = x;
  95331. this.y = y;
  95332. this.z = z;
  95333. return this;
  95334. },
  95335. add: function (v1, v2) {
  95336. this.x = v1.x + v2.x;
  95337. this.y = v1.y + v2.y;
  95338. this.z = v1.z + v2.z;
  95339. return this;
  95340. },
  95341. addEqual: function (v) {
  95342. this.x += v.x;
  95343. this.y += v.y;
  95344. this.z += v.z;
  95345. return this;
  95346. },
  95347. addTime: function (v, t) {
  95348. this.x += v.x * t;
  95349. this.y += v.y * t;
  95350. this.z += v.z * t;
  95351. return this;
  95352. },
  95353. sub: function (v1, v2) {
  95354. this.x = v1.x - v2.x;
  95355. this.y = v1.y - v2.y;
  95356. this.z = v1.z - v2.z;
  95357. return this;
  95358. },
  95359. subEqual: function (v) {
  95360. this.x -= v.x;
  95361. this.y -= v.y;
  95362. this.z -= v.z;
  95363. return this;
  95364. },
  95365. addScale: function (v, s) {
  95366. this.x += v.x * s;
  95367. this.y += v.y * s;
  95368. this.z += v.z * s;
  95369. return this;
  95370. },
  95371. scale: function (v, s) {
  95372. this.x = v.x * s;
  95373. this.y = v.y * s;
  95374. this.z = v.z * s;
  95375. return this;
  95376. },
  95377. scaleEqual: function (s) {
  95378. this.x *= s;
  95379. this.y *= s;
  95380. this.z *= s;
  95381. return this;
  95382. },
  95383. /*dot: function(v){
  95384. return this.x*v.x+this.y*v.y+this.z*v.z;
  95385. },*/
  95386. cross: function (v1, v2) {
  95387. var ax = v1.x, ay = v1.y, az = v1.z,
  95388. bx = v2.x, by = v2.y, bz = v2.z;
  95389. this.x = ay * bz - az * by;
  95390. this.y = az * bx - ax * bz;
  95391. this.z = ax * by - ay * bx;
  95392. return this;
  95393. },
  95394. mul: function (o, v, m) {
  95395. var te = m.elements;
  95396. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  95397. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  95398. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  95399. return this;
  95400. },
  95401. mulMat: function (m, v) {
  95402. var te = m.elements;
  95403. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  95404. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  95405. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  95406. return this;
  95407. },
  95408. normalize: function (v) {
  95409. var x = v.x, y = v.y, z = v.z;
  95410. var l = x * x + y * y + z * z;
  95411. if (l > 0) {
  95412. l = 1 / OIMO.sqrt(l);
  95413. this.x = x * l;
  95414. this.y = y * l;
  95415. this.z = z * l;
  95416. }
  95417. return this;
  95418. },
  95419. /*norm: function(){
  95420. var x = this.x, y = this.y, z = this.z;
  95421. var l = x*x + y*y + z*z;
  95422. if (l > 0) {
  95423. l = 1 / OIMO.sqrt(l);
  95424. this.x = x*l;
  95425. this.y = y*l;
  95426. this.z = z*l;
  95427. }
  95428. return this;
  95429. },*/
  95430. invert: function (v) {
  95431. this.x = -v.x;
  95432. this.y = -v.y;
  95433. this.z = -v.z;
  95434. return this;
  95435. },
  95436. /*length: function(){
  95437. var x = this.x, y = this.y, z = this.z;
  95438. return OIMO.sqrt(x*x + y*y + z*z);
  95439. },*/
  95440. negate: function () {
  95441. this.x = -this.x;
  95442. this.y = -this.y;
  95443. this.z = -this.z;
  95444. return this;
  95445. },
  95446. dot: function (v) {
  95447. return this.x * v.x + this.y * v.y + this.z * v.z;
  95448. },
  95449. lengthSq: function () {
  95450. return this.x * this.x + this.y * this.y + this.z * this.z;
  95451. },
  95452. length: function () {
  95453. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  95454. },
  95455. /*len: function(){
  95456. var x = this.x, y = this.y, z = this.z;
  95457. return x*x + y*y + z*z;
  95458. },*/
  95459. copy: function (v) {
  95460. this.x = v.x;
  95461. this.y = v.y;
  95462. this.z = v.z;
  95463. return this;
  95464. },
  95465. applyQuaternion: function (q) {
  95466. var x = this.x;
  95467. var y = this.y;
  95468. var z = this.z;
  95469. var qx = q.x;
  95470. var qy = q.y;
  95471. var qz = q.z;
  95472. var qs = q.s;
  95473. // calculate quat * vector
  95474. var ix = qs * x + qy * z - qz * y;
  95475. var iy = qs * y + qz * x - qx * z;
  95476. var iz = qs * z + qx * y - qy * x;
  95477. var iw = -qx * x - qy * y - qz * z;
  95478. // calculate result * inverse quat
  95479. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  95480. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  95481. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  95482. return this;
  95483. },
  95484. testZero: function () {
  95485. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  95486. else return false;
  95487. },
  95488. testDiff: function (v) {
  95489. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  95490. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  95491. //else return false;
  95492. },
  95493. equals: function (v) {
  95494. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  95495. },
  95496. clone: function () {
  95497. return new this.constructor(this.x, this.y, this.z);
  95498. },
  95499. toString: function () {
  95500. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  95501. },
  95502. multiplyScalar: function (scalar) {
  95503. if (isFinite(scalar)) {
  95504. this.x *= scalar;
  95505. this.y *= scalar;
  95506. this.z *= scalar;
  95507. } else {
  95508. this.x = 0;
  95509. this.y = 0;
  95510. this.z = 0;
  95511. }
  95512. return this;
  95513. },
  95514. divideScalar: function (scalar) {
  95515. return this.multiplyScalar(1 / scalar);
  95516. },
  95517. // TODO rename to normalize
  95518. norm: function () {
  95519. return this.divideScalar(this.length());
  95520. },
  95521. }
  95522. OIMO.Euler = function (x, y, z, order) {
  95523. this._x = x || 0;
  95524. this._y = y || 0;
  95525. this._z = z || 0;
  95526. this._order = order || OIMO.Euler.DefaultOrder;
  95527. };
  95528. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  95529. OIMO.Euler.DefaultOrder = 'XYZ';
  95530. OIMO.clamp = function (x, a, b) {
  95531. return (x < a) ? a : ((x > b) ? b : x);
  95532. }
  95533. OIMO.Euler.prototype = {
  95534. constructor: OIMO.Euler,
  95535. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  95536. get x() {
  95537. return this._x;
  95538. },
  95539. set x(value) {
  95540. this._x = value;
  95541. this.onChangeCallback();
  95542. },
  95543. get y() {
  95544. return this._y;
  95545. },
  95546. set y(value) {
  95547. this._y = value;
  95548. this.onChangeCallback();
  95549. },
  95550. get z() {
  95551. return this._z;
  95552. },
  95553. set z(value) {
  95554. this._z = value;
  95555. this.onChangeCallback();
  95556. },
  95557. get order() {
  95558. return this._order;
  95559. },
  95560. set order(value) {
  95561. this._order = value;
  95562. this.onChangeCallback();
  95563. },
  95564. set: function (x, y, z, order) {
  95565. this._x = x;
  95566. this._y = y;
  95567. this._z = z;
  95568. this._order = order || this._order;
  95569. this.onChangeCallback();
  95570. return this;
  95571. },
  95572. copy: function (euler) {
  95573. this._x = euler._x;
  95574. this._y = euler._y;
  95575. this._z = euler._z;
  95576. this._order = euler._order;
  95577. this.onChangeCallback();
  95578. return this;
  95579. },
  95580. setFromRotationMatrix: function (m, order) {
  95581. var clamp = OIMO.clamp;
  95582. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  95583. var te = m.elements;
  95584. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  95585. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  95586. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  95587. var m11 = te[0], m12 = te[1], m13 = te[2],
  95588. m21 = te[3], m22 = te[4], m23 = te[5],
  95589. m31 = te[6], m32 = te[7], m33 = te[8];
  95590. order = order || this._order;
  95591. if (order === 'XYZ') {
  95592. this._y = OIMO.asin(clamp(m13, -1, 1));
  95593. if (OIMO.abs(m13) < 0.99999) {
  95594. this._x = OIMO.atan2(-m23, m33);
  95595. this._z = OIMO.atan2(-m12, m11);
  95596. } else {
  95597. this._x = OIMO.atan2(m32, m22);
  95598. this._z = 0;
  95599. }
  95600. } else if (order === 'YXZ') {
  95601. this._x = OIMO.asin(-clamp(m23, -1, 1));
  95602. if (OIMO.abs(m23) < 0.99999) {
  95603. this._y = OIMO.atan2(m13, m33);
  95604. this._z = OIMO.atan2(m21, m22);
  95605. } else {
  95606. this._y = OIMO.atan2(-m31, m11);
  95607. this._z = 0;
  95608. }
  95609. } else if (order === 'ZXY') {
  95610. this._x = OIMO.asin(clamp(m32, -1, 1));
  95611. if (OIMO.abs(m32) < 0.99999) {
  95612. this._y = OIMO.atan2(-m31, m33);
  95613. this._z = OIMO.atan2(-m12, m22);
  95614. } else {
  95615. this._y = 0;
  95616. this._z = OIMO.atan2(m21, m11);
  95617. }
  95618. } else if (order === 'ZYX') {
  95619. this._y = OIMO.asin(-clamp(m31, -1, 1));
  95620. if (OIMO.abs(m31) < 0.99999) {
  95621. this._x = OIMO.atan2(m32, m33);
  95622. this._z = OIMO.atan2(m21, m11);
  95623. } else {
  95624. this._x = 0;
  95625. this._z = OIMO.atan2(-m12, m22);
  95626. }
  95627. } else if (order === 'YZX') {
  95628. this._z = OIMO.asin(clamp(m21, -1, 1));
  95629. if (OIMO.abs(m21) < 0.99999) {
  95630. this._x = OIMO.atan2(-m23, m22);
  95631. this._y = OIMO.atan2(-m31, m11);
  95632. } else {
  95633. this._x = 0;
  95634. this._y = OIMO.atan2(m13, m33);
  95635. }
  95636. } else if (order === 'XZY') {
  95637. this._z = OIMO.asin(-clamp(m12, -1, 1));
  95638. if (OIMO.abs(m12) < 0.99999) {
  95639. this._x = OIMO.atan2(m32, m22);
  95640. this._y = OIMO.atan2(m13, m11);
  95641. } else {
  95642. this._x = OIMO.atan2(-m23, m33);
  95643. this._y = 0;
  95644. }
  95645. } else {
  95646. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  95647. }
  95648. this._order = order;
  95649. this.onChangeCallback();
  95650. return this;
  95651. },
  95652. setFromQuaternion: function (q, order, update) {
  95653. var clamp = OIMO.clamp;
  95654. // q is assumed to be normalized
  95655. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  95656. var sqx = q.x * q.x;
  95657. var sqy = q.y * q.y;
  95658. var sqz = q.z * q.z;
  95659. var sqw = q.s * q.s;
  95660. order = order || this._order;
  95661. if (order === 'XYZ') {
  95662. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  95663. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  95664. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  95665. } else if (order === 'YXZ') {
  95666. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  95667. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  95668. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  95669. } else if (order === 'ZXY') {
  95670. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  95671. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  95672. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  95673. } else if (order === 'ZYX') {
  95674. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  95675. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  95676. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  95677. } else if (order === 'YZX') {
  95678. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  95679. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  95680. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  95681. } else if (order === 'XZY') {
  95682. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  95683. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  95684. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  95685. } else {
  95686. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  95687. }
  95688. this._order = order;
  95689. if (update !== false) this.onChangeCallback();
  95690. return this;
  95691. },
  95692. reorder: function () {
  95693. // WARNING: this discards revolution information -bhouston
  95694. var q = new OIMO.Quat();
  95695. return function (newOrder) {
  95696. q.setFromEuler(this);
  95697. this.setFromQuaternion(q, newOrder);
  95698. };
  95699. }(),
  95700. equals: function (euler) {
  95701. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  95702. },
  95703. fromArray: function (array) {
  95704. this._x = array[0];
  95705. this._y = array[1];
  95706. this._z = array[2];
  95707. if (array[3] !== undefined) this._order = array[3];
  95708. this.onChangeCallback();
  95709. return this;
  95710. },
  95711. toArray: function () {
  95712. return [this._x, this._y, this._z, this._order];
  95713. },
  95714. onChange: function (callback) {
  95715. this.onChangeCallback = callback;
  95716. return this;
  95717. },
  95718. onChangeCallback: function () { },
  95719. clone: function () {
  95720. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  95721. }
  95722. };
  95723. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  95724. var c1 = OIMO.cos(oy * 0.5);//heading
  95725. var s1 = OIMO.sin(oy * 0.5);
  95726. var c2 = OIMO.cos(oz * 0.5);//altitude
  95727. var s2 = OIMO.sin(oz * 0.5);
  95728. var c3 = OIMO.cos(ox * 0.5);//bank
  95729. var s3 = OIMO.sin(ox * 0.5);
  95730. var c1c2 = c1 * c2;
  95731. var s1s2 = s1 * s2;
  95732. var w = c1c2 * c3 - s1s2 * s3;
  95733. var x = c1c2 * s3 + s1s2 * c3;
  95734. var y = s1 * c2 * c3 + c1 * s2 * s3;
  95735. var z = c1 * s2 * c3 - s1 * c2 * s3;
  95736. var angle = 2 * OIMO.acos(w);
  95737. var norm = x * x + y * y + z * z;
  95738. if (norm < 0.001) {
  95739. x = 1;
  95740. y = z = 0;
  95741. } else {
  95742. norm = OIMO.sqrt(norm);
  95743. x /= norm;
  95744. y /= norm;
  95745. z /= norm;
  95746. }
  95747. return [angle, x, y, z];
  95748. }
  95749. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  95750. var ch = OIMO.cos(oy);//heading
  95751. var sh = OIMO.sin(oy);
  95752. var ca = OIMO.cos(oz);//altitude
  95753. var sa = OIMO.sin(oz);
  95754. var cb = OIMO.cos(ox);//bank
  95755. var sb = OIMO.sin(ox);
  95756. var mtx = new OIMO.Mat33();
  95757. var te = mtx.elements;
  95758. te[0] = ch * ca;
  95759. te[1] = sh * sb - ch * sa * cb;
  95760. te[2] = ch * sa * sb + sh * cb;
  95761. te[3] = sa;
  95762. te[4] = ca * cb;
  95763. te[5] = -ca * sb;
  95764. te[6] = -sh * ca;
  95765. te[7] = sh * sa * cb + ch * sb;
  95766. te[8] = -sh * sa * sb + ch * cb;
  95767. return mtx;
  95768. }
  95769. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  95770. var te = mtx.elements;
  95771. var x, y, z;
  95772. if (te[3] > 0.998) { // singularity at north pole
  95773. y = OIMO.atan2(te[2], te[8]);
  95774. z = OIMO.PI / 2;
  95775. x = 0;
  95776. } else if (te[3] < -0.998) { // singularity at south pole
  95777. y = OIMO.atan2(te[2], te[8]);
  95778. z = -OIMO.PI / 2;
  95779. x = 0;
  95780. } else {
  95781. y = OIMO.atan2(-te[6], te[0]);
  95782. x = OIMO.atan2(-te[5], te[4]);
  95783. z = OIMO.asin(te[3]);
  95784. }
  95785. return [x, y, z];
  95786. }
  95787. OIMO.unwrapDegrees = function (r) {
  95788. r = r % 360;
  95789. if (r > 180) r -= 360;
  95790. if (r < -180) r += 360;
  95791. return r;
  95792. }
  95793. OIMO.unwrapRadian = function (r) {
  95794. r = r % OIMO.TwoPI;
  95795. if (r > OIMO.PI) r -= OIMO.TwoPI;
  95796. if (r < -OIMO.PI) r += OIMO.TwoPI;
  95797. return r;
  95798. }
  95799. OIMO.Distance3d = function (p1, p2) {
  95800. var xd = p2[0] - p1[0];
  95801. var yd = p2[1] - p1[1];
  95802. var zd = p2[2] - p1[2];
  95803. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  95804. }
  95805. /**
  95806. * The base class of all type of the constraints.
  95807. * @author saharan
  95808. */
  95809. OIMO.Constraint = function () {
  95810. // The parent world of the constraint.
  95811. this.parent = null;
  95812. // The first body of the constraint.
  95813. this.body1 = null;
  95814. // The second body of the constraint.
  95815. this.body2 = null;
  95816. // Internal
  95817. this.addedToIsland = false;
  95818. }
  95819. OIMO.Constraint.prototype = {
  95820. constructor: OIMO.Constraint,
  95821. /**
  95822. * Prepare for solving the constraint.
  95823. * @param timeStep
  95824. * @param invTimeStep
  95825. */
  95826. preSolve: function (timeStep, invTimeStep) {
  95827. OIMO.Error("Constraint", "Inheritance error.");
  95828. },
  95829. /**
  95830. * Solve the constraint.
  95831. * This is usually called iteratively.
  95832. */
  95833. solve: function () {
  95834. OIMO.Error("Constraint", "Inheritance error.");
  95835. },
  95836. /**
  95837. * Do the post-processing.
  95838. */
  95839. postSolve: function () {
  95840. OIMO.Error("Constraint", "Inheritance error.");
  95841. }
  95842. }
  95843. /**
  95844. * Joints are used to constrain the motion between two rigid bodies.
  95845. * @author saharan
  95846. * @author lo-th
  95847. */
  95848. OIMO.Joint = function (config) {
  95849. OIMO.Constraint.call(this);
  95850. // joint name
  95851. this.name = "";
  95852. // The type of the joint.
  95853. this.type = OIMO.JOINT_NULL;
  95854. // The previous joint in the world.
  95855. this.prev = null;
  95856. // The next joint in the world.
  95857. this.next = null;
  95858. this.body1 = config.body1;
  95859. this.body2 = config.body2;
  95860. // The anchor point on the first rigid body in local coordinate system.
  95861. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  95862. // The anchor point on the second rigid body in local coordinate system.
  95863. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  95864. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  95865. this.relativeAnchorPoint1 = new OIMO.Vec3();
  95866. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  95867. this.relativeAnchorPoint2 = new OIMO.Vec3();
  95868. // The anchor point on the first rigid body in world coordinate system.
  95869. this.anchorPoint1 = new OIMO.Vec3();
  95870. // The anchor point on the second rigid body in world coordinate system.
  95871. this.anchorPoint2 = new OIMO.Vec3();
  95872. // Whether allow collision between connected rigid bodies or not.
  95873. this.allowCollision = config.allowCollision;
  95874. this.b1Link = new OIMO.JointLink(this);
  95875. this.b2Link = new OIMO.JointLink(this);
  95876. this.matrix = new OIMO.Mat44();
  95877. };
  95878. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  95879. OIMO.Joint.prototype.constructor = OIMO.Joint;
  95880. // Update all the anchor points.
  95881. OIMO.Joint.prototype.updateAnchorPoints = function () {
  95882. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  95883. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  95884. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  95885. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  95886. };
  95887. // Attach the joint from the bodies.
  95888. OIMO.Joint.prototype.attach = function () {
  95889. this.b1Link.body = this.body2;
  95890. this.b2Link.body = this.body1;
  95891. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  95892. else this.b1Link.next = null;
  95893. this.body1.jointLink = this.b1Link;
  95894. this.body1.numJoints++;
  95895. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  95896. else this.b2Link.next = null;
  95897. this.body2.jointLink = this.b2Link;
  95898. this.body2.numJoints++;
  95899. };
  95900. // Detach the joint from the bodies.
  95901. OIMO.Joint.prototype.detach = function () {
  95902. var prev = this.b1Link.prev;
  95903. var next = this.b1Link.next;
  95904. if (prev != null) prev.next = next;
  95905. if (next != null) next.prev = prev;
  95906. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  95907. this.b1Link.prev = null;
  95908. this.b1Link.next = null;
  95909. this.b1Link.body = null;
  95910. this.body1.numJoints--;
  95911. prev = this.b2Link.prev;
  95912. next = this.b2Link.next;
  95913. if (prev != null) prev.next = next;
  95914. if (next != null) next.prev = prev;
  95915. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  95916. this.b2Link.prev = null;
  95917. this.b2Link.next = null;
  95918. this.b2Link.body = null;
  95919. this.body2.numJoints--;
  95920. this.b1Link.body = null;
  95921. this.b2Link.body = null;
  95922. };
  95923. // Awake the bodies.
  95924. OIMO.Joint.prototype.awake = function () {
  95925. this.body1.awake();
  95926. this.body2.awake();
  95927. };
  95928. // calculation function
  95929. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  95930. };
  95931. OIMO.Joint.prototype.solve = function () {
  95932. };
  95933. OIMO.Joint.prototype.postSolve = function () {
  95934. };
  95935. // Delete process
  95936. OIMO.Joint.prototype.remove = function () {
  95937. this.dispose();
  95938. };
  95939. OIMO.Joint.prototype.dispose = function () {
  95940. this.parent.removeJoint(this);
  95941. };
  95942. // Three js add
  95943. OIMO.Joint.prototype.getPosition = function () {
  95944. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  95945. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  95946. return [p1, p2];
  95947. };
  95948. OIMO.Joint.prototype.getMatrix = function () {
  95949. var m = this.matrix.elements;
  95950. var p1 = this.anchorPoint1;
  95951. var p2 = this.anchorPoint2;
  95952. m[0] = p1.x * OIMO.WORLD_SCALE;
  95953. m[1] = p1.y * OIMO.WORLD_SCALE;
  95954. m[2] = p1.z * OIMO.WORLD_SCALE;
  95955. m[3] = 0;
  95956. m[4] = p2.x * OIMO.WORLD_SCALE;
  95957. m[5] = p2.y * OIMO.WORLD_SCALE;
  95958. m[6] = p2.z * OIMO.WORLD_SCALE;
  95959. m[7] = 0;
  95960. return m;
  95961. };
  95962. /**
  95963. * A joint configuration holds all configuration data for constructing a joint.
  95964. * Joint configurations can be reused safely.
  95965. * @author saharan
  95966. */
  95967. OIMO.JointConfig = function () {
  95968. // The first rigid body of the joint.
  95969. this.body1 = null;
  95970. // The second rigid body of the joint.
  95971. this.body2 = null;
  95972. // The anchor point on the first rigid body in local coordinate system.
  95973. this.localAnchorPoint1 = new OIMO.Vec3();
  95974. // The anchor point on the second rigid body in local coordinate system.
  95975. this.localAnchorPoint2 = new OIMO.Vec3();
  95976. // The axis in the first body's coordinate system.
  95977. // his property is available in some joints.
  95978. this.localAxis1 = new OIMO.Vec3();
  95979. // The axis in the second body's coordinate system.
  95980. // This property is available in some joints.
  95981. this.localAxis2 = new OIMO.Vec3();
  95982. // Whether allow collision between connected rigid bodies or not.
  95983. this.allowCollision = false;
  95984. };
  95985. /**
  95986. * A link list of joints.
  95987. * @author saharan
  95988. */
  95989. OIMO.JointLink = function (joint) {
  95990. // The previous joint link.
  95991. this.prev = null;
  95992. // The next joint link.
  95993. this.next = null;
  95994. // The other rigid body connected to the joint.
  95995. this.body = null;
  95996. // The joint of the link.
  95997. this.joint = joint;
  95998. };
  95999. /**
  96000. * An information of limit and motor.
  96001. * @author saharan
  96002. */
  96003. OIMO.LimitMotor = function (axis, fixed) {
  96004. fixed = fixed || false;
  96005. // The axis of the constraint.
  96006. this.axis = axis;
  96007. // The current angle for rotational constraints.
  96008. this.angle = 0;
  96009. // The lower limit. Set lower > upper to disable
  96010. this.lowerLimit = fixed ? 0 : 1;
  96011. //if(fixed)this.lowerLimit = 0;
  96012. //else this.lowerLimit = 1;
  96013. // The upper limit. Set lower > upper to disable.
  96014. this.upperLimit = 0;
  96015. // The target motor speed.
  96016. this.motorSpeed = 0;
  96017. // The maximum motor force or torque. Set 0 to disable.
  96018. this.maxMotorForce = 0;
  96019. // The frequency of the spring. Set 0 to disable.
  96020. this.frequency = 0;
  96021. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  96022. this.dampingRatio = 0;
  96023. };
  96024. OIMO.LimitMotor.prototype = {
  96025. constructor: OIMO.LimitMotor,
  96026. /**
  96027. * Set limit data into this constraint.
  96028. * @param lowerLimit
  96029. * @param upperLimit
  96030. */
  96031. setLimit: function (lowerLimit, upperLimit) {
  96032. this.lowerLimit = lowerLimit;
  96033. this.upperLimit = upperLimit;
  96034. },
  96035. /**
  96036. * Set motor data into this constraint.
  96037. * @param motorSpeed
  96038. * @param maxMotorForce
  96039. */
  96040. setMotor: function (motorSpeed, maxMotorForce) {
  96041. this.motorSpeed = motorSpeed;
  96042. this.maxMotorForce = maxMotorForce;
  96043. },
  96044. /**
  96045. * Set spring data into this constraint.
  96046. * @param frequency
  96047. * @param dampingRatio
  96048. */
  96049. setSpring: function (frequency, dampingRatio) {
  96050. this.frequency = frequency;
  96051. this.dampingRatio = dampingRatio;
  96052. }
  96053. };
  96054. /**
  96055. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  96056. * @author saharan
  96057. * @author lo-th
  96058. */
  96059. OIMO.BallAndSocketJoint = function (config) {
  96060. OIMO.Joint.call(this, config);
  96061. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  96062. this.lc = new OIMO.LinearConstraint(this);
  96063. };
  96064. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  96065. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  96066. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96067. this.updateAnchorPoints();
  96068. this.lc.preSolve(timeStep, invTimeStep);
  96069. };
  96070. OIMO.BallAndSocketJoint.prototype.solve = function () {
  96071. this.lc.solve();
  96072. };
  96073. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  96074. };
  96075. /**
  96076. * A distance joint limits the distance between two anchor points on rigid bodies.
  96077. * @author saharan
  96078. * @author lo-th
  96079. */
  96080. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  96081. OIMO.Joint.call(this, config);
  96082. this.type = OIMO.JOINT_DISTANCE;
  96083. this.normal = new OIMO.Vec3();
  96084. this.nr = new OIMO.Vec3();
  96085. // The limit and motor information of the joint.
  96086. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  96087. this.limitMotor.lowerLimit = minDistance;
  96088. this.limitMotor.upperLimit = maxDistance;
  96089. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  96090. };
  96091. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  96092. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  96093. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96094. this.updateAnchorPoints();
  96095. //var nr = this.nr;
  96096. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  96097. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  96098. //if(len>0) len = 1/len;
  96099. //this.normal.scale( nr, len );
  96100. this.normal.normalize(this.nr);
  96101. this.t.preSolve(timeStep, invTimeStep);
  96102. };
  96103. OIMO.DistanceJoint.prototype.solve = function () {
  96104. this.t.solve();
  96105. };
  96106. OIMO.DistanceJoint.prototype.postSolve = function () {
  96107. };
  96108. /**
  96109. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  96110. * @author saharan
  96111. * @author lo-th
  96112. */
  96113. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  96114. OIMO.Joint.call(this, config);
  96115. this.type = OIMO.JOINT_HINGE;
  96116. // The axis in the first body's coordinate system.
  96117. this.localAxis1 = config.localAxis1.clone().norm();
  96118. // The axis in the second body's coordinate system.
  96119. this.localAxis2 = config.localAxis2.clone().norm();
  96120. // make angle axis 1
  96121. this.localAngle1 = new OIMO.Vec3(
  96122. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  96123. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  96124. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  96125. ).norm();
  96126. // make angle axis 2
  96127. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96128. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  96129. this.nor = new OIMO.Vec3();
  96130. this.tan = new OIMO.Vec3();
  96131. this.bin = new OIMO.Vec3();
  96132. this.ax1 = new OIMO.Vec3();
  96133. this.ax2 = new OIMO.Vec3();
  96134. this.an1 = new OIMO.Vec3();
  96135. this.an2 = new OIMO.Vec3();
  96136. // The rotational limit and motor information of the joint.
  96137. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  96138. this.limitMotor.lowerLimit = lowerAngleLimit;
  96139. this.limitMotor.upperLimit = upperAngleLimit;
  96140. this.lc = new OIMO.LinearConstraint(this);
  96141. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96142. };
  96143. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  96144. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  96145. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96146. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  96147. this.updateAnchorPoints();
  96148. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  96149. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  96150. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  96151. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  96152. this.nor.set(
  96153. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  96154. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  96155. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  96156. ).norm();
  96157. this.tan.set(
  96158. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  96159. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  96160. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  96161. ).norm();
  96162. this.bin.set(
  96163. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  96164. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  96165. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  96166. );
  96167. // calculate hinge angle
  96168. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  96169. if (
  96170. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  96171. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  96172. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  96173. ) {
  96174. this.limitMotor.angle = -limite;
  96175. } else {
  96176. this.limitMotor.angle = limite;
  96177. }
  96178. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  96179. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  96180. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  96181. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  96182. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  96183. this.r3.preSolve(timeStep, invTimeStep);
  96184. this.lc.preSolve(timeStep, invTimeStep);
  96185. };
  96186. OIMO.HingeJoint.prototype.solve = function () {
  96187. this.r3.solve();
  96188. this.lc.solve();
  96189. };
  96190. OIMO.HingeJoint.prototype.postSolve = function () {
  96191. };
  96192. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  96193. if (cos > 1) return 0;
  96194. else if (cos < -1) return OIMO.PI;
  96195. else return OIMO.acos(cos);
  96196. };
  96197. /**
  96198. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  96199. * @author saharan
  96200. * @author lo-th
  96201. */
  96202. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  96203. OIMO.Joint.call(this, config);
  96204. this.type = OIMO.JOINT_PRISMATIC;
  96205. // The axis in the first body's coordinate system.
  96206. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  96207. // The axis in the second body's coordinate system.
  96208. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  96209. this.localAxis1X = this.localAxis1.x;
  96210. this.localAxis1Y = this.localAxis1.y;
  96211. this.localAxis1Z = this.localAxis1.z;
  96212. this.localAxis2X = this.localAxis2.x;
  96213. this.localAxis2Y = this.localAxis2.y;
  96214. this.localAxis2Z = this.localAxis2.z;
  96215. this.nor = new OIMO.Vec3();
  96216. this.tan = new OIMO.Vec3();
  96217. this.bin = new OIMO.Vec3();
  96218. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96219. // The translational limit and motor information of the joint.
  96220. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  96221. this.limitMotor.lowerLimit = lowerTranslation;
  96222. this.limitMotor.upperLimit = upperTranslation;
  96223. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96224. };
  96225. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  96226. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  96227. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96228. var tmpM;
  96229. var tmp1X;
  96230. var tmp1Y;
  96231. var tmp1Z;
  96232. this.updateAnchorPoints();
  96233. tmpM = this.body1.rotation.elements;
  96234. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  96235. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  96236. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  96237. tmpM = this.body2.rotation.elements;
  96238. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  96239. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  96240. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  96241. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  96242. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  96243. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  96244. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  96245. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96246. nx *= tmp1X;
  96247. ny *= tmp1X;
  96248. nz *= tmp1X;
  96249. var tx = ny * nx - nz * nz;
  96250. var ty = -nz * ny - nx * nx;
  96251. var tz = nx * nz + ny * ny;
  96252. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  96253. tx *= tmp1X;
  96254. ty *= tmp1X;
  96255. tz *= tmp1X;
  96256. var bx = ny * tz - nz * ty;
  96257. var by = nz * tx - nx * tz;
  96258. var bz = nx * ty - ny * tx;
  96259. this.nor.init(nx, ny, nz);
  96260. this.tan.init(tx, ty, tz);
  96261. this.bin.init(bx, by, bz);
  96262. this.ac.preSolve(timeStep, invTimeStep);
  96263. this.t3.preSolve(timeStep, invTimeStep);
  96264. };
  96265. OIMO.PrismaticJoint.prototype.solve = function () {
  96266. this.ac.solve();
  96267. this.t3.solve();
  96268. };
  96269. OIMO.PrismaticJoint.prototype.postSolve = function () {
  96270. };
  96271. /**
  96272. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  96273. * @author saharan
  96274. * @author lo-th
  96275. */
  96276. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  96277. OIMO.Joint.call(this, config);
  96278. this.type = OIMO.JOINT_SLIDER;
  96279. // The first axis in local coordinate system.
  96280. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  96281. // The second axis in local coordinate system.
  96282. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  96283. var len;
  96284. this.localAxis1X = this.localAxis1.x;
  96285. this.localAxis1Y = this.localAxis1.y;
  96286. this.localAxis1Z = this.localAxis1.z;
  96287. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  96288. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  96289. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  96290. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  96291. this.localAngAxis1X *= len;
  96292. this.localAngAxis1Y *= len;
  96293. this.localAngAxis1Z *= len;
  96294. this.localAxis2X = this.localAxis2.x;
  96295. this.localAxis2Y = this.localAxis2.y;
  96296. this.localAxis2Z = this.localAxis2.z;
  96297. // make angle axis 2
  96298. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96299. var tarc = arc.elements;
  96300. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  96301. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  96302. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  96303. this.nor = new OIMO.Vec3();
  96304. this.tan = new OIMO.Vec3();
  96305. this.bin = new OIMO.Vec3();
  96306. // The limit and motor for the rotation
  96307. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  96308. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96309. // The limit and motor for the translation.
  96310. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  96311. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  96312. this.translationalLimitMotor.upperLimit = upperTranslation;
  96313. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96314. };
  96315. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  96316. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  96317. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96318. var tmpM;
  96319. var tmp1X;
  96320. var tmp1Y;
  96321. var tmp1Z;
  96322. this.updateAnchorPoints();
  96323. tmpM = this.body1.rotation.elements;
  96324. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  96325. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  96326. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  96327. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  96328. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  96329. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  96330. tmpM = this.body2.rotation.elements;
  96331. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  96332. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  96333. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  96334. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  96335. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  96336. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  96337. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  96338. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  96339. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  96340. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  96341. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96342. nx *= tmp1X;
  96343. ny *= tmp1X;
  96344. nz *= tmp1X;
  96345. var tx = ny * nx - nz * nz;
  96346. var ty = -nz * ny - nx * nx;
  96347. var tz = nx * nz + ny * ny;
  96348. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  96349. tx *= tmp1X;
  96350. ty *= tmp1X;
  96351. tz *= tmp1X;
  96352. var bx = ny * tz - nz * ty;
  96353. var by = nz * tx - nx * tz;
  96354. var bz = nx * ty - ny * tx;
  96355. this.nor.init(nx, ny, nz);
  96356. this.tan.init(tx, ty, tz);
  96357. this.bin.init(bx, by, bz);
  96358. // ----------------------------------------------
  96359. // calculate hinge angle
  96360. // ----------------------------------------------
  96361. if (
  96362. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  96363. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  96364. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  96365. ) {
  96366. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  96367. } else {
  96368. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  96369. }
  96370. // angular error
  96371. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  96372. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  96373. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  96374. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  96375. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  96376. this.r3.preSolve(timeStep, invTimeStep);
  96377. this.t3.preSolve(timeStep, invTimeStep);
  96378. };
  96379. OIMO.SliderJoint.prototype.solve = function () {
  96380. this.r3.solve();
  96381. this.t3.solve();
  96382. };
  96383. OIMO.SliderJoint.prototype.postSolve = function () {
  96384. };
  96385. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  96386. if (cos > 1) return 0;
  96387. else if (cos < -1) return OIMO.PI;
  96388. else return OIMO.acos(cos);
  96389. };
  96390. /**
  96391. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  96392. * The wheel joint also allows for relative translation for the suspension.
  96393. * @author saharan
  96394. * @author lo-th
  96395. */
  96396. OIMO.WheelJoint = function (config) {
  96397. OIMO.Joint.call(this, config);
  96398. this.type = OIMO.JOINT_WHEEL;
  96399. // The first axis in local coordinate system.
  96400. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  96401. // The second axis in local coordinate system.
  96402. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  96403. var len;
  96404. this.localAxis1X = this.localAxis1.x;
  96405. this.localAxis1Y = this.localAxis1.y;
  96406. this.localAxis1Z = this.localAxis1.z;
  96407. this.localAxis2X = this.localAxis2.x;
  96408. this.localAxis2Y = this.localAxis2.y;
  96409. this.localAxis2Z = this.localAxis2.z;
  96410. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  96411. if (dot > -1 && dot < 1) {
  96412. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  96413. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  96414. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  96415. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  96416. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  96417. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  96418. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  96419. this.localAngAxis1X *= len;
  96420. this.localAngAxis1Y *= len;
  96421. this.localAngAxis1Z *= len;
  96422. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  96423. this.localAngAxis2X *= len;
  96424. this.localAngAxis2Y *= len;
  96425. this.localAngAxis2Z *= len;
  96426. } else {
  96427. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  96428. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  96429. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  96430. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  96431. this.localAngAxis1X *= len;
  96432. this.localAngAxis1Y *= len;
  96433. this.localAngAxis1Z *= len;
  96434. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96435. var tarc = arc.elements;
  96436. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  96437. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  96438. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  96439. }
  96440. this.nor = new OIMO.Vec3();
  96441. this.tan = new OIMO.Vec3();
  96442. this.bin = new OIMO.Vec3();
  96443. // The translational limit and motor information of the joint.
  96444. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  96445. this.translationalLimitMotor.frequency = 8;
  96446. this.translationalLimitMotor.dampingRatio = 1;
  96447. // The first rotational limit and motor information of the joint.
  96448. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  96449. // The second rotational limit and motor information of the joint.
  96450. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  96451. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  96452. this.t3.weight = 1;
  96453. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  96454. };
  96455. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  96456. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  96457. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96458. var tmpM;
  96459. var tmp1X;
  96460. var tmp1Y;
  96461. var tmp1Z;
  96462. this.updateAnchorPoints();
  96463. tmpM = this.body1.rotation.elements;
  96464. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  96465. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  96466. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  96467. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  96468. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  96469. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  96470. tmpM = this.body2.rotation.elements;
  96471. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  96472. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  96473. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  96474. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  96475. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  96476. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  96477. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  96478. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  96479. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  96480. } else {
  96481. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  96482. }
  96483. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  96484. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  96485. } else {
  96486. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  96487. }
  96488. var nx = y2 * z1 - z2 * y1;
  96489. var ny = z2 * x1 - x2 * z1;
  96490. var nz = x2 * y1 - y2 * x1;
  96491. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  96492. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96493. nx *= tmp1X;
  96494. ny *= tmp1X;
  96495. nz *= tmp1X;
  96496. var tx = ny * z2 - nz * y2;
  96497. var ty = nz * x2 - nx * z2;
  96498. var tz = nx * y2 - ny * x2;
  96499. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  96500. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96501. tx *= tmp1X;
  96502. ty *= tmp1X;
  96503. tz *= tmp1X;
  96504. var bx = y1 * nz - z1 * ny;
  96505. var by = z1 * nx - x1 * nz;
  96506. var bz = x1 * ny - y1 * nx;
  96507. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  96508. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96509. bx *= tmp1X;
  96510. by *= tmp1X;
  96511. bz *= tmp1X;
  96512. this.nor.init(nx, ny, nz);
  96513. this.tan.init(tx, ty, tz);
  96514. this.bin.init(bx, by, bz);
  96515. this.r3.preSolve(timeStep, invTimeStep);
  96516. this.t3.preSolve(timeStep, invTimeStep);
  96517. };
  96518. OIMO.WheelJoint.prototype.solve = function () {
  96519. this.r3.solve();
  96520. this.t3.solve();
  96521. };
  96522. OIMO.WheelJoint.prototype.postSolve = function () {
  96523. };
  96524. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  96525. if (cos > 1) return 0;
  96526. else if (cos < -1) return OIMO.PI;
  96527. else return OIMO.acos(cos);
  96528. };
  96529. /**
  96530. * An angular constraint for all axes for various joints.
  96531. * @author saharan
  96532. */
  96533. OIMO.AngularConstraint = function (joint, targetOrientation) {
  96534. this.joint = joint;
  96535. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  96536. this.relativeOrientation = new OIMO.Quat();
  96537. this.ii1 = null;
  96538. this.ii2 = null;
  96539. this.dd = null;
  96540. this.vel = new OIMO.Vec3();
  96541. this.imp = new OIMO.Vec3();
  96542. this.rn0 = new OIMO.Vec3();
  96543. this.rn1 = new OIMO.Vec3();
  96544. this.rn2 = new OIMO.Vec3();
  96545. this.b1 = joint.body1;
  96546. this.b2 = joint.body2;
  96547. this.a1 = this.b1.angularVelocity;
  96548. this.a2 = this.b2.angularVelocity;
  96549. this.i1 = this.b1.inverseInertia;
  96550. this.i2 = this.b2.inverseInertia;
  96551. };
  96552. OIMO.AngularConstraint.prototype = {
  96553. constructor: OIMO.AngularConstraint,
  96554. preSolve: function (timeStep, invTimeStep) {
  96555. var inv, len, v, vv;
  96556. this.ii1 = this.i1.clone();
  96557. this.ii2 = this.i2.clone();
  96558. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  96559. inv = 1 / (v[0] * (v[4] * v[8] - v[7] * v[5]) + v[3] * (v[7] * v[2] - v[1] * v[8]) + v[6] * (v[1] * v[5] - v[4] * v[2]));
  96560. this.dd = new OIMO.Mat33(
  96561. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  96562. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  96563. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  96564. ).multiply(inv);
  96565. this.relativeOrientation.invert(this.b1.orientation);
  96566. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  96567. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  96568. inv = this.relativeOrientation.s * 2;
  96569. this.vel.scale(this.relativeOrientation, inv);
  96570. len = this.vel.length();
  96571. if (len > 0.02) {
  96572. len = (0.02 - len) / len * invTimeStep * 0.05;
  96573. this.vel.scaleEqual(len);
  96574. } else {
  96575. this.vel.init();
  96576. }
  96577. this.rn1.mulMat(this.ii1, this.imp);
  96578. this.rn2.mulMat(this.ii2, this.imp);
  96579. this.a1.addEqual(this.rn1);
  96580. this.a2.subEqual(this.rn2);
  96581. },
  96582. solve: function () {
  96583. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  96584. this.rn0.mulMat(this.dd, r);
  96585. this.rn1.mulMat(this.ii1, this.rn0);
  96586. this.rn2.mulMat(this.ii2, this.rn0);
  96587. this.imp.addEqual(this.rn0);
  96588. this.a1.addEqual(this.rn1);
  96589. this.a2.subEqual(this.rn2);
  96590. }
  96591. };
  96592. /**
  96593. * A linear constraint for all axes for various joints.
  96594. * @author saharan
  96595. */
  96596. OIMO.LinearConstraint = function (joint) {
  96597. this.m1 = NaN;
  96598. this.m2 = NaN;
  96599. this.ii1 = null;
  96600. this.ii2 = null;
  96601. this.dd = null;
  96602. this.r1x = NaN;
  96603. this.r1y = NaN;
  96604. this.r1z = NaN;
  96605. this.r2x = NaN;
  96606. this.r2y = NaN;
  96607. this.r2z = NaN;
  96608. this.ax1x = NaN;
  96609. this.ax1y = NaN;
  96610. this.ax1z = NaN;
  96611. this.ay1x = NaN;
  96612. this.ay1y = NaN;
  96613. this.ay1z = NaN;
  96614. this.az1x = NaN;
  96615. this.az1y = NaN;
  96616. this.az1z = NaN;
  96617. this.ax2x = NaN;
  96618. this.ax2y = NaN;
  96619. this.ax2z = NaN;
  96620. this.ay2x = NaN;
  96621. this.ay2y = NaN;
  96622. this.ay2z = NaN;
  96623. this.az2x = NaN;
  96624. this.az2y = NaN;
  96625. this.az2z = NaN;
  96626. this.vel = NaN;
  96627. this.velx = NaN;
  96628. this.vely = NaN;
  96629. this.velz = NaN;
  96630. this.joint = joint;
  96631. this.r1 = joint.relativeAnchorPoint1;
  96632. this.r2 = joint.relativeAnchorPoint2;
  96633. this.p1 = joint.anchorPoint1;
  96634. this.p2 = joint.anchorPoint2;
  96635. this.b1 = joint.body1;
  96636. this.b2 = joint.body2;
  96637. this.l1 = this.b1.linearVelocity;
  96638. this.l2 = this.b2.linearVelocity;
  96639. this.a1 = this.b1.angularVelocity;
  96640. this.a2 = this.b2.angularVelocity;
  96641. this.i1 = this.b1.inverseInertia;
  96642. this.i2 = this.b2.inverseInertia;
  96643. this.impx = 0;
  96644. this.impy = 0;
  96645. this.impz = 0;
  96646. }
  96647. OIMO.LinearConstraint.prototype = {
  96648. constructor: OIMO.LinearConstraint,
  96649. preSolve: function (timeStep, invTimeStep) {
  96650. this.r1x = this.r1.x;
  96651. this.r1y = this.r1.y;
  96652. this.r1z = this.r1.z;
  96653. this.r2x = this.r2.x;
  96654. this.r2y = this.r2.y;
  96655. this.r2z = this.r2.z;
  96656. this.m1 = this.b1.inverseMass;
  96657. this.m2 = this.b2.inverseMass;
  96658. this.ii1 = this.i1.clone();
  96659. this.ii2 = this.i2.clone();
  96660. var ii1 = this.ii1.elements;
  96661. var ii2 = this.ii2.elements;
  96662. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  96663. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  96664. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  96665. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  96666. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  96667. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  96668. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  96669. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  96670. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  96671. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  96672. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  96673. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  96674. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  96675. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  96676. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  96677. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  96678. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  96679. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  96680. // calculate point-to-point mass matrix
  96681. // from impulse equation
  96682. //
  96683. // M = ([/m] - [r^][/I][r^]) ^ -1
  96684. //
  96685. // where
  96686. //
  96687. // [/m] = |1/m, 0, 0|
  96688. // |0, 1/m, 0|
  96689. // |0, 0, 1/m|
  96690. //
  96691. // [r^] = |0, -rz, ry|
  96692. // |rz, 0, -rx|
  96693. // |-ry, rx, 0|
  96694. //
  96695. // [/I] = Inverted moment inertia
  96696. var rxx = this.m1 + this.m2;
  96697. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  96698. var k = kk.elements;
  96699. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  96700. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  96701. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  96702. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  96703. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  96704. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  96705. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  96706. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  96707. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  96708. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  96709. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  96710. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  96711. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  96712. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  96713. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  96714. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  96715. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  96716. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  96717. var inv = 1 / (k[0] * (k[4] * k[8] - k[7] * k[5]) + k[3] * (k[7] * k[2] - k[1] * k[8]) + k[6] * (k[1] * k[5] - k[4] * k[2]));
  96718. this.dd = new OIMO.Mat33(
  96719. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  96720. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  96721. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  96722. ).multiply(inv);
  96723. this.velx = this.p2.x - this.p1.x;
  96724. this.vely = this.p2.y - this.p1.y;
  96725. this.velz = this.p2.z - this.p1.z;
  96726. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  96727. if (len > 0.005) {
  96728. len = (0.005 - len) / len * invTimeStep * 0.05;
  96729. this.velx *= len;
  96730. this.vely *= len;
  96731. this.velz *= len;
  96732. } else {
  96733. this.velx = 0;
  96734. this.vely = 0;
  96735. this.velz = 0;
  96736. }
  96737. this.impx *= 0.95;
  96738. this.impy *= 0.95;
  96739. this.impz *= 0.95;
  96740. this.l1.x += this.impx * this.m1;
  96741. this.l1.y += this.impy * this.m1;
  96742. this.l1.z += this.impz * this.m1;
  96743. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  96744. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  96745. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  96746. this.l2.x -= this.impx * this.m2;
  96747. this.l2.y -= this.impy * this.m2;
  96748. this.l2.z -= this.impz * this.m2;
  96749. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  96750. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  96751. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  96752. },
  96753. solve: function () {
  96754. var d = this.dd.elements;
  96755. var rvx = this.l2.x - this.l1.x + this.a2.y * this.r2z - this.a2.z * this.r2y - this.a1.y * this.r1z + this.a1.z * this.r1y - this.velx;
  96756. var rvy = this.l2.y - this.l1.y + this.a2.z * this.r2x - this.a2.x * this.r2z - this.a1.z * this.r1x + this.a1.x * this.r1z - this.vely;
  96757. var rvz = this.l2.z - this.l1.z + this.a2.x * this.r2y - this.a2.y * this.r2x - this.a1.x * this.r1y + this.a1.y * this.r1x - this.velz;
  96758. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  96759. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  96760. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  96761. this.impx += nimpx;
  96762. this.impy += nimpy;
  96763. this.impz += nimpz;
  96764. this.l1.x += nimpx * this.m1;
  96765. this.l1.y += nimpy * this.m1;
  96766. this.l1.z += nimpz * this.m1;
  96767. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  96768. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  96769. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  96770. this.l2.x -= nimpx * this.m2;
  96771. this.l2.y -= nimpy * this.m2;
  96772. this.l2.z -= nimpz * this.m2;
  96773. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  96774. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  96775. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  96776. }
  96777. }
  96778. /**
  96779. * A three-axis rotational constraint for various joints.
  96780. * @author saharan
  96781. */
  96782. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96783. this.cfm1 = NaN;
  96784. this.cfm2 = NaN;
  96785. this.cfm3 = NaN;
  96786. this.i1e00 = NaN;
  96787. this.i1e01 = NaN;
  96788. this.i1e02 = NaN;
  96789. this.i1e10 = NaN;
  96790. this.i1e11 = NaN;
  96791. this.i1e12 = NaN;
  96792. this.i1e20 = NaN;
  96793. this.i1e21 = NaN;
  96794. this.i1e22 = NaN;
  96795. this.i2e00 = NaN;
  96796. this.i2e01 = NaN;
  96797. this.i2e02 = NaN;
  96798. this.i2e10 = NaN;
  96799. this.i2e11 = NaN;
  96800. this.i2e12 = NaN;
  96801. this.i2e20 = NaN;
  96802. this.i2e21 = NaN;
  96803. this.i2e22 = NaN;
  96804. this.ax1 = NaN;
  96805. this.ay1 = NaN;
  96806. this.az1 = NaN;
  96807. this.ax2 = NaN;
  96808. this.ay2 = NaN;
  96809. this.az2 = NaN;
  96810. this.ax3 = NaN;
  96811. this.ay3 = NaN;
  96812. this.az3 = NaN;
  96813. this.a1x1 = NaN; // jacoians
  96814. this.a1y1 = NaN;
  96815. this.a1z1 = NaN;
  96816. this.a2x1 = NaN;
  96817. this.a2y1 = NaN;
  96818. this.a2z1 = NaN;
  96819. this.a1x2 = NaN;
  96820. this.a1y2 = NaN;
  96821. this.a1z2 = NaN;
  96822. this.a2x2 = NaN;
  96823. this.a2y2 = NaN;
  96824. this.a2z2 = NaN;
  96825. this.a1x3 = NaN;
  96826. this.a1y3 = NaN;
  96827. this.a1z3 = NaN;
  96828. this.a2x3 = NaN;
  96829. this.a2y3 = NaN;
  96830. this.a2z3 = NaN;
  96831. this.lowerLimit1 = NaN;
  96832. this.upperLimit1 = NaN;
  96833. this.limitVelocity1 = NaN;
  96834. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96835. this.enableMotor1 = false;
  96836. this.motorSpeed1 = NaN;
  96837. this.maxMotorForce1 = NaN;
  96838. this.maxMotorImpulse1 = NaN;
  96839. this.lowerLimit2 = NaN;
  96840. this.upperLimit2 = NaN;
  96841. this.limitVelocity2 = NaN;
  96842. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96843. this.enableMotor2 = false;
  96844. this.motorSpeed2 = NaN;
  96845. this.maxMotorForce2 = NaN;
  96846. this.maxMotorImpulse2 = NaN;
  96847. this.lowerLimit3 = NaN;
  96848. this.upperLimit3 = NaN;
  96849. this.limitVelocity3 = NaN;
  96850. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96851. this.enableMotor3 = false;
  96852. this.motorSpeed3 = NaN;
  96853. this.maxMotorForce3 = NaN;
  96854. this.maxMotorImpulse3 = NaN;
  96855. this.k00 = NaN; // K = J*M*JT
  96856. this.k01 = NaN;
  96857. this.k02 = NaN;
  96858. this.k10 = NaN;
  96859. this.k11 = NaN;
  96860. this.k12 = NaN;
  96861. this.k20 = NaN;
  96862. this.k21 = NaN;
  96863. this.k22 = NaN;
  96864. this.kv00 = NaN; // diagonals without CFMs
  96865. this.kv11 = NaN;
  96866. this.kv22 = NaN;
  96867. this.dv00 = NaN; // ...inverted
  96868. this.dv11 = NaN;
  96869. this.dv22 = NaN;
  96870. this.d00 = NaN; // K^-1
  96871. this.d01 = NaN;
  96872. this.d02 = NaN;
  96873. this.d10 = NaN;
  96874. this.d11 = NaN;
  96875. this.d12 = NaN;
  96876. this.d20 = NaN;
  96877. this.d21 = NaN;
  96878. this.d22 = NaN;
  96879. this.limitMotor1 = limitMotor1;
  96880. this.limitMotor2 = limitMotor2;
  96881. this.limitMotor3 = limitMotor3;
  96882. this.b1 = joint.body1;
  96883. this.b2 = joint.body2;
  96884. this.a1 = this.b1.angularVelocity;
  96885. this.a2 = this.b2.angularVelocity;
  96886. this.i1 = this.b1.inverseInertia;
  96887. this.i2 = this.b2.inverseInertia;
  96888. this.limitImpulse1 = 0;
  96889. this.motorImpulse1 = 0;
  96890. this.limitImpulse2 = 0;
  96891. this.motorImpulse2 = 0;
  96892. this.limitImpulse3 = 0;
  96893. this.motorImpulse3 = 0;
  96894. }
  96895. OIMO.Rotational3Constraint.prototype = {
  96896. constructor: OIMO.Rotational3Constraint,
  96897. preSolve: function (timeStep, invTimeStep) {
  96898. this.ax1 = this.limitMotor1.axis.x;
  96899. this.ay1 = this.limitMotor1.axis.y;
  96900. this.az1 = this.limitMotor1.axis.z;
  96901. this.ax2 = this.limitMotor2.axis.x;
  96902. this.ay2 = this.limitMotor2.axis.y;
  96903. this.az2 = this.limitMotor2.axis.z;
  96904. this.ax3 = this.limitMotor3.axis.x;
  96905. this.ay3 = this.limitMotor3.axis.y;
  96906. this.az3 = this.limitMotor3.axis.z;
  96907. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  96908. this.upperLimit1 = this.limitMotor1.upperLimit;
  96909. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  96910. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  96911. this.enableMotor1 = this.maxMotorForce1 > 0;
  96912. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  96913. this.upperLimit2 = this.limitMotor2.upperLimit;
  96914. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96915. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96916. this.enableMotor2 = this.maxMotorForce2 > 0;
  96917. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96918. this.upperLimit3 = this.limitMotor3.upperLimit;
  96919. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96920. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96921. this.enableMotor3 = this.maxMotorForce3 > 0;
  96922. var ti1 = this.i1.elements;
  96923. var ti2 = this.i2.elements;
  96924. this.i1e00 = ti1[0];
  96925. this.i1e01 = ti1[1];
  96926. this.i1e02 = ti1[2];
  96927. this.i1e10 = ti1[3];
  96928. this.i1e11 = ti1[4];
  96929. this.i1e12 = ti1[5];
  96930. this.i1e20 = ti1[6];
  96931. this.i1e21 = ti1[7];
  96932. this.i1e22 = ti1[8];
  96933. this.i2e00 = ti2[0];
  96934. this.i2e01 = ti2[1];
  96935. this.i2e02 = ti2[2];
  96936. this.i2e10 = ti2[3];
  96937. this.i2e11 = ti2[4];
  96938. this.i2e12 = ti2[5];
  96939. this.i2e20 = ti2[6];
  96940. this.i2e21 = ti2[7];
  96941. this.i2e22 = ti2[8];
  96942. var frequency1 = this.limitMotor1.frequency;
  96943. var frequency2 = this.limitMotor2.frequency;
  96944. var frequency3 = this.limitMotor3.frequency;
  96945. var enableSpring1 = frequency1 > 0;
  96946. var enableSpring2 = frequency2 > 0;
  96947. var enableSpring3 = frequency3 > 0;
  96948. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96949. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96950. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96951. var angle1 = this.limitMotor1.angle;
  96952. if (enableLimit1) {
  96953. if (this.lowerLimit1 == this.upperLimit1) {
  96954. if (this.limitState1 != 0) {
  96955. this.limitState1 = 0;
  96956. this.limitImpulse1 = 0;
  96957. }
  96958. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96959. } else if (angle1 < this.lowerLimit1) {
  96960. if (this.limitState1 != -1) {
  96961. this.limitState1 = -1;
  96962. this.limitImpulse1 = 0;
  96963. }
  96964. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96965. } else if (angle1 > this.upperLimit1) {
  96966. if (this.limitState1 != 1) {
  96967. this.limitState1 = 1;
  96968. this.limitImpulse1 = 0;
  96969. }
  96970. this.limitVelocity1 = this.upperLimit1 - angle1;
  96971. } else {
  96972. this.limitState1 = 2;
  96973. this.limitImpulse1 = 0;
  96974. this.limitVelocity1 = 0;
  96975. }
  96976. if (!enableSpring1) {
  96977. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  96978. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  96979. else this.limitVelocity1 = 0;
  96980. }
  96981. } else {
  96982. this.limitState1 = 2;
  96983. this.limitImpulse1 = 0;
  96984. }
  96985. var angle2 = this.limitMotor2.angle;
  96986. if (enableLimit2) {
  96987. if (this.lowerLimit2 == this.upperLimit2) {
  96988. if (this.limitState2 != 0) {
  96989. this.limitState2 = 0;
  96990. this.limitImpulse2 = 0;
  96991. }
  96992. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96993. } else if (angle2 < this.lowerLimit2) {
  96994. if (this.limitState2 != -1) {
  96995. this.limitState2 = -1;
  96996. this.limitImpulse2 = 0;
  96997. }
  96998. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96999. } else if (angle2 > this.upperLimit2) {
  97000. if (this.limitState2 != 1) {
  97001. this.limitState2 = 1;
  97002. this.limitImpulse2 = 0;
  97003. }
  97004. this.limitVelocity2 = this.upperLimit2 - angle2;
  97005. } else {
  97006. this.limitState2 = 2;
  97007. this.limitImpulse2 = 0;
  97008. this.limitVelocity2 = 0;
  97009. }
  97010. if (!enableSpring2) {
  97011. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  97012. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  97013. else this.limitVelocity2 = 0;
  97014. }
  97015. } else {
  97016. this.limitState2 = 2;
  97017. this.limitImpulse2 = 0;
  97018. }
  97019. var angle3 = this.limitMotor3.angle;
  97020. if (enableLimit3) {
  97021. if (this.lowerLimit3 == this.upperLimit3) {
  97022. if (this.limitState3 != 0) {
  97023. this.limitState3 = 0;
  97024. this.limitImpulse3 = 0;
  97025. }
  97026. this.limitVelocity3 = this.lowerLimit3 - angle3;
  97027. } else if (angle3 < this.lowerLimit3) {
  97028. if (this.limitState3 != -1) {
  97029. this.limitState3 = -1;
  97030. this.limitImpulse3 = 0;
  97031. }
  97032. this.limitVelocity3 = this.lowerLimit3 - angle3;
  97033. } else if (angle3 > this.upperLimit3) {
  97034. if (this.limitState3 != 1) {
  97035. this.limitState3 = 1;
  97036. this.limitImpulse3 = 0;
  97037. }
  97038. this.limitVelocity3 = this.upperLimit3 - angle3;
  97039. } else {
  97040. this.limitState3 = 2;
  97041. this.limitImpulse3 = 0;
  97042. this.limitVelocity3 = 0;
  97043. }
  97044. if (!enableSpring3) {
  97045. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  97046. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  97047. else this.limitVelocity3 = 0;
  97048. }
  97049. } else {
  97050. this.limitState3 = 2;
  97051. this.limitImpulse3 = 0;
  97052. }
  97053. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  97054. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  97055. } else {
  97056. this.motorImpulse1 = 0;
  97057. this.maxMotorImpulse1 = 0;
  97058. }
  97059. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  97060. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  97061. } else {
  97062. this.motorImpulse2 = 0;
  97063. this.maxMotorImpulse2 = 0;
  97064. }
  97065. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  97066. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  97067. } else {
  97068. this.motorImpulse3 = 0;
  97069. this.maxMotorImpulse3 = 0;
  97070. }
  97071. // build jacobians
  97072. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  97073. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  97074. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  97075. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  97076. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  97077. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  97078. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  97079. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  97080. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  97081. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  97082. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  97083. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  97084. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  97085. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  97086. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  97087. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  97088. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  97089. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  97090. // build an impulse matrix
  97091. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  97092. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  97093. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  97094. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  97095. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  97096. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  97097. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  97098. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  97099. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  97100. this.kv00 = this.k00;
  97101. this.kv11 = this.k11;
  97102. this.kv22 = this.k22;
  97103. this.dv00 = 1 / this.kv00;
  97104. this.dv11 = 1 / this.kv11;
  97105. this.dv22 = 1 / this.kv22;
  97106. if (enableSpring1 && this.limitState1 != 2) {
  97107. var omega = 6.2831853 * frequency1;
  97108. var k = omega * omega * timeStep;
  97109. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  97110. this.cfm1 = this.kv00 * dmp;
  97111. this.limitVelocity1 *= k * dmp;
  97112. } else {
  97113. this.cfm1 = 0;
  97114. this.limitVelocity1 *= invTimeStep * 0.05;
  97115. }
  97116. if (enableSpring2 && this.limitState2 != 2) {
  97117. omega = 6.2831853 * frequency2;
  97118. k = omega * omega * timeStep;
  97119. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  97120. this.cfm2 = this.kv11 * dmp;
  97121. this.limitVelocity2 *= k * dmp;
  97122. } else {
  97123. this.cfm2 = 0;
  97124. this.limitVelocity2 *= invTimeStep * 0.05;
  97125. }
  97126. if (enableSpring3 && this.limitState3 != 2) {
  97127. omega = 6.2831853 * frequency3;
  97128. k = omega * omega * timeStep;
  97129. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  97130. this.cfm3 = this.kv22 * dmp;
  97131. this.limitVelocity3 *= k * dmp;
  97132. } else {
  97133. this.cfm3 = 0;
  97134. this.limitVelocity3 *= invTimeStep * 0.05;
  97135. }
  97136. this.k00 += this.cfm1;
  97137. this.k11 += this.cfm2;
  97138. this.k22 += this.cfm3;
  97139. var inv = 1 / (
  97140. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  97141. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  97142. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  97143. );
  97144. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  97145. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  97146. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  97147. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  97148. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  97149. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  97150. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  97151. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  97152. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  97153. this.limitImpulse1 *= 0.95;
  97154. this.motorImpulse1 *= 0.95;
  97155. this.limitImpulse2 *= 0.95;
  97156. this.motorImpulse2 *= 0.95;
  97157. this.limitImpulse3 *= 0.95;
  97158. this.motorImpulse3 *= 0.95;
  97159. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  97160. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  97161. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  97162. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  97163. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  97164. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  97165. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  97166. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  97167. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  97168. },
  97169. solve_: function () {
  97170. var rvx = this.a2.x - this.a1.x;
  97171. var rvy = this.a2.y - this.a1.y;
  97172. var rvz = this.a2.z - this.a1.z;
  97173. this.limitVelocity3 = 30;
  97174. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  97175. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  97176. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  97177. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97178. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97179. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97180. this.limitImpulse1 += dLimitImpulse1;
  97181. this.limitImpulse2 += dLimitImpulse2;
  97182. this.limitImpulse3 += dLimitImpulse3;
  97183. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  97184. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  97185. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  97186. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  97187. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  97188. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  97189. },
  97190. solve: function () {
  97191. var rvx = this.a2.x - this.a1.x;
  97192. var rvy = this.a2.y - this.a1.y;
  97193. var rvz = this.a2.z - this.a1.z;
  97194. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  97195. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97196. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  97197. var oldMotorImpulse1 = this.motorImpulse1;
  97198. var oldMotorImpulse2 = this.motorImpulse2;
  97199. var oldMotorImpulse3 = this.motorImpulse3;
  97200. var dMotorImpulse1 = 0;
  97201. var dMotorImpulse2 = 0;
  97202. var dMotorImpulse3 = 0;
  97203. if (this.enableMotor1) {
  97204. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  97205. this.motorImpulse1 += dMotorImpulse1;
  97206. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  97207. this.motorImpulse1 = this.maxMotorImpulse1;
  97208. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  97209. this.motorImpulse1 = -this.maxMotorImpulse1;
  97210. }
  97211. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  97212. }
  97213. if (this.enableMotor2) {
  97214. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  97215. this.motorImpulse2 += dMotorImpulse2;
  97216. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  97217. this.motorImpulse2 = this.maxMotorImpulse2;
  97218. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  97219. this.motorImpulse2 = -this.maxMotorImpulse2;
  97220. }
  97221. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  97222. }
  97223. if (this.enableMotor3) {
  97224. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  97225. this.motorImpulse3 += dMotorImpulse3;
  97226. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  97227. this.motorImpulse3 = this.maxMotorImpulse3;
  97228. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  97229. this.motorImpulse3 = -this.maxMotorImpulse3;
  97230. }
  97231. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  97232. }
  97233. // apply motor impulse to relative velocity
  97234. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  97235. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  97236. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  97237. // subtract target velocity and applied impulse
  97238. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  97239. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  97240. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  97241. var oldLimitImpulse1 = this.limitImpulse1;
  97242. var oldLimitImpulse2 = this.limitImpulse2;
  97243. var oldLimitImpulse3 = this.limitImpulse3;
  97244. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97245. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97246. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97247. this.limitImpulse1 += dLimitImpulse1;
  97248. this.limitImpulse2 += dLimitImpulse2;
  97249. this.limitImpulse3 += dLimitImpulse3;
  97250. // clamp
  97251. var clampState = 0;
  97252. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  97253. dLimitImpulse1 = -oldLimitImpulse1;
  97254. rvn2 += dLimitImpulse1 * this.k10;
  97255. rvn3 += dLimitImpulse1 * this.k20;
  97256. clampState |= 1;
  97257. }
  97258. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  97259. dLimitImpulse2 = -oldLimitImpulse2;
  97260. rvn1 += dLimitImpulse2 * this.k01;
  97261. rvn3 += dLimitImpulse2 * this.k21;
  97262. clampState |= 2;
  97263. }
  97264. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  97265. dLimitImpulse3 = -oldLimitImpulse3;
  97266. rvn1 += dLimitImpulse3 * this.k02;
  97267. rvn2 += dLimitImpulse3 * this.k12;
  97268. clampState |= 4;
  97269. }
  97270. // update un-clamped impulse
  97271. // TODO: isolate division
  97272. var det;
  97273. switch (clampState) {
  97274. case 1: // update 2 3
  97275. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  97276. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  97277. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  97278. break;
  97279. case 2: // update 1 3
  97280. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  97281. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  97282. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  97283. break;
  97284. case 3: // update 3
  97285. dLimitImpulse3 = rvn3 / this.k22;
  97286. break;
  97287. case 4: // update 1 2
  97288. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  97289. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  97290. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  97291. break;
  97292. case 5: // update 2
  97293. dLimitImpulse2 = rvn2 / this.k11;
  97294. break;
  97295. case 6: // update 1
  97296. dLimitImpulse1 = rvn1 / this.k00;
  97297. break;
  97298. }
  97299. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  97300. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  97301. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  97302. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  97303. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  97304. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  97305. // apply impulse
  97306. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  97307. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  97308. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  97309. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  97310. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  97311. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  97312. rvx = this.a2.x - this.a1.x;
  97313. rvy = this.a2.y - this.a1.y;
  97314. rvz = this.a2.z - this.a1.z;
  97315. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97316. }
  97317. }
  97318. /**
  97319. * A rotational constraint for various joints.
  97320. * @author saharan
  97321. */
  97322. OIMO.RotationalConstraint = function (joint, limitMotor) {
  97323. this.cfm = NaN;
  97324. this.i1e00 = NaN;
  97325. this.i1e01 = NaN;
  97326. this.i1e02 = NaN;
  97327. this.i1e10 = NaN;
  97328. this.i1e11 = NaN;
  97329. this.i1e12 = NaN;
  97330. this.i1e20 = NaN;
  97331. this.i1e21 = NaN;
  97332. this.i1e22 = NaN;
  97333. this.i2e00 = NaN;
  97334. this.i2e01 = NaN;
  97335. this.i2e02 = NaN;
  97336. this.i2e10 = NaN;
  97337. this.i2e11 = NaN;
  97338. this.i2e12 = NaN;
  97339. this.i2e20 = NaN;
  97340. this.i2e21 = NaN;
  97341. this.i2e22 = NaN;
  97342. this.motorDenom = NaN;
  97343. this.invMotorDenom = NaN;
  97344. this.invDenom = NaN;
  97345. this.ax = NaN;
  97346. this.ay = NaN;
  97347. this.az = NaN;
  97348. this.a1x = NaN;
  97349. this.a1y = NaN;
  97350. this.a1z = NaN;
  97351. this.a2x = NaN;
  97352. this.a2y = NaN;
  97353. this.a2z = NaN;
  97354. this.enableLimit = false;
  97355. this.lowerLimit = NaN;
  97356. this.upperLimit = NaN;
  97357. this.limitVelocity = NaN;
  97358. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97359. this.enableMotor = false;
  97360. this.motorSpeed = NaN;
  97361. this.maxMotorForce = NaN;
  97362. this.maxMotorImpulse = NaN;
  97363. this.limitMotor = limitMotor;
  97364. this.b1 = joint.body1;
  97365. this.b2 = joint.body2;
  97366. this.a1 = this.b1.angularVelocity;
  97367. this.a2 = this.b2.angularVelocity;
  97368. this.i1 = this.b1.inverseInertia;
  97369. this.i2 = this.b2.inverseInertia;
  97370. this.limitImpulse = 0;
  97371. this.motorImpulse = 0;
  97372. }
  97373. OIMO.RotationalConstraint.prototype = {
  97374. constructor: OIMO.RotationalConstraint,
  97375. preSolve: function (timeStep, invTimeStep) {
  97376. this.ax = this.limitMotor.axis.x;
  97377. this.ay = this.limitMotor.axis.y;
  97378. this.az = this.limitMotor.axis.z;
  97379. this.lowerLimit = this.limitMotor.lowerLimit;
  97380. this.upperLimit = this.limitMotor.upperLimit;
  97381. this.motorSpeed = this.limitMotor.motorSpeed;
  97382. this.maxMotorForce = this.limitMotor.maxMotorForce;
  97383. this.enableMotor = this.maxMotorForce > 0;
  97384. var ti1 = this.i1.elements;
  97385. var ti2 = this.i2.elements;
  97386. this.i1e00 = ti1[0];
  97387. this.i1e01 = ti1[1];
  97388. this.i1e02 = ti1[2];
  97389. this.i1e10 = ti1[3];
  97390. this.i1e11 = ti1[4];
  97391. this.i1e12 = ti1[5];
  97392. this.i1e20 = ti1[6];
  97393. this.i1e21 = ti1[7];
  97394. this.i1e22 = ti1[8];
  97395. this.i2e00 = ti2[0];
  97396. this.i2e01 = ti2[1];
  97397. this.i2e02 = ti2[2];
  97398. this.i2e10 = ti2[3];
  97399. this.i2e11 = ti2[4];
  97400. this.i2e12 = ti2[5];
  97401. this.i2e20 = ti2[6];
  97402. this.i2e21 = ti2[7];
  97403. this.i2e22 = ti2[8];
  97404. var frequency = this.limitMotor.frequency;
  97405. var enableSpring = frequency > 0;
  97406. var enableLimit = this.lowerLimit <= this.upperLimit;
  97407. var angle = this.limitMotor.angle;
  97408. if (enableLimit) {
  97409. if (this.lowerLimit == this.upperLimit) {
  97410. if (this.limitState != 0) {
  97411. this.limitState = 0;
  97412. this.limitImpulse = 0;
  97413. }
  97414. this.limitVelocity = this.lowerLimit - angle;
  97415. } else if (angle < this.lowerLimit) {
  97416. if (this.limitState != -1) {
  97417. this.limitState = -1;
  97418. this.limitImpulse = 0;
  97419. }
  97420. this.limitVelocity = this.lowerLimit - angle;
  97421. } else if (angle > this.upperLimit) {
  97422. if (this.limitState != 1) {
  97423. this.limitState = 1;
  97424. this.limitImpulse = 0;
  97425. }
  97426. this.limitVelocity = this.upperLimit - angle;
  97427. } else {
  97428. this.limitState = 2;
  97429. this.limitImpulse = 0;
  97430. this.limitVelocity = 0;
  97431. }
  97432. if (!enableSpring) {
  97433. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  97434. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  97435. else this.limitVelocity = 0;
  97436. }
  97437. } else {
  97438. this.limitState = 2;
  97439. this.limitImpulse = 0;
  97440. }
  97441. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  97442. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  97443. } else {
  97444. this.motorImpulse = 0;
  97445. this.maxMotorImpulse = 0;
  97446. }
  97447. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  97448. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  97449. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  97450. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  97451. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  97452. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  97453. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  97454. this.invMotorDenom = 1 / this.motorDenom;
  97455. if (enableSpring && this.limitState != 2) {
  97456. var omega = 6.2831853 * frequency;
  97457. var k = omega * omega * timeStep;
  97458. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  97459. this.cfm = this.motorDenom * dmp;
  97460. this.limitVelocity *= k * dmp;
  97461. } else {
  97462. this.cfm = 0;
  97463. this.limitVelocity *= invTimeStep * 0.05;
  97464. }
  97465. this.invDenom = 1 / (this.motorDenom + this.cfm);
  97466. this.limitImpulse *= 0.95;
  97467. this.motorImpulse *= 0.95;
  97468. var totalImpulse = this.limitImpulse + this.motorImpulse;
  97469. this.a1.x += totalImpulse * this.a1x;
  97470. this.a1.y += totalImpulse * this.a1y;
  97471. this.a1.z += totalImpulse * this.a1z;
  97472. this.a2.x -= totalImpulse * this.a2x;
  97473. this.a2.y -= totalImpulse * this.a2y;
  97474. this.a2.z -= totalImpulse * this.a2z;
  97475. },
  97476. solve: function () {
  97477. var rvn = this.ax * (this.a2.x - this.a1.x) + this.ay * (this.a2.y - this.a1.y) + this.az * (this.a2.z - this.a1.z);
  97478. // motor part
  97479. var newMotorImpulse;
  97480. if (this.enableMotor) {
  97481. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  97482. var oldMotorImpulse = this.motorImpulse;
  97483. this.motorImpulse += newMotorImpulse;
  97484. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  97485. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  97486. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  97487. rvn -= newMotorImpulse * this.motorDenom;
  97488. } else newMotorImpulse = 0;
  97489. // limit part
  97490. var newLimitImpulse;
  97491. if (this.limitState != 2) {
  97492. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  97493. var oldLimitImpulse = this.limitImpulse;
  97494. this.limitImpulse += newLimitImpulse;
  97495. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  97496. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  97497. } else newLimitImpulse = 0;
  97498. var totalImpulse = newLimitImpulse + newMotorImpulse;
  97499. this.a1.x += totalImpulse * this.a1x;
  97500. this.a1.y += totalImpulse * this.a1y;
  97501. this.a1.z += totalImpulse * this.a1z;
  97502. this.a2.x -= totalImpulse * this.a2x;
  97503. this.a2.y -= totalImpulse * this.a2y;
  97504. this.a2.z -= totalImpulse * this.a2z;
  97505. }
  97506. }
  97507. /**
  97508. * A three-axis translational constraint for various joints.
  97509. * @author saharan
  97510. */
  97511. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  97512. this.m1 = NaN;
  97513. this.m2 = NaN;
  97514. this.i1e00 = NaN;
  97515. this.i1e01 = NaN;
  97516. this.i1e02 = NaN;
  97517. this.i1e10 = NaN;
  97518. this.i1e11 = NaN;
  97519. this.i1e12 = NaN;
  97520. this.i1e20 = NaN;
  97521. this.i1e21 = NaN;
  97522. this.i1e22 = NaN;
  97523. this.i2e00 = NaN;
  97524. this.i2e01 = NaN;
  97525. this.i2e02 = NaN;
  97526. this.i2e10 = NaN;
  97527. this.i2e11 = NaN;
  97528. this.i2e12 = NaN;
  97529. this.i2e20 = NaN;
  97530. this.i2e21 = NaN;
  97531. this.i2e22 = NaN;
  97532. this.ax1 = NaN;
  97533. this.ay1 = NaN;
  97534. this.az1 = NaN;
  97535. this.ax2 = NaN;
  97536. this.ay2 = NaN;
  97537. this.az2 = NaN;
  97538. this.ax3 = NaN;
  97539. this.ay3 = NaN;
  97540. this.az3 = NaN;
  97541. this.r1x = NaN;
  97542. this.r1y = NaN;
  97543. this.r1z = NaN;
  97544. this.r2x = NaN;
  97545. this.r2y = NaN;
  97546. this.r2z = NaN;
  97547. this.t1x1 = NaN;// jacobians
  97548. this.t1y1 = NaN;
  97549. this.t1z1 = NaN;
  97550. this.t2x1 = NaN;
  97551. this.t2y1 = NaN;
  97552. this.t2z1 = NaN;
  97553. this.l1x1 = NaN;
  97554. this.l1y1 = NaN;
  97555. this.l1z1 = NaN;
  97556. this.l2x1 = NaN;
  97557. this.l2y1 = NaN;
  97558. this.l2z1 = NaN;
  97559. this.a1x1 = NaN;
  97560. this.a1y1 = NaN;
  97561. this.a1z1 = NaN;
  97562. this.a2x1 = NaN;
  97563. this.a2y1 = NaN;
  97564. this.a2z1 = NaN;
  97565. this.t1x2 = NaN;
  97566. this.t1y2 = NaN;
  97567. this.t1z2 = NaN;
  97568. this.t2x2 = NaN;
  97569. this.t2y2 = NaN;
  97570. this.t2z2 = NaN;
  97571. this.l1x2 = NaN;
  97572. this.l1y2 = NaN;
  97573. this.l1z2 = NaN;
  97574. this.l2x2 = NaN;
  97575. this.l2y2 = NaN;
  97576. this.l2z2 = NaN;
  97577. this.a1x2 = NaN;
  97578. this.a1y2 = NaN;
  97579. this.a1z2 = NaN;
  97580. this.a2x2 = NaN;
  97581. this.a2y2 = NaN;
  97582. this.a2z2 = NaN;
  97583. this.t1x3 = NaN;
  97584. this.t1y3 = NaN;
  97585. this.t1z3 = NaN;
  97586. this.t2x3 = NaN;
  97587. this.t2y3 = NaN;
  97588. this.t2z3 = NaN;
  97589. this.l1x3 = NaN;
  97590. this.l1y3 = NaN;
  97591. this.l1z3 = NaN;
  97592. this.l2x3 = NaN;
  97593. this.l2y3 = NaN;
  97594. this.l2z3 = NaN;
  97595. this.a1x3 = NaN;
  97596. this.a1y3 = NaN;
  97597. this.a1z3 = NaN;
  97598. this.a2x3 = NaN;
  97599. this.a2y3 = NaN;
  97600. this.a2z3 = NaN;
  97601. this.lowerLimit1 = NaN;
  97602. this.upperLimit1 = NaN;
  97603. this.limitVelocity1 = NaN;
  97604. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97605. this.enableMotor1 = false;
  97606. this.motorSpeed1 = NaN;
  97607. this.maxMotorForce1 = NaN;
  97608. this.maxMotorImpulse1 = NaN;
  97609. this.lowerLimit2 = NaN;
  97610. this.upperLimit2 = NaN;
  97611. this.limitVelocity2 = NaN;
  97612. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97613. this.enableMotor2 = false;
  97614. this.motorSpeed2 = NaN;
  97615. this.maxMotorForce2 = NaN;
  97616. this.maxMotorImpulse2 = NaN;
  97617. this.lowerLimit3 = NaN;
  97618. this.upperLimit3 = NaN;
  97619. this.limitVelocity3 = NaN;
  97620. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97621. this.enableMotor3 = false;
  97622. this.motorSpeed3 = NaN;
  97623. this.maxMotorForce3 = NaN;
  97624. this.maxMotorImpulse3 = NaN;
  97625. this.k00 = NaN; // K = J*M*JT
  97626. this.k01 = NaN;
  97627. this.k02 = NaN;
  97628. this.k10 = NaN;
  97629. this.k11 = NaN;
  97630. this.k12 = NaN;
  97631. this.k20 = NaN;
  97632. this.k21 = NaN;
  97633. this.k22 = NaN;
  97634. this.kv00 = NaN; // diagonals without CFMs
  97635. this.kv11 = NaN;
  97636. this.kv22 = NaN;
  97637. this.dv00 = NaN; // ...inverted
  97638. this.dv11 = NaN;
  97639. this.dv22 = NaN;
  97640. this.d00 = NaN; // K^-1
  97641. this.d01 = NaN;
  97642. this.d02 = NaN;
  97643. this.d10 = NaN;
  97644. this.d11 = NaN;
  97645. this.d12 = NaN;
  97646. this.d20 = NaN;
  97647. this.d21 = NaN;
  97648. this.d22 = NaN;
  97649. this.limitMotor1 = limitMotor1;
  97650. this.limitMotor2 = limitMotor2;
  97651. this.limitMotor3 = limitMotor3;
  97652. this.b1 = joint.body1;
  97653. this.b2 = joint.body2;
  97654. this.p1 = joint.anchorPoint1;
  97655. this.p2 = joint.anchorPoint2;
  97656. this.r1 = joint.relativeAnchorPoint1;
  97657. this.r2 = joint.relativeAnchorPoint2;
  97658. this.l1 = this.b1.linearVelocity;
  97659. this.l2 = this.b2.linearVelocity;
  97660. this.a1 = this.b1.angularVelocity;
  97661. this.a2 = this.b2.angularVelocity;
  97662. this.i1 = this.b1.inverseInertia;
  97663. this.i2 = this.b2.inverseInertia;
  97664. this.limitImpulse1 = 0;
  97665. this.motorImpulse1 = 0;
  97666. this.limitImpulse2 = 0;
  97667. this.motorImpulse2 = 0;
  97668. this.limitImpulse3 = 0;
  97669. this.motorImpulse3 = 0;
  97670. this.cfm1 = 0;// Constraint Force Mixing
  97671. this.cfm2 = 0;
  97672. this.cfm3 = 0;
  97673. this.weight = -1;
  97674. }
  97675. OIMO.Translational3Constraint.prototype = {
  97676. constructor: OIMO.Translational3Constraint,
  97677. preSolve: function (timeStep, invTimeStep) {
  97678. this.ax1 = this.limitMotor1.axis.x;
  97679. this.ay1 = this.limitMotor1.axis.y;
  97680. this.az1 = this.limitMotor1.axis.z;
  97681. this.ax2 = this.limitMotor2.axis.x;
  97682. this.ay2 = this.limitMotor2.axis.y;
  97683. this.az2 = this.limitMotor2.axis.z;
  97684. this.ax3 = this.limitMotor3.axis.x;
  97685. this.ay3 = this.limitMotor3.axis.y;
  97686. this.az3 = this.limitMotor3.axis.z;
  97687. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  97688. this.upperLimit1 = this.limitMotor1.upperLimit;
  97689. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  97690. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  97691. this.enableMotor1 = this.maxMotorForce1 > 0;
  97692. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  97693. this.upperLimit2 = this.limitMotor2.upperLimit;
  97694. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  97695. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  97696. this.enableMotor2 = this.maxMotorForce2 > 0;
  97697. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  97698. this.upperLimit3 = this.limitMotor3.upperLimit;
  97699. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  97700. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  97701. this.enableMotor3 = this.maxMotorForce3 > 0;
  97702. this.m1 = this.b1.inverseMass;
  97703. this.m2 = this.b2.inverseMass;
  97704. var ti1 = this.i1.elements;
  97705. var ti2 = this.i2.elements;
  97706. this.i1e00 = ti1[0];
  97707. this.i1e01 = ti1[1];
  97708. this.i1e02 = ti1[2];
  97709. this.i1e10 = ti1[3];
  97710. this.i1e11 = ti1[4];
  97711. this.i1e12 = ti1[5];
  97712. this.i1e20 = ti1[6];
  97713. this.i1e21 = ti1[7];
  97714. this.i1e22 = ti1[8];
  97715. this.i2e00 = ti2[0];
  97716. this.i2e01 = ti2[1];
  97717. this.i2e02 = ti2[2];
  97718. this.i2e10 = ti2[3];
  97719. this.i2e11 = ti2[4];
  97720. this.i2e12 = ti2[5];
  97721. this.i2e20 = ti2[6];
  97722. this.i2e21 = ti2[7];
  97723. this.i2e22 = ti2[8];
  97724. var dx = this.p2.x - this.p1.x;
  97725. var dy = this.p2.y - this.p1.y;
  97726. var dz = this.p2.z - this.p1.z;
  97727. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  97728. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  97729. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  97730. var frequency1 = this.limitMotor1.frequency;
  97731. var frequency2 = this.limitMotor2.frequency;
  97732. var frequency3 = this.limitMotor3.frequency;
  97733. var enableSpring1 = frequency1 > 0;
  97734. var enableSpring2 = frequency2 > 0;
  97735. var enableSpring3 = frequency3 > 0;
  97736. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  97737. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  97738. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  97739. // for stability
  97740. if (enableSpring1 && d1 > 20 || d1 < -20) {
  97741. enableSpring1 = false;
  97742. }
  97743. if (enableSpring2 && d2 > 20 || d2 < -20) {
  97744. enableSpring2 = false;
  97745. }
  97746. if (enableSpring3 && d3 > 20 || d3 < -20) {
  97747. enableSpring3 = false;
  97748. }
  97749. if (enableLimit1) {
  97750. if (this.lowerLimit1 == this.upperLimit1) {
  97751. if (this.limitState1 != 0) {
  97752. this.limitState1 = 0;
  97753. this.limitImpulse1 = 0;
  97754. }
  97755. this.limitVelocity1 = this.lowerLimit1 - d1;
  97756. if (!enableSpring1) d1 = this.lowerLimit1;
  97757. } else if (d1 < this.lowerLimit1) {
  97758. if (this.limitState1 != -1) {
  97759. this.limitState1 = -1;
  97760. this.limitImpulse1 = 0;
  97761. }
  97762. this.limitVelocity1 = this.lowerLimit1 - d1;
  97763. if (!enableSpring1) d1 = this.lowerLimit1;
  97764. } else if (d1 > this.upperLimit1) {
  97765. if (this.limitState1 != 1) {
  97766. this.limitState1 = 1;
  97767. this.limitImpulse1 = 0;
  97768. }
  97769. this.limitVelocity1 = this.upperLimit1 - d1;
  97770. if (!enableSpring1) d1 = this.upperLimit1;
  97771. } else {
  97772. this.limitState1 = 2;
  97773. this.limitImpulse1 = 0;
  97774. this.limitVelocity1 = 0;
  97775. }
  97776. if (!enableSpring1) {
  97777. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  97778. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  97779. else this.limitVelocity1 = 0;
  97780. }
  97781. } else {
  97782. this.limitState1 = 2;
  97783. this.limitImpulse1 = 0;
  97784. }
  97785. if (enableLimit2) {
  97786. if (this.lowerLimit2 == this.upperLimit2) {
  97787. if (this.limitState2 != 0) {
  97788. this.limitState2 = 0;
  97789. this.limitImpulse2 = 0;
  97790. }
  97791. this.limitVelocity2 = this.lowerLimit2 - d2;
  97792. if (!enableSpring2) d2 = this.lowerLimit2;
  97793. } else if (d2 < this.lowerLimit2) {
  97794. if (this.limitState2 != -1) {
  97795. this.limitState2 = -1;
  97796. this.limitImpulse2 = 0;
  97797. }
  97798. this.limitVelocity2 = this.lowerLimit2 - d2;
  97799. if (!enableSpring2) d2 = this.lowerLimit2;
  97800. } else if (d2 > this.upperLimit2) {
  97801. if (this.limitState2 != 1) {
  97802. this.limitState2 = 1;
  97803. this.limitImpulse2 = 0;
  97804. }
  97805. this.limitVelocity2 = this.upperLimit2 - d2;
  97806. if (!enableSpring2) d2 = this.upperLimit2;
  97807. } else {
  97808. this.limitState2 = 2;
  97809. this.limitImpulse2 = 0;
  97810. this.limitVelocity2 = 0;
  97811. }
  97812. if (!enableSpring2) {
  97813. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  97814. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  97815. else this.limitVelocity2 = 0;
  97816. }
  97817. } else {
  97818. this.limitState2 = 2;
  97819. this.limitImpulse2 = 0;
  97820. }
  97821. if (enableLimit3) {
  97822. if (this.lowerLimit3 == this.upperLimit3) {
  97823. if (this.limitState3 != 0) {
  97824. this.limitState3 = 0;
  97825. this.limitImpulse3 = 0;
  97826. }
  97827. this.limitVelocity3 = this.lowerLimit3 - d3;
  97828. if (!enableSpring3) d3 = this.lowerLimit3;
  97829. } else if (d3 < this.lowerLimit3) {
  97830. if (this.limitState3 != -1) {
  97831. this.limitState3 = -1;
  97832. this.limitImpulse3 = 0;
  97833. }
  97834. this.limitVelocity3 = this.lowerLimit3 - d3;
  97835. if (!enableSpring3) d3 = this.lowerLimit3;
  97836. } else if (d3 > this.upperLimit3) {
  97837. if (this.limitState3 != 1) {
  97838. this.limitState3 = 1;
  97839. this.limitImpulse3 = 0;
  97840. }
  97841. this.limitVelocity3 = this.upperLimit3 - d3;
  97842. if (!enableSpring3) d3 = this.upperLimit3;
  97843. } else {
  97844. this.limitState3 = 2;
  97845. this.limitImpulse3 = 0;
  97846. this.limitVelocity3 = 0;
  97847. }
  97848. if (!enableSpring3) {
  97849. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  97850. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  97851. else this.limitVelocity3 = 0;
  97852. }
  97853. } else {
  97854. this.limitState3 = 2;
  97855. this.limitImpulse3 = 0;
  97856. }
  97857. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  97858. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  97859. } else {
  97860. this.motorImpulse1 = 0;
  97861. this.maxMotorImpulse1 = 0;
  97862. }
  97863. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  97864. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  97865. } else {
  97866. this.motorImpulse2 = 0;
  97867. this.maxMotorImpulse2 = 0;
  97868. }
  97869. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  97870. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  97871. } else {
  97872. this.motorImpulse3 = 0;
  97873. this.maxMotorImpulse3 = 0;
  97874. }
  97875. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  97876. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  97877. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  97878. var w1 = this.m2 / (this.m1 + this.m2);
  97879. if (this.weight >= 0) w1 = this.weight; // use given weight
  97880. var w2 = 1 - w1;
  97881. this.r1x = this.r1.x + rdx * w1;
  97882. this.r1y = this.r1.y + rdy * w1;
  97883. this.r1z = this.r1.z + rdz * w1;
  97884. this.r2x = this.r2.x - rdx * w2;
  97885. this.r2y = this.r2.y - rdy * w2;
  97886. this.r2z = this.r2.z - rdz * w2;
  97887. // build jacobians
  97888. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  97889. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  97890. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  97891. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  97892. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  97893. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  97894. this.l1x1 = this.ax1 * this.m1;
  97895. this.l1y1 = this.ay1 * this.m1;
  97896. this.l1z1 = this.az1 * this.m1;
  97897. this.l2x1 = this.ax1 * this.m2;
  97898. this.l2y1 = this.ay1 * this.m2;
  97899. this.l2z1 = this.az1 * this.m2;
  97900. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  97901. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  97902. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  97903. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  97904. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  97905. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  97906. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  97907. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  97908. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  97909. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  97910. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  97911. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  97912. this.l1x2 = this.ax2 * this.m1;
  97913. this.l1y2 = this.ay2 * this.m1;
  97914. this.l1z2 = this.az2 * this.m1;
  97915. this.l2x2 = this.ax2 * this.m2;
  97916. this.l2y2 = this.ay2 * this.m2;
  97917. this.l2z2 = this.az2 * this.m2;
  97918. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  97919. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  97920. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  97921. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  97922. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  97923. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  97924. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  97925. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  97926. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  97927. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  97928. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  97929. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  97930. this.l1x3 = this.ax3 * this.m1;
  97931. this.l1y3 = this.ay3 * this.m1;
  97932. this.l1z3 = this.az3 * this.m1;
  97933. this.l2x3 = this.ax3 * this.m2;
  97934. this.l2y3 = this.ay3 * this.m2;
  97935. this.l2z3 = this.az3 * this.m2;
  97936. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  97937. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  97938. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  97939. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  97940. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  97941. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  97942. // build an impulse matrix
  97943. var m12 = this.m1 + this.m2;
  97944. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  97945. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  97946. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  97947. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  97948. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  97949. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  97950. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  97951. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  97952. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  97953. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  97954. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  97955. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  97956. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  97957. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  97958. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  97959. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  97960. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  97961. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  97962. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  97963. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  97964. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  97965. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  97966. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  97967. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  97968. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  97969. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  97970. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  97971. this.kv00 = this.k00;
  97972. this.kv11 = this.k11;
  97973. this.kv22 = this.k22;
  97974. this.dv00 = 1 / this.kv00;
  97975. this.dv11 = 1 / this.kv11;
  97976. this.dv22 = 1 / this.kv22;
  97977. if (enableSpring1 && this.limitState1 != 2) {
  97978. var omega = 6.2831853 * frequency1;
  97979. var k = omega * omega * timeStep;
  97980. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  97981. this.cfm1 = this.kv00 * dmp;
  97982. this.limitVelocity1 *= k * dmp;
  97983. } else {
  97984. this.cfm1 = 0;
  97985. this.limitVelocity1 *= invTimeStep * 0.05;
  97986. }
  97987. if (enableSpring2 && this.limitState2 != 2) {
  97988. omega = 6.2831853 * frequency2;
  97989. k = omega * omega * timeStep;
  97990. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  97991. this.cfm2 = this.kv11 * dmp;
  97992. this.limitVelocity2 *= k * dmp;
  97993. } else {
  97994. this.cfm2 = 0;
  97995. this.limitVelocity2 *= invTimeStep * 0.05;
  97996. }
  97997. if (enableSpring3 && this.limitState3 != 2) {
  97998. omega = 6.2831853 * frequency3;
  97999. k = omega * omega * timeStep;
  98000. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  98001. this.cfm3 = this.kv22 * dmp;
  98002. this.limitVelocity3 *= k * dmp;
  98003. } else {
  98004. this.cfm3 = 0;
  98005. this.limitVelocity3 *= invTimeStep * 0.05;
  98006. }
  98007. this.k00 += this.cfm1;
  98008. this.k11 += this.cfm2;
  98009. this.k22 += this.cfm3;
  98010. var inv = 1 / (
  98011. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  98012. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  98013. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  98014. );
  98015. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  98016. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  98017. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  98018. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  98019. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  98020. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  98021. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  98022. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  98023. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  98024. // warm starting
  98025. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  98026. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  98027. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  98028. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  98029. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  98030. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  98031. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  98032. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  98033. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  98034. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  98035. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  98036. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  98037. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  98038. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  98039. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  98040. },
  98041. solve: function () {
  98042. var rvx = this.l2.x - this.l1.x + this.a2.y * this.r2z - this.a2.z * this.r2y - this.a1.y * this.r1z + this.a1.z * this.r1y;
  98043. var rvy = this.l2.y - this.l1.y + this.a2.z * this.r2x - this.a2.x * this.r2z - this.a1.z * this.r1x + this.a1.x * this.r1z;
  98044. var rvz = this.l2.z - this.l1.z + this.a2.x * this.r2y - this.a2.y * this.r2x - this.a1.x * this.r1y + this.a1.y * this.r1x;
  98045. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  98046. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  98047. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  98048. var oldMotorImpulse1 = this.motorImpulse1;
  98049. var oldMotorImpulse2 = this.motorImpulse2;
  98050. var oldMotorImpulse3 = this.motorImpulse3;
  98051. var dMotorImpulse1 = 0;
  98052. var dMotorImpulse2 = 0;
  98053. var dMotorImpulse3 = 0;
  98054. if (this.enableMotor1) {
  98055. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  98056. this.motorImpulse1 += dMotorImpulse1;
  98057. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  98058. this.motorImpulse1 = this.maxMotorImpulse1;
  98059. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  98060. this.motorImpulse1 = -this.maxMotorImpulse1;
  98061. }
  98062. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  98063. }
  98064. if (this.enableMotor2) {
  98065. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  98066. this.motorImpulse2 += dMotorImpulse2;
  98067. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  98068. this.motorImpulse2 = this.maxMotorImpulse2;
  98069. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  98070. this.motorImpulse2 = -this.maxMotorImpulse2;
  98071. }
  98072. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  98073. }
  98074. if (this.enableMotor3) {
  98075. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  98076. this.motorImpulse3 += dMotorImpulse3;
  98077. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  98078. this.motorImpulse3 = this.maxMotorImpulse3;
  98079. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  98080. this.motorImpulse3 = -this.maxMotorImpulse3;
  98081. }
  98082. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  98083. }
  98084. // apply motor impulse to relative velocity
  98085. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  98086. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  98087. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  98088. // subtract target velocity and applied impulse
  98089. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  98090. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  98091. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  98092. var oldLimitImpulse1 = this.limitImpulse1;
  98093. var oldLimitImpulse2 = this.limitImpulse2;
  98094. var oldLimitImpulse3 = this.limitImpulse3;
  98095. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  98096. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  98097. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  98098. this.limitImpulse1 += dLimitImpulse1;
  98099. this.limitImpulse2 += dLimitImpulse2;
  98100. this.limitImpulse3 += dLimitImpulse3;
  98101. // clamp
  98102. var clampState = 0;
  98103. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  98104. dLimitImpulse1 = -oldLimitImpulse1;
  98105. rvn2 += dLimitImpulse1 * this.k10;
  98106. rvn3 += dLimitImpulse1 * this.k20;
  98107. clampState |= 1;
  98108. }
  98109. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  98110. dLimitImpulse2 = -oldLimitImpulse2;
  98111. rvn1 += dLimitImpulse2 * this.k01;
  98112. rvn3 += dLimitImpulse2 * this.k21;
  98113. clampState |= 2;
  98114. }
  98115. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  98116. dLimitImpulse3 = -oldLimitImpulse3;
  98117. rvn1 += dLimitImpulse3 * this.k02;
  98118. rvn2 += dLimitImpulse3 * this.k12;
  98119. clampState |= 4;
  98120. }
  98121. // update un-clamped impulse
  98122. // TODO: isolate division
  98123. var det;
  98124. switch (clampState) {
  98125. case 1:// update 2 3
  98126. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  98127. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  98128. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  98129. break;
  98130. case 2:// update 1 3
  98131. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  98132. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  98133. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  98134. break;
  98135. case 3:// update 3
  98136. dLimitImpulse3 = rvn3 / this.k22;
  98137. break;
  98138. case 4:// update 1 2
  98139. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  98140. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  98141. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  98142. break;
  98143. case 5:// update 2
  98144. dLimitImpulse2 = rvn2 / this.k11;
  98145. break;
  98146. case 6:// update 1
  98147. dLimitImpulse1 = rvn1 / this.k00;
  98148. break;
  98149. }
  98150. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  98151. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  98152. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  98153. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  98154. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  98155. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  98156. // apply impulse
  98157. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  98158. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  98159. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  98160. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  98161. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  98162. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  98163. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  98164. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  98165. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  98166. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  98167. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  98168. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  98169. }
  98170. }
  98171. /**
  98172. * A translational constraint for various joints.
  98173. * @author saharan
  98174. */
  98175. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  98176. this.cfm = NaN;
  98177. this.m1 = NaN;
  98178. this.m2 = NaN;
  98179. this.i1e00 = NaN;
  98180. this.i1e01 = NaN;
  98181. this.i1e02 = NaN;
  98182. this.i1e10 = NaN;
  98183. this.i1e11 = NaN;
  98184. this.i1e12 = NaN;
  98185. this.i1e20 = NaN;
  98186. this.i1e21 = NaN;
  98187. this.i1e22 = NaN;
  98188. this.i2e00 = NaN;
  98189. this.i2e01 = NaN;
  98190. this.i2e02 = NaN;
  98191. this.i2e10 = NaN;
  98192. this.i2e11 = NaN;
  98193. this.i2e12 = NaN;
  98194. this.i2e20 = NaN;
  98195. this.i2e21 = NaN;
  98196. this.i2e22 = NaN;
  98197. this.motorDenom = NaN;
  98198. this.invMotorDenom = NaN;
  98199. this.invDenom = NaN;
  98200. this.ax = NaN;
  98201. this.ay = NaN;
  98202. this.az = NaN;
  98203. this.r1x = NaN;
  98204. this.r1y = NaN;
  98205. this.r1z = NaN;
  98206. this.r2x = NaN;
  98207. this.r2y = NaN;
  98208. this.r2z = NaN;
  98209. this.t1x = NaN;
  98210. this.t1y = NaN;
  98211. this.t1z = NaN;
  98212. this.t2x = NaN;
  98213. this.t2y = NaN;
  98214. this.t2z = NaN;
  98215. this.l1x = NaN;
  98216. this.l1y = NaN;
  98217. this.l1z = NaN;
  98218. this.l2x = NaN;
  98219. this.l2y = NaN;
  98220. this.l2z = NaN;
  98221. this.a1x = NaN;
  98222. this.a1y = NaN;
  98223. this.a1z = NaN;
  98224. this.a2x = NaN;
  98225. this.a2y = NaN;
  98226. this.a2z = NaN;
  98227. this.lowerLimit = NaN;
  98228. this.upperLimit = NaN;
  98229. this.limitVelocity = NaN;
  98230. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  98231. this.enableMotor = false;
  98232. this.motorSpeed = NaN;
  98233. this.maxMotorForce = NaN;
  98234. this.maxMotorImpulse = NaN;
  98235. this.limitMotor = limitMotor;
  98236. this.b1 = joint.body1;
  98237. this.b2 = joint.body2;
  98238. this.p1 = joint.anchorPoint1;
  98239. this.p2 = joint.anchorPoint2;
  98240. this.r1 = joint.relativeAnchorPoint1;
  98241. this.r2 = joint.relativeAnchorPoint2;
  98242. this.l1 = this.b1.linearVelocity;
  98243. this.l2 = this.b2.linearVelocity;
  98244. this.a1 = this.b1.angularVelocity;
  98245. this.a2 = this.b2.angularVelocity;
  98246. this.i1 = this.b1.inverseInertia;
  98247. this.i2 = this.b2.inverseInertia;
  98248. this.limitImpulse = 0;
  98249. this.motorImpulse = 0;
  98250. }
  98251. OIMO.TranslationalConstraint.prototype = {
  98252. constructor: OIMO.TranslationalConstraint,
  98253. preSolve: function (timeStep, invTimeStep) {
  98254. this.ax = this.limitMotor.axis.x;
  98255. this.ay = this.limitMotor.axis.y;
  98256. this.az = this.limitMotor.axis.z;
  98257. this.lowerLimit = this.limitMotor.lowerLimit;
  98258. this.upperLimit = this.limitMotor.upperLimit;
  98259. this.motorSpeed = this.limitMotor.motorSpeed;
  98260. this.maxMotorForce = this.limitMotor.maxMotorForce;
  98261. this.enableMotor = this.maxMotorForce > 0;
  98262. this.m1 = this.b1.inverseMass;
  98263. this.m2 = this.b2.inverseMass;
  98264. var ti1 = this.i1.elements;
  98265. var ti2 = this.i2.elements;
  98266. this.i1e00 = ti1[0];
  98267. this.i1e01 = ti1[1];
  98268. this.i1e02 = ti1[2];
  98269. this.i1e10 = ti1[3];
  98270. this.i1e11 = ti1[4];
  98271. this.i1e12 = ti1[5];
  98272. this.i1e20 = ti1[6];
  98273. this.i1e21 = ti1[7];
  98274. this.i1e22 = ti1[8];
  98275. this.i2e00 = ti2[0];
  98276. this.i2e01 = ti2[1];
  98277. this.i2e02 = ti2[2];
  98278. this.i2e10 = ti2[3];
  98279. this.i2e11 = ti2[4];
  98280. this.i2e12 = ti2[5];
  98281. this.i2e20 = ti2[6];
  98282. this.i2e21 = ti2[7];
  98283. this.i2e22 = ti2[8];
  98284. var dx = this.p2.x - this.p1.x;
  98285. var dy = this.p2.y - this.p1.y;
  98286. var dz = this.p2.z - this.p1.z;
  98287. var d = dx * this.ax + dy * this.ay + dz * this.az;
  98288. var frequency = this.limitMotor.frequency;
  98289. var enableSpring = frequency > 0;
  98290. var enableLimit = this.lowerLimit <= this.upperLimit;
  98291. if (enableSpring && d > 20 || d < -20) {
  98292. enableSpring = false;
  98293. }
  98294. if (enableLimit) {
  98295. if (this.lowerLimit == this.upperLimit) {
  98296. if (this.limitState != 0) {
  98297. this.limitState = 0;
  98298. this.limitImpulse = 0;
  98299. }
  98300. this.limitVelocity = this.lowerLimit - d;
  98301. if (!enableSpring) d = this.lowerLimit;
  98302. } else if (d < this.lowerLimit) {
  98303. if (this.limitState != -1) {
  98304. this.limitState = -1;
  98305. this.limitImpulse = 0;
  98306. }
  98307. this.limitVelocity = this.lowerLimit - d;
  98308. if (!enableSpring) d = this.lowerLimit;
  98309. } else if (d > this.upperLimit) {
  98310. if (this.limitState != 1) {
  98311. this.limitState = 1;
  98312. this.limitImpulse = 0;
  98313. }
  98314. this.limitVelocity = this.upperLimit - d;
  98315. if (!enableSpring) d = this.upperLimit;
  98316. } else {
  98317. this.limitState = 2;
  98318. this.limitImpulse = 0;
  98319. this.limitVelocity = 0;
  98320. }
  98321. if (!enableSpring) {
  98322. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  98323. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  98324. else this.limitVelocity = 0;
  98325. }
  98326. } else {
  98327. this.limitState = 2;
  98328. this.limitImpulse = 0;
  98329. }
  98330. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  98331. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  98332. } else {
  98333. this.motorImpulse = 0;
  98334. this.maxMotorImpulse = 0;
  98335. }
  98336. var rdx = d * this.ax;
  98337. var rdy = d * this.ay;
  98338. var rdz = d * this.az;
  98339. var w1 = this.m1 / (this.m1 + this.m2);
  98340. var w2 = 1 - w1;
  98341. this.r1x = this.r1.x + rdx * w1;
  98342. this.r1y = this.r1.y + rdy * w1;
  98343. this.r1z = this.r1.z + rdz * w1;
  98344. this.r2x = this.r2.x - rdx * w2;
  98345. this.r2y = this.r2.y - rdy * w2;
  98346. this.r2z = this.r2.z - rdz * w2;
  98347. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  98348. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  98349. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  98350. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  98351. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  98352. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  98353. this.l1x = this.ax * this.m1;
  98354. this.l1y = this.ay * this.m1;
  98355. this.l1z = this.az * this.m1;
  98356. this.l2x = this.ax * this.m2;
  98357. this.l2y = this.ay * this.m2;
  98358. this.l2z = this.az * this.m2;
  98359. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  98360. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  98361. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  98362. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  98363. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  98364. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  98365. this.motorDenom =
  98366. this.m1 + this.m2 +
  98367. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  98368. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  98369. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  98370. this.invMotorDenom = 1 / this.motorDenom;
  98371. if (enableSpring && this.limitState != 2) {
  98372. var omega = 6.2831853 * frequency;
  98373. var k = omega * omega * timeStep;
  98374. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  98375. this.cfm = this.motorDenom * dmp;
  98376. this.limitVelocity *= k * dmp;
  98377. } else {
  98378. this.cfm = 0;
  98379. this.limitVelocity *= invTimeStep * 0.05;
  98380. }
  98381. this.invDenom = 1 / (this.motorDenom + this.cfm);
  98382. var totalImpulse = this.limitImpulse + this.motorImpulse;
  98383. this.l1.x += totalImpulse * this.l1x;
  98384. this.l1.y += totalImpulse * this.l1y;
  98385. this.l1.z += totalImpulse * this.l1z;
  98386. this.a1.x += totalImpulse * this.a1x;
  98387. this.a1.y += totalImpulse * this.a1y;
  98388. this.a1.z += totalImpulse * this.a1z;
  98389. this.l2.x -= totalImpulse * this.l2x;
  98390. this.l2.y -= totalImpulse * this.l2y;
  98391. this.l2.z -= totalImpulse * this.l2z;
  98392. this.a2.x -= totalImpulse * this.a2x;
  98393. this.a2.y -= totalImpulse * this.a2y;
  98394. this.a2.z -= totalImpulse * this.a2z;
  98395. },
  98396. solve: function () {
  98397. var rvn =
  98398. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  98399. this.t2x * this.a2.x - this.t1x * this.a1.x + this.t2y * this.a2.y - this.t1y * this.a1.y + this.t2z * this.a2.z - this.t1z * this.a1.z;
  98400. // motor part
  98401. var newMotorImpulse;
  98402. if (this.enableMotor) {
  98403. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  98404. var oldMotorImpulse = this.motorImpulse;
  98405. this.motorImpulse += newMotorImpulse;
  98406. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  98407. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  98408. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  98409. rvn -= newMotorImpulse * this.motorDenom;
  98410. } else newMotorImpulse = 0;
  98411. // limit part
  98412. var newLimitImpulse;
  98413. if (this.limitState != 2) {
  98414. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  98415. var oldLimitImpulse = this.limitImpulse;
  98416. this.limitImpulse += newLimitImpulse;
  98417. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  98418. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  98419. } else newLimitImpulse = 0;
  98420. var totalImpulse = newLimitImpulse + newMotorImpulse;
  98421. this.l1.x += totalImpulse * this.l1x;
  98422. this.l1.y += totalImpulse * this.l1y;
  98423. this.l1.z += totalImpulse * this.l1z;
  98424. this.a1.x += totalImpulse * this.a1x;
  98425. this.a1.y += totalImpulse * this.a1y;
  98426. this.a1.z += totalImpulse * this.a1z;
  98427. this.l2.x -= totalImpulse * this.l2x;
  98428. this.l2.y -= totalImpulse * this.l2y;
  98429. this.l2.z -= totalImpulse * this.l2z;
  98430. this.a2.x -= totalImpulse * this.a2x;
  98431. this.a2.y -= totalImpulse * this.a2y;
  98432. this.a2.z -= totalImpulse * this.a2z;
  98433. }
  98434. }
  98435. /**
  98436. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  98437. * @author saharan
  98438. */
  98439. OIMO.Contact = function () {
  98440. // The first shape.
  98441. this.shape1 = null;
  98442. // The second shape.
  98443. this.shape2 = null;
  98444. // The first rigid body.
  98445. this.body1 = null;
  98446. // The second rigid body.
  98447. this.body2 = null;
  98448. // The previous contact in the world.
  98449. this.prev = null;
  98450. // The next contact in the world.
  98451. this.next = null;
  98452. // Internal
  98453. this.persisting = false;
  98454. // Whether both the rigid bodies are sleeping or not.
  98455. this.sleeping = false;
  98456. // The collision detector between two shapes.
  98457. this.detector = null;
  98458. // The contact constraint of the contact.
  98459. this.constraint = null;
  98460. // Whether the shapes are touching or not.
  98461. this.touching = false;
  98462. this.b1Link = new OIMO.ContactLink(this);
  98463. this.b2Link = new OIMO.ContactLink(this);
  98464. this.s1Link = new OIMO.ContactLink(this);
  98465. this.s2Link = new OIMO.ContactLink(this);
  98466. // The contact manifold of the contact.
  98467. this.manifold = new OIMO.ContactManifold();
  98468. this.buffer = [];// vector 4
  98469. this.buffer.length = 4;
  98470. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  98471. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  98472. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  98473. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  98474. this.points = this.manifold.points;
  98475. this.constraint = new OIMO.ContactConstraint(this.manifold);
  98476. }
  98477. OIMO.Contact.prototype = {
  98478. constructor: OIMO.Contact,
  98479. mixRestitution: function (restitution1, restitution2) {
  98480. return OIMO.sqrt(restitution1 * restitution2);
  98481. },
  98482. mixFriction: function (friction1, friction2) {
  98483. return OIMO.sqrt(friction1 * friction2);
  98484. },
  98485. /**
  98486. * Update the contact manifold.
  98487. */
  98488. updateManifold: function () {
  98489. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  98490. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  98491. var numBuffers = this.manifold.numPoints;
  98492. var i = numBuffers;
  98493. while (i--) {
  98494. //for(var i=0;i<numBuffers;i++){
  98495. var b = this.buffer[i];
  98496. var p = this.points[i];
  98497. b.lp1X = p.localPoint1.x;
  98498. b.lp1Y = p.localPoint1.y;
  98499. b.lp1Z = p.localPoint1.z;
  98500. b.lp2X = p.localPoint2.x;
  98501. b.lp2Y = p.localPoint2.y;
  98502. b.lp2Z = p.localPoint2.z;
  98503. b.impulse = p.normalImpulse;
  98504. }
  98505. this.manifold.numPoints = 0;
  98506. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  98507. var num = this.manifold.numPoints;
  98508. if (num == 0) {
  98509. this.touching = false;
  98510. return;
  98511. }
  98512. this.touching = true;
  98513. i = num;
  98514. while (i--) {
  98515. //for(i=0; i<num; i++){
  98516. p = this.points[i];
  98517. var lp1x = p.localPoint1.x;
  98518. var lp1y = p.localPoint1.y;
  98519. var lp1z = p.localPoint1.z;
  98520. var lp2x = p.localPoint2.x;
  98521. var lp2y = p.localPoint2.y;
  98522. var lp2z = p.localPoint2.z;
  98523. var index = -1;
  98524. var minDistance = 0.0004;
  98525. var j = numBuffers;
  98526. while (j--) {
  98527. //for(var j=0;j<numBuffers;j++){
  98528. b = this.buffer[j];
  98529. var dx = b.lp1X - lp1x;
  98530. var dy = b.lp1Y - lp1y;
  98531. var dz = b.lp1Z - lp1z;
  98532. var distance1 = dx * dx + dy * dy + dz * dz;
  98533. dx = b.lp2X - lp2x;
  98534. dy = b.lp2Y - lp2y;
  98535. dz = b.lp2Z - lp2z;
  98536. var distance2 = dx * dx + dy * dy + dz * dz;
  98537. if (distance1 < distance2) {
  98538. if (distance1 < minDistance) {
  98539. minDistance = distance1;
  98540. index = j;
  98541. }
  98542. } else {
  98543. if (distance2 < minDistance) {
  98544. minDistance = distance2;
  98545. index = j;
  98546. }
  98547. }
  98548. }
  98549. if (index != -1) {
  98550. var tmp = this.buffer[index];
  98551. this.buffer[index] = this.buffer[--numBuffers];
  98552. this.buffer[numBuffers] = tmp;
  98553. p.normalImpulse = tmp.impulse;
  98554. p.warmStarted = true;
  98555. } else {
  98556. p.normalImpulse = 0;
  98557. p.warmStarted = false;
  98558. }
  98559. }
  98560. },
  98561. /**
  98562. * Attach the contact to the shapes.
  98563. * @param shape1
  98564. * @param shape2
  98565. */
  98566. attach: function (shape1, shape2) {
  98567. this.shape1 = shape1;
  98568. this.shape2 = shape2;
  98569. this.body1 = shape1.parent;
  98570. this.body2 = shape2.parent;
  98571. this.manifold.body1 = this.body1;
  98572. this.manifold.body2 = this.body2;
  98573. this.constraint.body1 = this.body1;
  98574. this.constraint.body2 = this.body2;
  98575. this.constraint.attach();
  98576. this.s1Link.shape = shape2;
  98577. this.s1Link.body = this.body2;
  98578. this.s2Link.shape = shape1;
  98579. this.s2Link.body = this.body1;
  98580. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  98581. else this.s1Link.next = null;
  98582. shape1.contactLink = this.s1Link;
  98583. shape1.numContacts++;
  98584. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  98585. else this.s2Link.next = null;
  98586. shape2.contactLink = this.s2Link;
  98587. shape2.numContacts++;
  98588. this.b1Link.shape = shape2;
  98589. this.b1Link.body = this.body2;
  98590. this.b2Link.shape = shape1;
  98591. this.b2Link.body = this.body1;
  98592. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  98593. else this.b1Link.next = null;
  98594. this.body1.contactLink = this.b1Link;
  98595. this.body1.numContacts++;
  98596. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  98597. else this.b2Link.next = null;
  98598. this.body2.contactLink = this.b2Link;
  98599. this.body2.numContacts++;
  98600. this.prev = null;
  98601. this.next = null;
  98602. this.persisting = true;
  98603. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  98604. this.manifold.numPoints = 0;
  98605. },
  98606. /**
  98607. * Detach the contact from the shapes.
  98608. */
  98609. detach: function () {
  98610. var prev = this.s1Link.prev;
  98611. var next = this.s1Link.next;
  98612. if (prev !== null) prev.next = next;
  98613. if (next !== null) next.prev = prev;
  98614. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  98615. this.s1Link.prev = null;
  98616. this.s1Link.next = null;
  98617. this.s1Link.shape = null;
  98618. this.s1Link.body = null;
  98619. this.shape1.numContacts--;
  98620. prev = this.s2Link.prev;
  98621. next = this.s2Link.next;
  98622. if (prev !== null) prev.next = next;
  98623. if (next !== null) next.prev = prev;
  98624. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  98625. this.s2Link.prev = null;
  98626. this.s2Link.next = null;
  98627. this.s2Link.shape = null;
  98628. this.s2Link.body = null;
  98629. this.shape2.numContacts--;
  98630. prev = this.b1Link.prev;
  98631. next = this.b1Link.next;
  98632. if (prev !== null) prev.next = next;
  98633. if (next !== null) next.prev = prev;
  98634. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  98635. this.b1Link.prev = null;
  98636. this.b1Link.next = null;
  98637. this.b1Link.shape = null;
  98638. this.b1Link.body = null;
  98639. this.body1.numContacts--;
  98640. prev = this.b2Link.prev;
  98641. next = this.b2Link.next;
  98642. if (prev !== null) prev.next = next;
  98643. if (next !== null) next.prev = prev;
  98644. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  98645. this.b2Link.prev = null;
  98646. this.b2Link.next = null;
  98647. this.b2Link.shape = null;
  98648. this.b2Link.body = null;
  98649. this.body2.numContacts--;
  98650. this.manifold.body1 = null;
  98651. this.manifold.body2 = null;
  98652. this.constraint.body1 = null;
  98653. this.constraint.body2 = null;
  98654. this.constraint.detach();
  98655. this.shape1 = null;
  98656. this.shape2 = null;
  98657. this.body1 = null;
  98658. this.body2 = null;
  98659. }
  98660. }
  98661. /**
  98662. * ...
  98663. * @author saharan
  98664. */
  98665. OIMO.ContactConstraint = function (manifold) {
  98666. OIMO.Constraint.call(this);
  98667. // The contact manifold of the constraint.
  98668. this.manifold = manifold;
  98669. // The coefficient of restitution of the constraint.
  98670. this.restitution = NaN;
  98671. // The coefficient of friction of the constraint.
  98672. this.friction = NaN;
  98673. this.p1 = null;
  98674. this.p2 = null;
  98675. this.lv1 = null;
  98676. this.lv2 = null;
  98677. this.av1 = null;
  98678. this.av2 = null;
  98679. this.i1 = null;
  98680. this.i2 = null;
  98681. this.ii1 = null;
  98682. this.ii2 = null;
  98683. this.m1 = NaN;
  98684. this.m2 = NaN;
  98685. this.num = 0;
  98686. this.ps = manifold.points;
  98687. this.cs = new OIMO.ContactPointDataBuffer();
  98688. this.cs.next = new OIMO.ContactPointDataBuffer();
  98689. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  98690. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  98691. }
  98692. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  98693. /**
  98694. * Attach the constraint to the bodies.
  98695. */
  98696. OIMO.ContactConstraint.prototype.attach = function () {
  98697. this.p1 = this.body1.position;
  98698. this.p2 = this.body2.position;
  98699. this.lv1 = this.body1.linearVelocity;
  98700. this.av1 = this.body1.angularVelocity;
  98701. this.lv2 = this.body2.linearVelocity;
  98702. this.av2 = this.body2.angularVelocity;
  98703. this.i1 = this.body1.inverseInertia;
  98704. this.i2 = this.body2.inverseInertia;
  98705. }
  98706. /**
  98707. * Detach the constraint from the bodies.
  98708. */
  98709. OIMO.ContactConstraint.prototype.detach = function () {
  98710. this.p1 = null;
  98711. this.p2 = null;
  98712. this.lv1 = null;
  98713. this.lv2 = null;
  98714. this.av1 = null;
  98715. this.av2 = null;
  98716. this.i1 = null;
  98717. this.i2 = null;
  98718. }
  98719. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  98720. this.m1 = this.body1.inverseMass;
  98721. this.m2 = this.body2.inverseMass;
  98722. this.ii1 = this.i1.clone();
  98723. this.ii2 = this.i2.clone();
  98724. var ii1 = this.ii1.elements;
  98725. var ii2 = this.ii2.elements;
  98726. var p1x = this.p1.x;
  98727. var p1y = this.p1.y;
  98728. var p1z = this.p1.z;
  98729. var p2x = this.p2.x;
  98730. var p2y = this.p2.y;
  98731. var p2z = this.p2.z;
  98732. var m1m2 = this.m1 + this.m2;
  98733. this.num = this.manifold.numPoints;
  98734. var c = this.cs;
  98735. for (var i = 0; i < this.num; i++) {
  98736. var p = this.ps[i];
  98737. var tmp1X;
  98738. var tmp1Y;
  98739. var tmp1Z;
  98740. var tmp2X;
  98741. var tmp2Y;
  98742. var tmp2Z;
  98743. tmp1X = p.position.x;
  98744. tmp1Y = p.position.y;
  98745. tmp1Z = p.position.z;
  98746. var rp1X = tmp1X - p1x;
  98747. var rp1Y = tmp1Y - p1y;
  98748. var rp1Z = tmp1Z - p1z;
  98749. var rp2X = tmp1X - p2x;
  98750. var rp2Y = tmp1Y - p2y;
  98751. var rp2Z = tmp1Z - p2z;
  98752. c.rp1X = rp1X;
  98753. c.rp1Y = rp1Y;
  98754. c.rp1Z = rp1Z;
  98755. c.rp2X = rp2X;
  98756. c.rp2Y = rp2Y;
  98757. c.rp2Z = rp2Z;
  98758. c.norImp = p.normalImpulse;
  98759. c.tanImp = p.tangentImpulse;
  98760. c.binImp = p.binormalImpulse;
  98761. var norX = p.normal.x;
  98762. var norY = p.normal.y;
  98763. var norZ = p.normal.z;
  98764. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  98765. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  98766. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  98767. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  98768. var tanX = rvX - rvn * norX;
  98769. var tanY = rvY - rvn * norY;
  98770. var tanZ = rvZ - rvn * norZ;
  98771. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  98772. if (len > 0.04) {
  98773. len = 1 / OIMO.sqrt(len);
  98774. } else {
  98775. tanX = norY * norX - norZ * norZ;
  98776. tanY = -norZ * norY - norX * norX;
  98777. tanZ = norX * norZ + norY * norY;
  98778. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  98779. }
  98780. tanX *= len;
  98781. tanY *= len;
  98782. tanZ *= len;
  98783. var binX = norY * tanZ - norZ * tanY;
  98784. var binY = norZ * tanX - norX * tanZ;
  98785. var binZ = norX * tanY - norY * tanX;
  98786. c.norX = norX;
  98787. c.norY = norY;
  98788. c.norZ = norZ;
  98789. c.tanX = tanX;
  98790. c.tanY = tanY;
  98791. c.tanZ = tanZ;
  98792. c.binX = binX;
  98793. c.binY = binY;
  98794. c.binZ = binZ;
  98795. c.norU1X = norX * this.m1;
  98796. c.norU1Y = norY * this.m1;
  98797. c.norU1Z = norZ * this.m1;
  98798. c.norU2X = norX * this.m2;
  98799. c.norU2Y = norY * this.m2;
  98800. c.norU2Z = norZ * this.m2;
  98801. c.tanU1X = tanX * this.m1;
  98802. c.tanU1Y = tanY * this.m1;
  98803. c.tanU1Z = tanZ * this.m1;
  98804. c.tanU2X = tanX * this.m2;
  98805. c.tanU2Y = tanY * this.m2;
  98806. c.tanU2Z = tanZ * this.m2;
  98807. c.binU1X = binX * this.m1;
  98808. c.binU1Y = binY * this.m1;
  98809. c.binU1Z = binZ * this.m1;
  98810. c.binU2X = binX * this.m2;
  98811. c.binU2Y = binY * this.m2;
  98812. c.binU2Z = binZ * this.m2;
  98813. var norT1X = rp1Y * norZ - rp1Z * norY;
  98814. var norT1Y = rp1Z * norX - rp1X * norZ;
  98815. var norT1Z = rp1X * norY - rp1Y * norX;
  98816. var norT2X = rp2Y * norZ - rp2Z * norY;
  98817. var norT2Y = rp2Z * norX - rp2X * norZ;
  98818. var norT2Z = rp2X * norY - rp2Y * norX;
  98819. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  98820. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  98821. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  98822. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  98823. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  98824. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  98825. var binT1X = rp1Y * binZ - rp1Z * binY;
  98826. var binT1Y = rp1Z * binX - rp1X * binZ;
  98827. var binT1Z = rp1X * binY - rp1Y * binX;
  98828. var binT2X = rp2Y * binZ - rp2Z * binY;
  98829. var binT2Y = rp2Z * binX - rp2X * binZ;
  98830. var binT2Z = rp2X * binY - rp2Y * binX;
  98831. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98832. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98833. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98834. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98835. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98836. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98837. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98838. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98839. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98840. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98841. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98842. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98843. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98844. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98845. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98846. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98847. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98848. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98849. c.norT1X = norT1X;
  98850. c.norT1Y = norT1Y;
  98851. c.norT1Z = norT1Z;
  98852. c.tanT1X = tanT1X;
  98853. c.tanT1Y = tanT1Y;
  98854. c.tanT1Z = tanT1Z;
  98855. c.binT1X = binT1X;
  98856. c.binT1Y = binT1Y;
  98857. c.binT1Z = binT1Z;
  98858. c.norT2X = norT2X;
  98859. c.norT2Y = norT2Y;
  98860. c.norT2Z = norT2Z;
  98861. c.tanT2X = tanT2X;
  98862. c.tanT2Y = tanT2Y;
  98863. c.tanT2Z = tanT2Z;
  98864. c.binT2X = binT2X;
  98865. c.binT2Y = binT2Y;
  98866. c.binT2Z = binT2Z;
  98867. c.norTU1X = norTU1X;
  98868. c.norTU1Y = norTU1Y;
  98869. c.norTU1Z = norTU1Z;
  98870. c.tanTU1X = tanTU1X;
  98871. c.tanTU1Y = tanTU1Y;
  98872. c.tanTU1Z = tanTU1Z;
  98873. c.binTU1X = binTU1X;
  98874. c.binTU1Y = binTU1Y;
  98875. c.binTU1Z = binTU1Z;
  98876. c.norTU2X = norTU2X;
  98877. c.norTU2Y = norTU2Y;
  98878. c.norTU2Z = norTU2Z;
  98879. c.tanTU2X = tanTU2X;
  98880. c.tanTU2Y = tanTU2Y;
  98881. c.tanTU2Z = tanTU2Z;
  98882. c.binTU2X = binTU2X;
  98883. c.binTU2Y = binTU2Y;
  98884. c.binTU2Z = binTU2Z;
  98885. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98886. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98887. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98888. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98889. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98890. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98891. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98892. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98893. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98894. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98895. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98896. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98897. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  98898. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98899. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98900. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98901. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98902. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98903. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98904. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98905. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98906. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98907. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98908. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98909. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98910. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  98911. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98912. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98913. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98914. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98915. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98916. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98917. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98918. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98919. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98920. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98921. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98922. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98923. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  98924. c.norDen = norDen;
  98925. c.tanDen = tanDen;
  98926. c.binDen = binDen;
  98927. if (p.warmStarted) {
  98928. var norImp = p.normalImpulse;
  98929. this.lv1.x += c.norU1X * norImp;
  98930. this.lv1.y += c.norU1Y * norImp;
  98931. this.lv1.z += c.norU1Z * norImp;
  98932. this.av1.x += norTU1X * norImp;
  98933. this.av1.y += norTU1Y * norImp;
  98934. this.av1.z += norTU1Z * norImp;
  98935. this.lv2.x -= c.norU2X * norImp;
  98936. this.lv2.y -= c.norU2Y * norImp;
  98937. this.lv2.z -= c.norU2Z * norImp;
  98938. this.av2.x -= norTU2X * norImp;
  98939. this.av2.y -= norTU2Y * norImp;
  98940. this.av2.z -= norTU2Z * norImp;
  98941. c.norImp = norImp;
  98942. c.tanImp = 0;
  98943. c.binImp = 0;
  98944. rvn = 0; // disable bouncing
  98945. } else {
  98946. c.norImp = 0;
  98947. c.tanImp = 0;
  98948. c.binImp = 0;
  98949. }
  98950. if (rvn > -1) {
  98951. rvn = 0; // disable bouncing
  98952. }
  98953. var norTar = this.restitution * -rvn;
  98954. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  98955. if (norTar < sepV) norTar = sepV;
  98956. c.norTar = norTar;
  98957. c.last = i == this.num - 1;
  98958. c = c.next;
  98959. }
  98960. }
  98961. OIMO.ContactConstraint.prototype.solve = function () {
  98962. var lv1x = this.lv1.x;
  98963. var lv1y = this.lv1.y;
  98964. var lv1z = this.lv1.z;
  98965. var lv2x = this.lv2.x;
  98966. var lv2y = this.lv2.y;
  98967. var lv2z = this.lv2.z;
  98968. var av1x = this.av1.x;
  98969. var av1y = this.av1.y;
  98970. var av1z = this.av1.z;
  98971. var av2x = this.av2.x;
  98972. var av2y = this.av2.y;
  98973. var av2z = this.av2.z;
  98974. var c = this.cs;
  98975. while (true) {
  98976. var oldImp1;
  98977. var newImp1;
  98978. var oldImp2;
  98979. var newImp2;
  98980. var rvn;
  98981. var norImp = c.norImp;
  98982. var tanImp = c.tanImp;
  98983. var binImp = c.binImp;
  98984. var max = -norImp * this.friction;
  98985. var rvX = lv2x - lv1x;
  98986. var rvY = lv2y - lv1y;
  98987. var rvZ = lv2z - lv1z;
  98988. rvn =
  98989. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  98990. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  98991. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  98992. ;
  98993. oldImp1 = tanImp;
  98994. newImp1 = rvn * c.tanDen;
  98995. tanImp += newImp1;
  98996. rvn =
  98997. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  98998. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  98999. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  99000. ;
  99001. oldImp2 = binImp;
  99002. newImp2 = rvn * c.binDen;
  99003. binImp += newImp2;
  99004. // cone friction clamp
  99005. var len = tanImp * tanImp + binImp * binImp;
  99006. if (len > max * max) {
  99007. len = max / OIMO.sqrt(len);
  99008. tanImp *= len;
  99009. binImp *= len;
  99010. }
  99011. newImp1 = tanImp - oldImp1;
  99012. newImp2 = binImp - oldImp2;
  99013. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  99014. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  99015. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  99016. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  99017. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  99018. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  99019. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  99020. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  99021. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  99022. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  99023. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  99024. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  99025. // restitution part
  99026. rvn =
  99027. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  99028. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  99029. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  99030. oldImp1 = norImp;
  99031. newImp1 = (rvn - c.norTar) * c.norDen;
  99032. norImp += newImp1;
  99033. if (norImp > 0) norImp = 0;
  99034. newImp1 = norImp - oldImp1;
  99035. lv1x += c.norU1X * newImp1;
  99036. lv1y += c.norU1Y * newImp1;
  99037. lv1z += c.norU1Z * newImp1;
  99038. av1x += c.norTU1X * newImp1;
  99039. av1y += c.norTU1Y * newImp1;
  99040. av1z += c.norTU1Z * newImp1;
  99041. lv2x -= c.norU2X * newImp1;
  99042. lv2y -= c.norU2Y * newImp1;
  99043. lv2z -= c.norU2Z * newImp1;
  99044. av2x -= c.norTU2X * newImp1;
  99045. av2y -= c.norTU2Y * newImp1;
  99046. av2z -= c.norTU2Z * newImp1;
  99047. c.norImp = norImp;
  99048. c.tanImp = tanImp;
  99049. c.binImp = binImp;
  99050. if (c.last) break;
  99051. c = c.next;
  99052. }
  99053. this.lv1.x = lv1x;
  99054. this.lv1.y = lv1y;
  99055. this.lv1.z = lv1z;
  99056. this.lv2.x = lv2x;
  99057. this.lv2.y = lv2y;
  99058. this.lv2.z = lv2z;
  99059. this.av1.x = av1x;
  99060. this.av1.y = av1y;
  99061. this.av1.z = av1z;
  99062. this.av2.x = av2x;
  99063. this.av2.y = av2y;
  99064. this.av2.z = av2z;
  99065. }
  99066. OIMO.ContactConstraint.prototype.postSolve = function () {
  99067. var c = this.cs;
  99068. var i = this.num;
  99069. while (i--) {
  99070. //for(var i=0;i<this.num;i++){
  99071. var p = this.ps[i];
  99072. p.normal.x = c.norX;
  99073. p.normal.y = c.norY;
  99074. p.normal.z = c.norZ;
  99075. p.tangent.x = c.tanX;
  99076. p.tangent.y = c.tanY;
  99077. p.tangent.z = c.tanZ;
  99078. p.binormal.x = c.binX;
  99079. p.binormal.y = c.binY;
  99080. p.binormal.z = c.binZ;
  99081. p.normalImpulse = c.norImp;
  99082. p.tangentImpulse = c.tanImp;
  99083. p.binormalImpulse = c.binImp;
  99084. p.normalDenominator = c.norDen;
  99085. p.tangentDenominator = c.tanDen;
  99086. p.binormalDenominator = c.binDen;
  99087. c = c.next;
  99088. }
  99089. }
  99090. /**
  99091. * A link list of contacts.
  99092. * @author saharan
  99093. */
  99094. OIMO.ContactLink = function (contact) {
  99095. // The previous contact link.
  99096. this.prev = null;
  99097. // The next contact link.
  99098. this.next = null;
  99099. // The shape of the contact.
  99100. this.shape = null;
  99101. // The other rigid body.
  99102. this.body = null;
  99103. // The contact of the link.
  99104. this.contact = contact;
  99105. }
  99106. /**
  99107. * A contact manifold between two shapes.
  99108. * @author saharan
  99109. */
  99110. OIMO.ContactManifold = function () {
  99111. // The first rigid body.
  99112. this.body1 = null;
  99113. // The second rigid body.
  99114. this.body2 = null;
  99115. // The number of manifold points.
  99116. this.numPoints = 0;
  99117. // The manifold points.
  99118. this.points = [];
  99119. this.points.length = 4;
  99120. this.points[0] = new OIMO.ManifoldPoint();
  99121. this.points[1] = new OIMO.ManifoldPoint();
  99122. this.points[2] = new OIMO.ManifoldPoint();
  99123. this.points[3] = new OIMO.ManifoldPoint();
  99124. }
  99125. OIMO.ContactManifold.prototype = {
  99126. constructor: OIMO.ContactManifold,
  99127. /**
  99128. * Reset the manifold.
  99129. * @param shape1
  99130. * @param shape2
  99131. */
  99132. reset: function (shape1, shape2) {
  99133. this.body1 = shape1.parent;
  99134. this.body2 = shape2.parent;
  99135. this.numPoints = 0;
  99136. },
  99137. /**
  99138. * Add a point into this manifold.
  99139. * @param x
  99140. * @param y
  99141. * @param z
  99142. * @param normalX
  99143. * @param normalY
  99144. * @param normalZ
  99145. * @param penetration
  99146. * @param flip
  99147. */
  99148. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  99149. var p = this.points[this.numPoints++];
  99150. p.position.x = x;
  99151. p.position.y = y;
  99152. p.position.z = z;
  99153. var r = this.body1.rotation;
  99154. var rx = x - this.body1.position.x;
  99155. var ry = y - this.body1.position.y;
  99156. var rz = z - this.body1.position.z;
  99157. var tr = r.elements;
  99158. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  99159. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  99160. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  99161. r = this.body2.rotation;
  99162. rx = x - this.body2.position.x;
  99163. ry = y - this.body2.position.y;
  99164. rz = z - this.body2.position.z;
  99165. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  99166. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  99167. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  99168. p.normalImpulse = 0;
  99169. if (flip) {
  99170. p.normal.x = -normalX;
  99171. p.normal.y = -normalY;
  99172. p.normal.z = -normalZ;
  99173. } else {
  99174. p.normal.x = normalX;
  99175. p.normal.y = normalY;
  99176. p.normal.z = normalZ;
  99177. }
  99178. p.penetration = penetration;
  99179. p.warmStarted = false;
  99180. }
  99181. }
  99182. OIMO.ContactPointDataBuffer = function () {
  99183. this.norX = NaN;
  99184. this.norY = NaN;
  99185. this.norZ = NaN;
  99186. this.tanX = NaN;
  99187. this.tanY = NaN;
  99188. this.tanZ = NaN;
  99189. this.binX = NaN;
  99190. this.binY = NaN;
  99191. this.binZ = NaN;
  99192. this.rp1X = NaN;
  99193. this.rp1Y = NaN;
  99194. this.rp1Z = NaN;
  99195. this.rp2X = NaN;
  99196. this.rp2Y = NaN;
  99197. this.rp2Z = NaN;
  99198. this.norU1X = NaN;
  99199. this.norU1Y = NaN;
  99200. this.norU1Z = NaN;
  99201. this.norU2X = NaN;
  99202. this.norU2Y = NaN;
  99203. this.norU2Z = NaN;
  99204. this.tanU1X = NaN;
  99205. this.tanU1Y = NaN;
  99206. this.tanU1Z = NaN;
  99207. this.tanU2X = NaN;
  99208. this.tanU2Y = NaN;
  99209. this.tanU2Z = NaN;
  99210. this.binU1X = NaN;
  99211. this.binU1Y = NaN;
  99212. this.binU1Z = NaN;
  99213. this.binU2X = NaN;
  99214. this.binU2Y = NaN;
  99215. this.binU2Z = NaN;
  99216. this.norT1X = NaN;
  99217. this.norT1Y = NaN;
  99218. this.norT1Z = NaN;
  99219. this.norT2X = NaN;
  99220. this.norT2Y = NaN;
  99221. this.norT2Z = NaN;
  99222. this.tanT1X = NaN;
  99223. this.tanT1Y = NaN;
  99224. this.tanT1Z = NaN;
  99225. this.tanT2X = NaN;
  99226. this.tanT2Y = NaN;
  99227. this.tanT2Z = NaN;
  99228. this.binT1X = NaN;
  99229. this.binT1Y = NaN;
  99230. this.binT1Z = NaN;
  99231. this.binT2X = NaN;
  99232. this.binT2Y = NaN;
  99233. this.binT2Z = NaN;
  99234. this.norTU1X = NaN;
  99235. this.norTU1Y = NaN;
  99236. this.norTU1Z = NaN;
  99237. this.norTU2X = NaN;
  99238. this.norTU2Y = NaN;
  99239. this.norTU2Z = NaN;
  99240. this.tanTU1X = NaN;
  99241. this.tanTU1Y = NaN;
  99242. this.tanTU1Z = NaN;
  99243. this.tanTU2X = NaN;
  99244. this.tanTU2Y = NaN;
  99245. this.tanTU2Z = NaN;
  99246. this.binTU1X = NaN;
  99247. this.binTU1Y = NaN;
  99248. this.binTU1Z = NaN;
  99249. this.binTU2X = NaN;
  99250. this.binTU2Y = NaN;
  99251. this.binTU2Z = NaN;
  99252. this.norImp = NaN;
  99253. this.tanImp = NaN;
  99254. this.binImp = NaN;
  99255. this.norDen = NaN;
  99256. this.tanDen = NaN;
  99257. this.binDen = NaN;
  99258. this.norTar = NaN;
  99259. this.next = null;
  99260. this.last = false;
  99261. }
  99262. OIMO.ImpulseDataBuffer = function () {
  99263. this.lp1X = NaN;
  99264. this.lp1Y = NaN;
  99265. this.lp1Z = NaN;
  99266. this.lp2X = NaN;
  99267. this.lp2Y = NaN;
  99268. this.lp2Z = NaN;
  99269. this.impulse = NaN;
  99270. }
  99271. /**
  99272. * The class holds details of the contact point.
  99273. * @author saharan
  99274. */
  99275. OIMO.ManifoldPoint = function () {
  99276. // Whether this manifold point is persisting or not.
  99277. this.warmStarted = false;
  99278. // The position of this manifold point.
  99279. this.position = new OIMO.Vec3();
  99280. // The position in the first shape's coordinate.
  99281. this.localPoint1 = new OIMO.Vec3();
  99282. // The position in the second shape's coordinate.
  99283. this.localPoint2 = new OIMO.Vec3();
  99284. // The normal vector of this manifold point.
  99285. this.normal = new OIMO.Vec3();
  99286. // The tangent vector of this manifold point.
  99287. this.tangent = new OIMO.Vec3();
  99288. // The binormal vector of this manifold point.
  99289. this.binormal = new OIMO.Vec3();
  99290. // The impulse in normal direction.
  99291. this.normalImpulse = 0;
  99292. // The impulse in tangent direction.
  99293. this.tangentImpulse = 0;
  99294. // The impulse in binormal direction.
  99295. this.binormalImpulse = 0;
  99296. // The denominator in normal direction.
  99297. this.normalDenominator = 0;
  99298. // The denominator in tangent direction.
  99299. this.tangentDenominator = 0;
  99300. // The denominator in binormal direction.
  99301. this.binormalDenominator = 0;
  99302. // The depth of penetration.
  99303. this.penetration = 0;
  99304. }
  99305. /**
  99306. * This class holds mass information of a shape.
  99307. * @author saharan
  99308. */
  99309. OIMO.MassInfo = function () {
  99310. // Mass of the shape.
  99311. this.mass = 0;
  99312. // The moment inertia of the shape.
  99313. this.inertia = new OIMO.Mat33();
  99314. };
  99315. /**
  99316. * A shape is used to detect collisions of rigid bodies.
  99317. * @author saharan
  99318. * @author lo-th
  99319. */
  99320. OIMO.Shape = function (config) {
  99321. this.type = OIMO.SHAPE_NULL;
  99322. // The global identification of the shape should be unique to the shape.
  99323. this.id = OIMO.nextID++;
  99324. // The previous shape in parent rigid body.
  99325. this.prev = null;
  99326. // The next shape in parent rigid body.
  99327. this.next = null;
  99328. // The proxy of the shape used for broad-phase collision detection.
  99329. this.proxy = null;
  99330. // The parent rigid body of the shape.
  99331. this.parent = null;
  99332. // The linked list of the contacts with the shape.
  99333. this.contactLink = null;
  99334. // The number of the contacts with the shape.
  99335. this.numContacts = 0;
  99336. // The center of gravity of the shape in world coordinate system.
  99337. this.position = new OIMO.Vec3();
  99338. // The rotation matrix of the shape in world coordinate system
  99339. this.rotation = new OIMO.Mat33();
  99340. // The position of the shape in parent's coordinate system.
  99341. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  99342. // The rotation matrix of the shape in parent's coordinate system.
  99343. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  99344. // The axis-aligned bounding box of the shape.
  99345. this.aabb = new OIMO.AABB();
  99346. // The density of the shape.
  99347. this.density = config.density;
  99348. // The coefficient of friction of the shape.
  99349. this.friction = config.friction;
  99350. // The coefficient of restitution of the shape.
  99351. this.restitution = config.restitution;
  99352. // The bits of the collision groups to which the shape belongs.
  99353. this.belongsTo = config.belongsTo;
  99354. // The bits of the collision groups with which the shape collides.
  99355. this.collidesWith = config.collidesWith;
  99356. };
  99357. OIMO.Shape.prototype = {
  99358. constructor: OIMO.Shape,
  99359. // Calculate the mass information of the shape.
  99360. calculateMassInfo: function (out) {
  99361. OIMO.Error("Shape", "Inheritance error.");
  99362. },
  99363. // Update the proxy of the shape.
  99364. updateProxy: function () {
  99365. OIMO.Error("Shape", "Inheritance error.");
  99366. }
  99367. };
  99368. /**
  99369. * A shape configuration holds common configuration data for constructing a shape.
  99370. * Shape configurations can be reused safely.
  99371. * @author saharan
  99372. */
  99373. OIMO.ShapeConfig = function () {
  99374. // The position of the shape in parent's coordinate system.
  99375. this.relativePosition = new OIMO.Vec3();
  99376. // The rotation matrix of the shape in parent's coordinate system.
  99377. this.relativeRotation = new OIMO.Mat33();
  99378. // The coefficient of friction of the shape.
  99379. this.friction = 0.4;
  99380. // The coefficient of restitution of the shape.
  99381. this.restitution = 0.2;
  99382. // The density of the shape.
  99383. this.density = 1;
  99384. // The bits of the collision groups to which the shape belongs.
  99385. this.belongsTo = 1;
  99386. // The bits of the collision groups with which the shape collides.
  99387. this.collidesWith = 0xffffffff;
  99388. };
  99389. /**
  99390. * A box shape.
  99391. * @author saharan
  99392. * @author lo-th
  99393. */
  99394. OIMO.BoxShape = function (config, Width, Height, Depth) {
  99395. OIMO.Shape.call(this, config);
  99396. this.type = OIMO.SHAPE_BOX;
  99397. // The width of the box.
  99398. this.width = Width;
  99399. // The height of the box.
  99400. this.height = Height;
  99401. // The depth of the box.
  99402. this.depth = Depth;
  99403. // The half-width of the box.
  99404. this.halfWidth = Width * 0.5;
  99405. // The half-height of the box.
  99406. this.halfHeight = Height * 0.5;
  99407. // The half-depth of the box.
  99408. this.halfDepth = Depth * 0.5;
  99409. this.dimentions = new OIMO_ARRAY_TYPE(18);
  99410. this.elements = new OIMO_ARRAY_TYPE(24);
  99411. };
  99412. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  99413. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  99414. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  99415. var mass = this.width * this.height * this.depth * this.density;
  99416. var divid = 1 / 12;
  99417. out.mass = mass;
  99418. out.inertia.set(
  99419. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  99420. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  99421. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  99422. );
  99423. };
  99424. OIMO.BoxShape.prototype.updateProxy = function () {
  99425. var te = this.rotation.elements;
  99426. var di = this.dimentions;
  99427. // Width
  99428. di[0] = te[0];
  99429. di[1] = te[3];
  99430. di[2] = te[6];
  99431. // Height
  99432. di[3] = te[1];
  99433. di[4] = te[4];
  99434. di[5] = te[7];
  99435. // Depth
  99436. di[6] = te[2];
  99437. di[7] = te[5];
  99438. di[8] = te[8];
  99439. // halp Width
  99440. di[9] = te[0] * this.halfWidth;
  99441. di[10] = te[3] * this.halfWidth;
  99442. di[11] = te[6] * this.halfWidth;
  99443. // halp Height
  99444. di[12] = te[1] * this.halfHeight;
  99445. di[13] = te[4] * this.halfHeight;
  99446. di[14] = te[7] * this.halfHeight;
  99447. // halp Depth
  99448. di[15] = te[2] * this.halfDepth;
  99449. di[16] = te[5] * this.halfDepth;
  99450. di[17] = te[8] * this.halfDepth;
  99451. var wx = di[9];
  99452. var wy = di[10];
  99453. var wz = di[11];
  99454. var hx = di[12];
  99455. var hy = di[13];
  99456. var hz = di[14];
  99457. var dx = di[15];
  99458. var dy = di[16];
  99459. var dz = di[17];
  99460. var x = this.position.x;
  99461. var y = this.position.y;
  99462. var z = this.position.z;
  99463. var v = this.elements;
  99464. //v1
  99465. v[0] = x + wx + hx + dx;
  99466. v[1] = y + wy + hy + dy;
  99467. v[2] = z + wz + hz + dz;
  99468. //v2
  99469. v[3] = x + wx + hx - dx;
  99470. v[4] = y + wy + hy - dy;
  99471. v[5] = z + wz + hz - dz;
  99472. //v3
  99473. v[6] = x + wx - hx + dx;
  99474. v[7] = y + wy - hy + dy;
  99475. v[8] = z + wz - hz + dz;
  99476. //v4
  99477. v[9] = x + wx - hx - dx;
  99478. v[10] = y + wy - hy - dy;
  99479. v[11] = z + wz - hz - dz;
  99480. //v5
  99481. v[12] = x - wx + hx + dx;
  99482. v[13] = y - wy + hy + dy;
  99483. v[14] = z - wz + hz + dz;
  99484. //v6
  99485. v[15] = x - wx + hx - dx;
  99486. v[16] = y - wy + hy - dy;
  99487. v[17] = z - wz + hz - dz;
  99488. //v7
  99489. v[18] = x - wx - hx + dx;
  99490. v[19] = y - wy - hy + dy;
  99491. v[20] = z - wz - hz + dz;
  99492. //v8
  99493. v[21] = x - wx - hx - dx;
  99494. v[22] = y - wy - hy - dy;
  99495. v[23] = z - wz - hz - dz;
  99496. var w = di[9] < 0 ? -di[9] : di[9];
  99497. var h = di[10] < 0 ? -di[10] : di[10];
  99498. var d = di[11] < 0 ? -di[11] : di[11];
  99499. w = di[12] < 0 ? w - di[12] : w + di[12];
  99500. h = di[13] < 0 ? h - di[13] : h + di[13];
  99501. d = di[14] < 0 ? d - di[14] : d + di[14];
  99502. w = di[15] < 0 ? w - di[15] : w + di[15];
  99503. h = di[16] < 0 ? h - di[16] : h + di[16];
  99504. d = di[17] < 0 ? d - di[17] : d + di[17];
  99505. var p = OIMO.AABB_PROX;
  99506. this.aabb.set(
  99507. this.position.x - w - p, this.position.x + w + p,
  99508. this.position.y - h - p, this.position.y + h + p,
  99509. this.position.z - d - p, this.position.z + d + p
  99510. );
  99511. if (this.proxy != null) this.proxy.update();
  99512. };
  99513. /**
  99514. * A sphere shape.
  99515. * @author saharan
  99516. * @author lo-th
  99517. */
  99518. OIMO.SphereShape = function (config, radius) {
  99519. OIMO.Shape.call(this, config);
  99520. this.type = OIMO.SHAPE_SPHERE;
  99521. // The radius of the shape.
  99522. this.radius = radius;
  99523. };
  99524. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  99525. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  99526. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  99527. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  99528. out.mass = mass;
  99529. var inertia = mass * this.radius * this.radius * 0.4;
  99530. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  99531. };
  99532. OIMO.SphereShape.prototype.updateProxy = function () {
  99533. var p = OIMO.AABB_PROX;
  99534. this.aabb.set(
  99535. this.position.x - this.radius - p, this.position.x + this.radius + p,
  99536. this.position.y - this.radius - p, this.position.y + this.radius + p,
  99537. this.position.z - this.radius - p, this.position.z + this.radius + p
  99538. );
  99539. if (this.proxy != null) this.proxy.update();
  99540. };
  99541. /**
  99542. * A cylinder shap.
  99543. * @author saharan
  99544. * @author lo-th
  99545. */
  99546. OIMO.CylinderShape = function (config, radius, height) {
  99547. OIMO.Shape.call(this, config);
  99548. this.type = OIMO.SHAPE_CYLINDER;
  99549. this.radius = radius;
  99550. this.height = height;
  99551. this.halfHeight = height * 0.5;
  99552. this.normalDirection = new OIMO.Vec3();
  99553. this.halfDirection = new OIMO.Vec3();
  99554. };
  99555. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  99556. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  99557. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  99558. var rsq = this.radius * this.radius;
  99559. var mass = OIMO.PI * rsq * this.height * this.density;
  99560. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  99561. var inertiaY = 0.5 * rsq;
  99562. out.mass = mass;
  99563. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  99564. };
  99565. OIMO.CylinderShape.prototype.updateProxy = function () {
  99566. var te = this.rotation.elements;
  99567. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  99568. xx = te[1] * te[1];
  99569. yy = te[4] * te[4];
  99570. zz = te[7] * te[7];
  99571. this.normalDirection.set(te[1], te[4], te[7]);
  99572. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  99573. wx = 1 - xx;
  99574. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  99575. if (len > 0) len = this.radius / len;
  99576. wx *= len;
  99577. hy = 1 - yy;
  99578. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  99579. if (len > 0) len = this.radius / len;
  99580. hy *= len;
  99581. dz = 1 - zz;
  99582. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  99583. if (len > 0) len = this.radius / len;
  99584. dz *= len;
  99585. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  99586. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  99587. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  99588. w = wx < 0 ? w - wx : w + wx;
  99589. h = hy < 0 ? h - hy : h + hy;
  99590. d = dz < 0 ? d - dz : d + dz;
  99591. p = OIMO.AABB_PROX;
  99592. this.aabb.set(
  99593. this.position.x - w - p, this.position.x + w + p,
  99594. this.position.y - h - p, this.position.y + h + p,
  99595. this.position.z - d - p, this.position.z + d + p
  99596. );
  99597. if (this.proxy != null) this.proxy.update();
  99598. };
  99599. /**
  99600. * A tetra shape.
  99601. * @author xprogram
  99602. */
  99603. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  99604. OIMO.Shape.call(this, config);
  99605. this.type = OIMO.SHAPE_TETRA;
  99606. // Vertices and faces of tetra
  99607. this.verts = [p1, p2, p3, p4];
  99608. this.faces = [
  99609. mtri(0, 1, 2),
  99610. mtri(1, 2, 3),
  99611. mtri(2, 3, 4),
  99612. mtri(4, 0, 1),
  99613. ];
  99614. };
  99615. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  99616. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  99617. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  99618. // I guess you could calculate box mass and split it
  99619. // in half for the tetra...
  99620. };
  99621. OIMO.TetraShape.prototype.updateProxy = function () {
  99622. this.aabb.setFromPoints(this.verts);
  99623. if (this.proxy !== null)
  99624. this.proxy.update();
  99625. };
  99626. function mtri(a, b, c) {
  99627. return { a: a, b: b, c: c };
  99628. }
  99629. OIMO.CollisionDetector = function () {
  99630. this.flip = false;
  99631. };
  99632. OIMO.CollisionDetector.prototype = {
  99633. constructor: OIMO.CollisionDetector,
  99634. detectCollision: function (shape1, shape2, manifold) {
  99635. OIMO.Error("CollisionDetector", "Inheritance error.");
  99636. }
  99637. };
  99638. /**
  99639. * A collision detector which detects collisions between two boxes.
  99640. * @author saharan
  99641. */
  99642. OIMO.BoxBoxCollisionDetector = function () {
  99643. OIMO.CollisionDetector.call(this);
  99644. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  99645. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  99646. this.used = new OIMO_ARRAY_TYPE(8);
  99647. this.INF = 1 / 0;
  99648. };
  99649. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99650. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  99651. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99652. // What you are doing
  99653. // · I to prepare a separate axis of the fifteen
  99654. //-Six in each of three normal vectors of the xyz direction of the box both
  99655. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  99656. // · Calculate the depth to the separation axis
  99657. // Calculates the distance using the inner product and put the amount of embedment
  99658. // · However a vertical separation axis and side to weight a little to avoid vibration
  99659. // And end when there is a separate axis that is remote even one
  99660. // · I look for separation axis with little to dent most
  99661. // Men and if separation axis of the first six - end collision
  99662. // Heng If it separate axis of nine other - side collision
  99663. // Heng - case of a side collision
  99664. // · Find points of two sides on which you made ​​the separation axis
  99665. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  99666. //-Surface - the case of the plane crash
  99667. //-Box A, box B and the other a box of better made ​​a separate axis
  99668. // • The surface A and the plane that made the separation axis of the box A, and B to the surface the face of the box B close in the opposite direction to the most isolated axis
  99669. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  99670. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  99671. // • If more than one candidate 5 exists, scraping up to four
  99672. // For potential collision points of all, to examine the distance between the surface A
  99673. // • If you were on the inside surface of A, and the collision point
  99674. var b1;
  99675. var b2;
  99676. if (shape1.id < shape2.id) {
  99677. b1 = (shape1);
  99678. b2 = (shape2);
  99679. } else {
  99680. b1 = (shape2);
  99681. b2 = (shape1);
  99682. }
  99683. var V1 = b1.elements;
  99684. var V2 = b2.elements;
  99685. var D1 = b1.dimentions;
  99686. var D2 = b2.dimentions;
  99687. var p1 = b1.position;
  99688. var p2 = b2.position;
  99689. var p1x = p1.x;
  99690. var p1y = p1.y;
  99691. var p1z = p1.z;
  99692. var p2x = p2.x;
  99693. var p2y = p2.y;
  99694. var p2z = p2.z;
  99695. // diff
  99696. var dx = p2x - p1x;
  99697. var dy = p2y - p1y;
  99698. var dz = p2z - p1z;
  99699. // distance
  99700. var w1 = b1.halfWidth;
  99701. var h1 = b1.halfHeight;
  99702. var d1 = b1.halfDepth;
  99703. var w2 = b2.halfWidth;
  99704. var h2 = b2.halfHeight;
  99705. var d2 = b2.halfDepth;
  99706. // direction
  99707. // ----------------------------
  99708. // 15 separating axes
  99709. // 1~6: face
  99710. // 7~f: edge
  99711. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  99712. // ----------------------------
  99713. var a1x = D1[0];
  99714. var a1y = D1[1];
  99715. var a1z = D1[2];
  99716. var a2x = D1[3];
  99717. var a2y = D1[4];
  99718. var a2z = D1[5];
  99719. var a3x = D1[6];
  99720. var a3y = D1[7];
  99721. var a3z = D1[8];
  99722. var d1x = D1[9];
  99723. var d1y = D1[10];
  99724. var d1z = D1[11];
  99725. var d2x = D1[12];
  99726. var d2y = D1[13];
  99727. var d2z = D1[14];
  99728. var d3x = D1[15];
  99729. var d3y = D1[16];
  99730. var d3z = D1[17];
  99731. var a4x = D2[0];
  99732. var a4y = D2[1];
  99733. var a4z = D2[2];
  99734. var a5x = D2[3];
  99735. var a5y = D2[4];
  99736. var a5z = D2[5];
  99737. var a6x = D2[6];
  99738. var a6y = D2[7];
  99739. var a6z = D2[8];
  99740. var d4x = D2[9];
  99741. var d4y = D2[10];
  99742. var d4z = D2[11];
  99743. var d5x = D2[12];
  99744. var d5y = D2[13];
  99745. var d5z = D2[14];
  99746. var d6x = D2[15];
  99747. var d6y = D2[16];
  99748. var d6z = D2[17];
  99749. var a7x = a1y * a4z - a1z * a4y;
  99750. var a7y = a1z * a4x - a1x * a4z;
  99751. var a7z = a1x * a4y - a1y * a4x;
  99752. var a8x = a1y * a5z - a1z * a5y;
  99753. var a8y = a1z * a5x - a1x * a5z;
  99754. var a8z = a1x * a5y - a1y * a5x;
  99755. var a9x = a1y * a6z - a1z * a6y;
  99756. var a9y = a1z * a6x - a1x * a6z;
  99757. var a9z = a1x * a6y - a1y * a6x;
  99758. var aax = a2y * a4z - a2z * a4y;
  99759. var aay = a2z * a4x - a2x * a4z;
  99760. var aaz = a2x * a4y - a2y * a4x;
  99761. var abx = a2y * a5z - a2z * a5y;
  99762. var aby = a2z * a5x - a2x * a5z;
  99763. var abz = a2x * a5y - a2y * a5x;
  99764. var acx = a2y * a6z - a2z * a6y;
  99765. var acy = a2z * a6x - a2x * a6z;
  99766. var acz = a2x * a6y - a2y * a6x;
  99767. var adx = a3y * a4z - a3z * a4y;
  99768. var ady = a3z * a4x - a3x * a4z;
  99769. var adz = a3x * a4y - a3y * a4x;
  99770. var aex = a3y * a5z - a3z * a5y;
  99771. var aey = a3z * a5x - a3x * a5z;
  99772. var aez = a3x * a5y - a3y * a5x;
  99773. var afx = a3y * a6z - a3z * a6y;
  99774. var afy = a3z * a6x - a3x * a6z;
  99775. var afz = a3x * a6y - a3y * a6x;
  99776. // right or left flags
  99777. var right1;
  99778. var right2;
  99779. var right3;
  99780. var right4;
  99781. var right5;
  99782. var right6;
  99783. var right7;
  99784. var right8;
  99785. var right9;
  99786. var righta;
  99787. var rightb;
  99788. var rightc;
  99789. var rightd;
  99790. var righte;
  99791. var rightf;
  99792. // overlapping distances
  99793. var overlap1;
  99794. var overlap2;
  99795. var overlap3;
  99796. var overlap4;
  99797. var overlap5;
  99798. var overlap6;
  99799. var overlap7;
  99800. var overlap8;
  99801. var overlap9;
  99802. var overlapa;
  99803. var overlapb;
  99804. var overlapc;
  99805. var overlapd;
  99806. var overlape;
  99807. var overlapf;
  99808. // invalid flags
  99809. var invalid7 = false;
  99810. var invalid8 = false;
  99811. var invalid9 = false;
  99812. var invalida = false;
  99813. var invalidb = false;
  99814. var invalidc = false;
  99815. var invalidd = false;
  99816. var invalide = false;
  99817. var invalidf = false;
  99818. // temporary variables
  99819. var len;
  99820. var len1;
  99821. var len2;
  99822. var dot1;
  99823. var dot2;
  99824. var dot3;
  99825. // try axis 1
  99826. len = a1x * dx + a1y * dy + a1z * dz;
  99827. right1 = len > 0;
  99828. if (!right1) len = -len;
  99829. len1 = w1;
  99830. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  99831. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  99832. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  99833. if (dot1 < 0) dot1 = -dot1;
  99834. if (dot2 < 0) dot2 = -dot2;
  99835. if (dot3 < 0) dot3 = -dot3;
  99836. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99837. overlap1 = len - len1 - len2;
  99838. if (overlap1 > 0) return;
  99839. // try axis 2
  99840. len = a2x * dx + a2y * dy + a2z * dz;
  99841. right2 = len > 0;
  99842. if (!right2) len = -len;
  99843. len1 = h1;
  99844. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  99845. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  99846. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  99847. if (dot1 < 0) dot1 = -dot1;
  99848. if (dot2 < 0) dot2 = -dot2;
  99849. if (dot3 < 0) dot3 = -dot3;
  99850. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99851. overlap2 = len - len1 - len2;
  99852. if (overlap2 > 0) return;
  99853. // try axis 3
  99854. len = a3x * dx + a3y * dy + a3z * dz;
  99855. right3 = len > 0;
  99856. if (!right3) len = -len;
  99857. len1 = d1;
  99858. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  99859. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  99860. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  99861. if (dot1 < 0) dot1 = -dot1;
  99862. if (dot2 < 0) dot2 = -dot2;
  99863. if (dot3 < 0) dot3 = -dot3;
  99864. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99865. overlap3 = len - len1 - len2;
  99866. if (overlap3 > 0) return;
  99867. // try axis 4
  99868. len = a4x * dx + a4y * dy + a4z * dz;
  99869. right4 = len > 0;
  99870. if (!right4) len = -len;
  99871. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  99872. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  99873. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  99874. if (dot1 < 0) dot1 = -dot1;
  99875. if (dot2 < 0) dot2 = -dot2;
  99876. if (dot3 < 0) dot3 = -dot3;
  99877. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99878. len2 = w2;
  99879. overlap4 = (len - len1 - len2) * 1.0;
  99880. if (overlap4 > 0) return;
  99881. // try axis 5
  99882. len = a5x * dx + a5y * dy + a5z * dz;
  99883. right5 = len > 0;
  99884. if (!right5) len = -len;
  99885. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  99886. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  99887. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  99888. if (dot1 < 0) dot1 = -dot1;
  99889. if (dot2 < 0) dot2 = -dot2;
  99890. if (dot3 < 0) dot3 = -dot3;
  99891. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99892. len2 = h2;
  99893. overlap5 = (len - len1 - len2) * 1.0;
  99894. if (overlap5 > 0) return;
  99895. // try axis 6
  99896. len = a6x * dx + a6y * dy + a6z * dz;
  99897. right6 = len > 0;
  99898. if (!right6) len = -len;
  99899. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  99900. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  99901. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  99902. if (dot1 < 0) dot1 = -dot1;
  99903. if (dot2 < 0) dot2 = -dot2;
  99904. if (dot3 < 0) dot3 = -dot3;
  99905. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99906. len2 = d2;
  99907. overlap6 = (len - len1 - len2) * 1.0;
  99908. if (overlap6 > 0) return;
  99909. // try axis 7
  99910. len = a7x * a7x + a7y * a7y + a7z * a7z;
  99911. if (len > 1e-5) {
  99912. len = 1 / OIMO.sqrt(len);
  99913. a7x *= len;
  99914. a7y *= len;
  99915. a7z *= len;
  99916. len = a7x * dx + a7y * dy + a7z * dz;
  99917. right7 = len > 0;
  99918. if (!right7) len = -len;
  99919. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  99920. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  99921. if (dot1 < 0) dot1 = -dot1;
  99922. if (dot2 < 0) dot2 = -dot2;
  99923. len1 = dot1 * h1 + dot2 * d1;
  99924. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  99925. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  99926. if (dot1 < 0) dot1 = -dot1;
  99927. if (dot2 < 0) dot2 = -dot2;
  99928. len2 = dot1 * h2 + dot2 * d2;
  99929. overlap7 = len - len1 - len2;
  99930. if (overlap7 > 0) return;
  99931. } else {
  99932. right7 = false;
  99933. overlap7 = 0;
  99934. invalid7 = true;
  99935. }
  99936. // try axis 8
  99937. len = a8x * a8x + a8y * a8y + a8z * a8z;
  99938. if (len > 1e-5) {
  99939. len = 1 / OIMO.sqrt(len);
  99940. a8x *= len;
  99941. a8y *= len;
  99942. a8z *= len;
  99943. len = a8x * dx + a8y * dy + a8z * dz;
  99944. right8 = len > 0;
  99945. if (!right8) len = -len;
  99946. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  99947. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  99948. if (dot1 < 0) dot1 = -dot1;
  99949. if (dot2 < 0) dot2 = -dot2;
  99950. len1 = dot1 * h1 + dot2 * d1;
  99951. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  99952. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  99953. if (dot1 < 0) dot1 = -dot1;
  99954. if (dot2 < 0) dot2 = -dot2;
  99955. len2 = dot1 * w2 + dot2 * d2;
  99956. overlap8 = len - len1 - len2;
  99957. if (overlap8 > 0) return;
  99958. } else {
  99959. right8 = false;
  99960. overlap8 = 0;
  99961. invalid8 = true;
  99962. }
  99963. // try axis 9
  99964. len = a9x * a9x + a9y * a9y + a9z * a9z;
  99965. if (len > 1e-5) {
  99966. len = 1 / OIMO.sqrt(len);
  99967. a9x *= len;
  99968. a9y *= len;
  99969. a9z *= len;
  99970. len = a9x * dx + a9y * dy + a9z * dz;
  99971. right9 = len > 0;
  99972. if (!right9) len = -len;
  99973. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  99974. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  99975. if (dot1 < 0) dot1 = -dot1;
  99976. if (dot2 < 0) dot2 = -dot2;
  99977. len1 = dot1 * h1 + dot2 * d1;
  99978. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  99979. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  99980. if (dot1 < 0) dot1 = -dot1;
  99981. if (dot2 < 0) dot2 = -dot2;
  99982. len2 = dot1 * w2 + dot2 * h2;
  99983. overlap9 = len - len1 - len2;
  99984. if (overlap9 > 0) return;
  99985. } else {
  99986. right9 = false;
  99987. overlap9 = 0;
  99988. invalid9 = true;
  99989. }
  99990. // try axis 10
  99991. len = aax * aax + aay * aay + aaz * aaz;
  99992. if (len > 1e-5) {
  99993. len = 1 / OIMO.sqrt(len);
  99994. aax *= len;
  99995. aay *= len;
  99996. aaz *= len;
  99997. len = aax * dx + aay * dy + aaz * dz;
  99998. righta = len > 0;
  99999. if (!righta) len = -len;
  100000. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  100001. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  100002. if (dot1 < 0) dot1 = -dot1;
  100003. if (dot2 < 0) dot2 = -dot2;
  100004. len1 = dot1 * w1 + dot2 * d1;
  100005. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  100006. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  100007. if (dot1 < 0) dot1 = -dot1;
  100008. if (dot2 < 0) dot2 = -dot2;
  100009. len2 = dot1 * h2 + dot2 * d2;
  100010. overlapa = len - len1 - len2;
  100011. if (overlapa > 0) return;
  100012. } else {
  100013. righta = false;
  100014. overlapa = 0;
  100015. invalida = true;
  100016. }
  100017. // try axis 11
  100018. len = abx * abx + aby * aby + abz * abz;
  100019. if (len > 1e-5) {
  100020. len = 1 / OIMO.sqrt(len);
  100021. abx *= len;
  100022. aby *= len;
  100023. abz *= len;
  100024. len = abx * dx + aby * dy + abz * dz;
  100025. rightb = len > 0;
  100026. if (!rightb) len = -len;
  100027. dot1 = abx * a1x + aby * a1y + abz * a1z;
  100028. dot2 = abx * a3x + aby * a3y + abz * a3z;
  100029. if (dot1 < 0) dot1 = -dot1;
  100030. if (dot2 < 0) dot2 = -dot2;
  100031. len1 = dot1 * w1 + dot2 * d1;
  100032. dot1 = abx * a4x + aby * a4y + abz * a4z;
  100033. dot2 = abx * a6x + aby * a6y + abz * a6z;
  100034. if (dot1 < 0) dot1 = -dot1;
  100035. if (dot2 < 0) dot2 = -dot2;
  100036. len2 = dot1 * w2 + dot2 * d2;
  100037. overlapb = len - len1 - len2;
  100038. if (overlapb > 0) return;
  100039. } else {
  100040. rightb = false;
  100041. overlapb = 0;
  100042. invalidb = true;
  100043. }
  100044. // try axis 12
  100045. len = acx * acx + acy * acy + acz * acz;
  100046. if (len > 1e-5) {
  100047. len = 1 / OIMO.sqrt(len);
  100048. acx *= len;
  100049. acy *= len;
  100050. acz *= len;
  100051. len = acx * dx + acy * dy + acz * dz;
  100052. rightc = len > 0;
  100053. if (!rightc) len = -len;
  100054. dot1 = acx * a1x + acy * a1y + acz * a1z;
  100055. dot2 = acx * a3x + acy * a3y + acz * a3z;
  100056. if (dot1 < 0) dot1 = -dot1;
  100057. if (dot2 < 0) dot2 = -dot2;
  100058. len1 = dot1 * w1 + dot2 * d1;
  100059. dot1 = acx * a4x + acy * a4y + acz * a4z;
  100060. dot2 = acx * a5x + acy * a5y + acz * a5z;
  100061. if (dot1 < 0) dot1 = -dot1;
  100062. if (dot2 < 0) dot2 = -dot2;
  100063. len2 = dot1 * w2 + dot2 * h2;
  100064. overlapc = len - len1 - len2;
  100065. if (overlapc > 0) return;
  100066. } else {
  100067. rightc = false;
  100068. overlapc = 0;
  100069. invalidc = true;
  100070. }
  100071. // try axis 13
  100072. len = adx * adx + ady * ady + adz * adz;
  100073. if (len > 1e-5) {
  100074. len = 1 / OIMO.sqrt(len);
  100075. adx *= len;
  100076. ady *= len;
  100077. adz *= len;
  100078. len = adx * dx + ady * dy + adz * dz;
  100079. rightd = len > 0;
  100080. if (!rightd) len = -len;
  100081. dot1 = adx * a1x + ady * a1y + adz * a1z;
  100082. dot2 = adx * a2x + ady * a2y + adz * a2z;
  100083. if (dot1 < 0) dot1 = -dot1;
  100084. if (dot2 < 0) dot2 = -dot2;
  100085. len1 = dot1 * w1 + dot2 * h1;
  100086. dot1 = adx * a5x + ady * a5y + adz * a5z;
  100087. dot2 = adx * a6x + ady * a6y + adz * a6z;
  100088. if (dot1 < 0) dot1 = -dot1;
  100089. if (dot2 < 0) dot2 = -dot2;
  100090. len2 = dot1 * h2 + dot2 * d2;
  100091. overlapd = len - len1 - len2;
  100092. if (overlapd > 0) return;
  100093. } else {
  100094. rightd = false;
  100095. overlapd = 0;
  100096. invalidd = true;
  100097. }
  100098. // try axis 14
  100099. len = aex * aex + aey * aey + aez * aez;
  100100. if (len > 1e-5) {
  100101. len = 1 / OIMO.sqrt(len);
  100102. aex *= len;
  100103. aey *= len;
  100104. aez *= len;
  100105. len = aex * dx + aey * dy + aez * dz;
  100106. righte = len > 0;
  100107. if (!righte) len = -len;
  100108. dot1 = aex * a1x + aey * a1y + aez * a1z;
  100109. dot2 = aex * a2x + aey * a2y + aez * a2z;
  100110. if (dot1 < 0) dot1 = -dot1;
  100111. if (dot2 < 0) dot2 = -dot2;
  100112. len1 = dot1 * w1 + dot2 * h1;
  100113. dot1 = aex * a4x + aey * a4y + aez * a4z;
  100114. dot2 = aex * a6x + aey * a6y + aez * a6z;
  100115. if (dot1 < 0) dot1 = -dot1;
  100116. if (dot2 < 0) dot2 = -dot2;
  100117. len2 = dot1 * w2 + dot2 * d2;
  100118. overlape = len - len1 - len2;
  100119. if (overlape > 0) return;
  100120. } else {
  100121. righte = false;
  100122. overlape = 0;
  100123. invalide = true;
  100124. }
  100125. // try axis 15
  100126. len = afx * afx + afy * afy + afz * afz;
  100127. if (len > 1e-5) {
  100128. len = 1 / OIMO.sqrt(len);
  100129. afx *= len;
  100130. afy *= len;
  100131. afz *= len;
  100132. len = afx * dx + afy * dy + afz * dz;
  100133. rightf = len > 0;
  100134. if (!rightf) len = -len;
  100135. dot1 = afx * a1x + afy * a1y + afz * a1z;
  100136. dot2 = afx * a2x + afy * a2y + afz * a2z;
  100137. if (dot1 < 0) dot1 = -dot1;
  100138. if (dot2 < 0) dot2 = -dot2;
  100139. len1 = dot1 * w1 + dot2 * h1;
  100140. dot1 = afx * a4x + afy * a4y + afz * a4z;
  100141. dot2 = afx * a5x + afy * a5y + afz * a5z;
  100142. if (dot1 < 0) dot1 = -dot1;
  100143. if (dot2 < 0) dot2 = -dot2;
  100144. len2 = dot1 * w2 + dot2 * h2;
  100145. overlapf = len - len1 - len2;
  100146. if (overlapf > 0) return;
  100147. } else {
  100148. rightf = false;
  100149. overlapf = 0;
  100150. invalidf = true;
  100151. }
  100152. // boxes are overlapping
  100153. var depth = overlap1;
  100154. var depth2 = overlap1;
  100155. var minIndex = 0;
  100156. var right = right1;
  100157. if (overlap2 > depth2) {
  100158. depth = overlap2;
  100159. depth2 = overlap2;
  100160. minIndex = 1;
  100161. right = right2;
  100162. }
  100163. if (overlap3 > depth2) {
  100164. depth = overlap3;
  100165. depth2 = overlap3;
  100166. minIndex = 2;
  100167. right = right3;
  100168. }
  100169. if (overlap4 > depth2) {
  100170. depth = overlap4;
  100171. depth2 = overlap4;
  100172. minIndex = 3;
  100173. right = right4;
  100174. }
  100175. if (overlap5 > depth2) {
  100176. depth = overlap5;
  100177. depth2 = overlap5;
  100178. minIndex = 4;
  100179. right = right5;
  100180. }
  100181. if (overlap6 > depth2) {
  100182. depth = overlap6;
  100183. depth2 = overlap6;
  100184. minIndex = 5;
  100185. right = right6;
  100186. }
  100187. if (overlap7 - 0.01 > depth2 && !invalid7) {
  100188. depth = overlap7;
  100189. depth2 = overlap7 - 0.01;
  100190. minIndex = 6;
  100191. right = right7;
  100192. }
  100193. if (overlap8 - 0.01 > depth2 && !invalid8) {
  100194. depth = overlap8;
  100195. depth2 = overlap8 - 0.01;
  100196. minIndex = 7;
  100197. right = right8;
  100198. }
  100199. if (overlap9 - 0.01 > depth2 && !invalid9) {
  100200. depth = overlap9;
  100201. depth2 = overlap9 - 0.01;
  100202. minIndex = 8;
  100203. right = right9;
  100204. }
  100205. if (overlapa - 0.01 > depth2 && !invalida) {
  100206. depth = overlapa;
  100207. depth2 = overlapa - 0.01;
  100208. minIndex = 9;
  100209. right = righta;
  100210. }
  100211. if (overlapb - 0.01 > depth2 && !invalidb) {
  100212. depth = overlapb;
  100213. depth2 = overlapb - 0.01;
  100214. minIndex = 10;
  100215. right = rightb;
  100216. }
  100217. if (overlapc - 0.01 > depth2 && !invalidc) {
  100218. depth = overlapc;
  100219. depth2 = overlapc - 0.01;
  100220. minIndex = 11;
  100221. right = rightc;
  100222. }
  100223. if (overlapd - 0.01 > depth2 && !invalidd) {
  100224. depth = overlapd;
  100225. depth2 = overlapd - 0.01;
  100226. minIndex = 12;
  100227. right = rightd;
  100228. }
  100229. if (overlape - 0.01 > depth2 && !invalide) {
  100230. depth = overlape;
  100231. depth2 = overlape - 0.01;
  100232. minIndex = 13;
  100233. right = righte;
  100234. }
  100235. if (overlapf - 0.01 > depth2 && !invalidf) {
  100236. depth = overlapf;
  100237. minIndex = 14;
  100238. right = rightf;
  100239. }
  100240. // normal
  100241. var nx = 0;
  100242. var ny = 0;
  100243. var nz = 0;
  100244. // edge line or face side normal
  100245. var n1x = 0;
  100246. var n1y = 0;
  100247. var n1z = 0;
  100248. var n2x = 0;
  100249. var n2y = 0;
  100250. var n2z = 0;
  100251. // center of current face
  100252. var cx = 0;
  100253. var cy = 0;
  100254. var cz = 0;
  100255. // face side
  100256. var s1x = 0;
  100257. var s1y = 0;
  100258. var s1z = 0;
  100259. var s2x = 0;
  100260. var s2y = 0;
  100261. var s2z = 0;
  100262. // swap b1 b2
  100263. var swap = false;
  100264. //_______________________________________
  100265. if (minIndex == 0) {// b1.x * b2
  100266. if (right) {
  100267. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  100268. nx = a1x; ny = a1y; nz = a1z;
  100269. } else {
  100270. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  100271. nx = -a1x; ny = -a1y; nz = -a1z;
  100272. }
  100273. s1x = d2x; s1y = d2y; s1z = d2z;
  100274. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  100275. s2x = d3x; s2y = d3y; s2z = d3z;
  100276. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  100277. }
  100278. else if (minIndex == 1) {// b1.y * b2
  100279. if (right) {
  100280. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  100281. nx = a2x; ny = a2y; nz = a2z;
  100282. } else {
  100283. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  100284. nx = -a2x; ny = -a2y; nz = -a2z;
  100285. }
  100286. s1x = d1x; s1y = d1y; s1z = d1z;
  100287. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  100288. s2x = d3x; s2y = d3y; s2z = d3z;
  100289. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  100290. }
  100291. else if (minIndex == 2) {// b1.z * b2
  100292. if (right) {
  100293. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  100294. nx = a3x; ny = a3y; nz = a3z;
  100295. } else {
  100296. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  100297. nx = -a3x; ny = -a3y; nz = -a3z;
  100298. }
  100299. s1x = d1x; s1y = d1y; s1z = d1z;
  100300. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  100301. s2x = d2x; s2y = d2y; s2z = d2z;
  100302. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  100303. }
  100304. else if (minIndex == 3) {// b2.x * b1
  100305. swap = true;
  100306. if (!right) {
  100307. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  100308. nx = a4x; ny = a4y; nz = a4z;
  100309. } else {
  100310. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  100311. nx = -a4x; ny = -a4y; nz = -a4z;
  100312. }
  100313. s1x = d5x; s1y = d5y; s1z = d5z;
  100314. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  100315. s2x = d6x; s2y = d6y; s2z = d6z;
  100316. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  100317. }
  100318. else if (minIndex == 4) {// b2.y * b1
  100319. swap = true;
  100320. if (!right) {
  100321. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  100322. nx = a5x; ny = a5y; nz = a5z;
  100323. } else {
  100324. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  100325. nx = -a5x; ny = -a5y; nz = -a5z;
  100326. }
  100327. s1x = d4x; s1y = d4y; s1z = d4z;
  100328. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  100329. s2x = d6x; s2y = d6y; s2z = d6z;
  100330. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  100331. }
  100332. else if (minIndex == 5) {// b2.z * b1
  100333. swap = true;
  100334. if (!right) {
  100335. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  100336. nx = a6x; ny = a6y; nz = a6z;
  100337. } else {
  100338. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  100339. nx = -a6x; ny = -a6y; nz = -a6z;
  100340. }
  100341. s1x = d4x; s1y = d4y; s1z = d4z;
  100342. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  100343. s2x = d5x; s2y = d5y; s2z = d5z;
  100344. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  100345. }
  100346. else if (minIndex == 6) {// b1.x * b2.x
  100347. nx = a7x; ny = a7y; nz = a7z;
  100348. n1x = a1x; n1y = a1y; n1z = a1z;
  100349. n2x = a4x; n2y = a4y; n2z = a4z;
  100350. }
  100351. else if (minIndex == 7) {// b1.x * b2.y
  100352. nx = a8x; ny = a8y; nz = a8z;
  100353. n1x = a1x; n1y = a1y; n1z = a1z;
  100354. n2x = a5x; n2y = a5y; n2z = a5z;
  100355. }
  100356. else if (minIndex == 8) {// b1.x * b2.z
  100357. nx = a9x; ny = a9y; nz = a9z;
  100358. n1x = a1x; n1y = a1y; n1z = a1z;
  100359. n2x = a6x; n2y = a6y; n2z = a6z;
  100360. }
  100361. else if (minIndex == 9) {// b1.y * b2.x
  100362. nx = aax; ny = aay; nz = aaz;
  100363. n1x = a2x; n1y = a2y; n1z = a2z;
  100364. n2x = a4x; n2y = a4y; n2z = a4z
  100365. }
  100366. else if (minIndex == 10) {// b1.y * b2.y
  100367. nx = abx; ny = aby; nz = abz;
  100368. n1x = a2x; n1y = a2y; n1z = a2z;
  100369. n2x = a5x; n2y = a5y; n2z = a5z;
  100370. }
  100371. else if (minIndex == 11) {// b1.y * b2.z
  100372. nx = acx; ny = acy; nz = acz;
  100373. n1x = a2x; n1y = a2y; n1z = a2z;
  100374. n2x = a6x; n2y = a6y; n2z = a6z;
  100375. }
  100376. else if (minIndex == 12) {// b1.z * b2.x
  100377. nx = adx; ny = ady; nz = adz;
  100378. n1x = a3x; n1y = a3y; n1z = a3z;
  100379. n2x = a4x; n2y = a4y; n2z = a4z;
  100380. }
  100381. else if (minIndex == 13) {// b1.z * b2.y
  100382. nx = aex; ny = aey; nz = aez;
  100383. n1x = a3x; n1y = a3y; n1z = a3z;
  100384. n2x = a5x; n2y = a5y; n2z = a5z;
  100385. }
  100386. else if (minIndex == 14) {// b1.z * b2.z
  100387. nx = afx; ny = afy; nz = afz;
  100388. n1x = a3x; n1y = a3y; n1z = a3z;
  100389. n2x = a6x; n2y = a6y; n2z = a6z;
  100390. }
  100391. //__________________________________________
  100392. var v;
  100393. if (minIndex > 5) {
  100394. if (!right) {
  100395. nx = -nx; ny = -ny; nz = -nz;
  100396. }
  100397. var distance;
  100398. var maxDistance;
  100399. var vx;
  100400. var vy;
  100401. var vz;
  100402. var v1x;
  100403. var v1y;
  100404. var v1z;
  100405. var v2x;
  100406. var v2y;
  100407. var v2z;
  100408. //vertex1;
  100409. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  100410. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  100411. //vertex2;
  100412. vx = V1[3]; vy = V1[4]; vz = V1[5];
  100413. distance = nx * vx + ny * vy + nz * vz;
  100414. if (distance > maxDistance) {
  100415. maxDistance = distance;
  100416. v1x = vx; v1y = vy; v1z = vz;
  100417. }
  100418. //vertex3;
  100419. vx = V1[6]; vy = V1[7]; vz = V1[8];
  100420. distance = nx * vx + ny * vy + nz * vz;
  100421. if (distance > maxDistance) {
  100422. maxDistance = distance;
  100423. v1x = vx; v1y = vy; v1z = vz;
  100424. }
  100425. //vertex4;
  100426. vx = V1[9]; vy = V1[10]; vz = V1[11];
  100427. distance = nx * vx + ny * vy + nz * vz;
  100428. if (distance > maxDistance) {
  100429. maxDistance = distance;
  100430. v1x = vx; v1y = vy; v1z = vz;
  100431. }
  100432. //vertex5;
  100433. vx = V1[12]; vy = V1[13]; vz = V1[14];
  100434. distance = nx * vx + ny * vy + nz * vz;
  100435. if (distance > maxDistance) {
  100436. maxDistance = distance;
  100437. v1x = vx; v1y = vy; v1z = vz;
  100438. }
  100439. //vertex6;
  100440. vx = V1[15]; vy = V1[16]; vz = V1[17];
  100441. distance = nx * vx + ny * vy + nz * vz;
  100442. if (distance > maxDistance) {
  100443. maxDistance = distance;
  100444. v1x = vx; v1y = vy; v1z = vz;
  100445. }
  100446. //vertex7;
  100447. vx = V1[18]; vy = V1[19]; vz = V1[20];
  100448. distance = nx * vx + ny * vy + nz * vz;
  100449. if (distance > maxDistance) {
  100450. maxDistance = distance;
  100451. v1x = vx; v1y = vy; v1z = vz;
  100452. }
  100453. //vertex8;
  100454. vx = V1[21]; vy = V1[22]; vz = V1[23];
  100455. distance = nx * vx + ny * vy + nz * vz;
  100456. if (distance > maxDistance) {
  100457. maxDistance = distance;
  100458. v1x = vx; v1y = vy; v1z = vz;
  100459. }
  100460. //vertex1;
  100461. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  100462. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  100463. //vertex2;
  100464. vx = V2[3]; vy = V2[4]; vz = V2[5];
  100465. distance = nx * vx + ny * vy + nz * vz;
  100466. if (distance < maxDistance) {
  100467. maxDistance = distance;
  100468. v2x = vx; v2y = vy; v2z = vz;
  100469. }
  100470. //vertex3;
  100471. vx = V2[6]; vy = V2[7]; vz = V2[8];
  100472. distance = nx * vx + ny * vy + nz * vz;
  100473. if (distance < maxDistance) {
  100474. maxDistance = distance;
  100475. v2x = vx; v2y = vy; v2z = vz;
  100476. }
  100477. //vertex4;
  100478. vx = V2[9]; vy = V2[10]; vz = V2[11];
  100479. distance = nx * vx + ny * vy + nz * vz;
  100480. if (distance < maxDistance) {
  100481. maxDistance = distance;
  100482. v2x = vx; v2y = vy; v2z = vz;
  100483. }
  100484. //vertex5;
  100485. vx = V2[12]; vy = V2[13]; vz = V2[14];
  100486. distance = nx * vx + ny * vy + nz * vz;
  100487. if (distance < maxDistance) {
  100488. maxDistance = distance;
  100489. v2x = vx; v2y = vy; v2z = vz;
  100490. }
  100491. //vertex6;
  100492. vx = V2[15]; vy = V2[16]; vz = V2[17];
  100493. distance = nx * vx + ny * vy + nz * vz;
  100494. if (distance < maxDistance) {
  100495. maxDistance = distance;
  100496. v2x = vx; v2y = vy; v2z = vz;
  100497. }
  100498. //vertex7;
  100499. vx = V2[18]; vy = V2[19]; vz = V2[20];
  100500. distance = nx * vx + ny * vy + nz * vz;
  100501. if (distance < maxDistance) {
  100502. maxDistance = distance;
  100503. v2x = vx; v2y = vy; v2z = vz;
  100504. }
  100505. //vertex8;
  100506. vx = V2[21]; vy = V2[22]; vz = V2[23];
  100507. distance = nx * vx + ny * vy + nz * vz;
  100508. if (distance < maxDistance) {
  100509. maxDistance = distance;
  100510. v2x = vx; v2y = vy; v2z = vz;
  100511. }
  100512. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  100513. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  100514. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  100515. manifold.addPoint(v1x + n1x * t + nx * depth * 0.5, v1y + n1y * t + ny * depth * 0.5, v1z + n1z * t + nz * depth * 0.5, nx, ny, nz, depth, false);
  100516. return;
  100517. }
  100518. // now detect face-face collision...
  100519. // target quad
  100520. var q1x;
  100521. var q1y;
  100522. var q1z;
  100523. var q2x;
  100524. var q2y;
  100525. var q2z;
  100526. var q3x;
  100527. var q3y;
  100528. var q3z;
  100529. var q4x;
  100530. var q4y;
  100531. var q4z;
  100532. // search support face and vertex
  100533. var minDot = 1;
  100534. var dot = 0;
  100535. var minDotIndex = 0;
  100536. if (swap) {
  100537. dot = a1x * nx + a1y * ny + a1z * nz;
  100538. if (dot < minDot) {
  100539. minDot = dot;
  100540. minDotIndex = 0;
  100541. }
  100542. if (-dot < minDot) {
  100543. minDot = -dot;
  100544. minDotIndex = 1;
  100545. }
  100546. dot = a2x * nx + a2y * ny + a2z * nz;
  100547. if (dot < minDot) {
  100548. minDot = dot;
  100549. minDotIndex = 2;
  100550. }
  100551. if (-dot < minDot) {
  100552. minDot = -dot;
  100553. minDotIndex = 3;
  100554. }
  100555. dot = a3x * nx + a3y * ny + a3z * nz;
  100556. if (dot < minDot) {
  100557. minDot = dot;
  100558. minDotIndex = 4;
  100559. }
  100560. if (-dot < minDot) {
  100561. minDot = -dot;
  100562. minDotIndex = 5;
  100563. }
  100564. if (minDotIndex == 0) {// x+ face
  100565. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  100566. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  100567. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  100568. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  100569. }
  100570. else if (minDotIndex == 1) {// x- face
  100571. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  100572. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  100573. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  100574. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  100575. }
  100576. else if (minDotIndex == 2) {// y+ face
  100577. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  100578. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  100579. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  100580. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  100581. }
  100582. else if (minDotIndex == 3) {// y- face
  100583. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  100584. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  100585. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  100586. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  100587. }
  100588. else if (minDotIndex == 4) {// z+ face
  100589. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  100590. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  100591. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  100592. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  100593. }
  100594. else if (minDotIndex == 5) {// z- face
  100595. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  100596. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  100597. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  100598. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  100599. }
  100600. } else {
  100601. dot = a4x * nx + a4y * ny + a4z * nz;
  100602. if (dot < minDot) {
  100603. minDot = dot;
  100604. minDotIndex = 0;
  100605. }
  100606. if (-dot < minDot) {
  100607. minDot = -dot;
  100608. minDotIndex = 1;
  100609. }
  100610. dot = a5x * nx + a5y * ny + a5z * nz;
  100611. if (dot < minDot) {
  100612. minDot = dot;
  100613. minDotIndex = 2;
  100614. }
  100615. if (-dot < minDot) {
  100616. minDot = -dot;
  100617. minDotIndex = 3;
  100618. }
  100619. dot = a6x * nx + a6y * ny + a6z * nz;
  100620. if (dot < minDot) {
  100621. minDot = dot;
  100622. minDotIndex = 4;
  100623. }
  100624. if (-dot < minDot) {
  100625. minDot = -dot;
  100626. minDotIndex = 5;
  100627. }
  100628. //______________________________________________________
  100629. if (minDotIndex == 0) {// x+ face
  100630. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  100631. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  100632. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  100633. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  100634. }
  100635. else if (minDotIndex == 1) {// x- face
  100636. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  100637. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  100638. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  100639. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  100640. }
  100641. else if (minDotIndex == 2) {// y+ face
  100642. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  100643. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  100644. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  100645. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  100646. }
  100647. else if (minDotIndex == 3) {// y- face
  100648. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  100649. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  100650. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  100651. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  100652. }
  100653. else if (minDotIndex == 4) {// z+ face
  100654. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  100655. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  100656. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  100657. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  100658. }
  100659. else if (minDotIndex == 5) {// z- face
  100660. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  100661. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  100662. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  100663. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  100664. }
  100665. }
  100666. // clip vertices
  100667. var numClipVertices;
  100668. var numAddedClipVertices;
  100669. var index;
  100670. var x1;
  100671. var y1;
  100672. var z1;
  100673. var x2;
  100674. var y2;
  100675. var z2;
  100676. this.clipVertices1[0] = q1x;
  100677. this.clipVertices1[1] = q1y;
  100678. this.clipVertices1[2] = q1z;
  100679. this.clipVertices1[3] = q2x;
  100680. this.clipVertices1[4] = q2y;
  100681. this.clipVertices1[5] = q2z;
  100682. this.clipVertices1[6] = q3x;
  100683. this.clipVertices1[7] = q3y;
  100684. this.clipVertices1[8] = q3z;
  100685. this.clipVertices1[9] = q4x;
  100686. this.clipVertices1[10] = q4y;
  100687. this.clipVertices1[11] = q4z;
  100688. numAddedClipVertices = 0;
  100689. x1 = this.clipVertices1[9];
  100690. y1 = this.clipVertices1[10];
  100691. z1 = this.clipVertices1[11];
  100692. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  100693. //var i = 4;
  100694. //while(i--){
  100695. for (var i = 0; i < 4; i++) {
  100696. index = i * 3;
  100697. x2 = this.clipVertices1[index];
  100698. y2 = this.clipVertices1[index + 1];
  100699. z2 = this.clipVertices1[index + 2];
  100700. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  100701. if (dot1 > 0) {
  100702. if (dot2 > 0) {
  100703. index = numAddedClipVertices * 3;
  100704. numAddedClipVertices++;
  100705. this.clipVertices2[index] = x2;
  100706. this.clipVertices2[index + 1] = y2;
  100707. this.clipVertices2[index + 2] = z2;
  100708. } else {
  100709. index = numAddedClipVertices * 3;
  100710. numAddedClipVertices++;
  100711. t = dot1 / (dot1 - dot2);
  100712. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100713. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100714. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100715. }
  100716. } else {
  100717. if (dot2 > 0) {
  100718. index = numAddedClipVertices * 3;
  100719. numAddedClipVertices++;
  100720. t = dot1 / (dot1 - dot2);
  100721. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100722. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100723. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100724. index = numAddedClipVertices * 3;
  100725. numAddedClipVertices++;
  100726. this.clipVertices2[index] = x2;
  100727. this.clipVertices2[index + 1] = y2;
  100728. this.clipVertices2[index + 2] = z2;
  100729. }
  100730. }
  100731. x1 = x2;
  100732. y1 = y2;
  100733. z1 = z2;
  100734. dot1 = dot2;
  100735. }
  100736. numClipVertices = numAddedClipVertices;
  100737. if (numClipVertices == 0) return;
  100738. numAddedClipVertices = 0;
  100739. index = (numClipVertices - 1) * 3;
  100740. x1 = this.clipVertices2[index];
  100741. y1 = this.clipVertices2[index + 1];
  100742. z1 = this.clipVertices2[index + 2];
  100743. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  100744. //i = numClipVertices;
  100745. //while(i--){
  100746. for (i = 0; i < numClipVertices; i++) {
  100747. index = i * 3;
  100748. x2 = this.clipVertices2[index];
  100749. y2 = this.clipVertices2[index + 1];
  100750. z2 = this.clipVertices2[index + 2];
  100751. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  100752. if (dot1 > 0) {
  100753. if (dot2 > 0) {
  100754. index = numAddedClipVertices * 3;
  100755. numAddedClipVertices++;
  100756. this.clipVertices1[index] = x2;
  100757. this.clipVertices1[index + 1] = y2;
  100758. this.clipVertices1[index + 2] = z2;
  100759. } else {
  100760. index = numAddedClipVertices * 3;
  100761. numAddedClipVertices++;
  100762. t = dot1 / (dot1 - dot2);
  100763. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100764. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100765. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100766. }
  100767. } else {
  100768. if (dot2 > 0) {
  100769. index = numAddedClipVertices * 3;
  100770. numAddedClipVertices++;
  100771. t = dot1 / (dot1 - dot2);
  100772. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100773. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100774. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100775. index = numAddedClipVertices * 3;
  100776. numAddedClipVertices++;
  100777. this.clipVertices1[index] = x2;
  100778. this.clipVertices1[index + 1] = y2;
  100779. this.clipVertices1[index + 2] = z2;
  100780. }
  100781. }
  100782. x1 = x2;
  100783. y1 = y2;
  100784. z1 = z2;
  100785. dot1 = dot2;
  100786. }
  100787. numClipVertices = numAddedClipVertices;
  100788. if (numClipVertices == 0) return;
  100789. numAddedClipVertices = 0;
  100790. index = (numClipVertices - 1) * 3;
  100791. x1 = this.clipVertices1[index];
  100792. y1 = this.clipVertices1[index + 1];
  100793. z1 = this.clipVertices1[index + 2];
  100794. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  100795. //i = numClipVertices;
  100796. //while(i--){
  100797. for (i = 0; i < numClipVertices; i++) {
  100798. index = i * 3;
  100799. x2 = this.clipVertices1[index];
  100800. y2 = this.clipVertices1[index + 1];
  100801. z2 = this.clipVertices1[index + 2];
  100802. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  100803. if (dot1 > 0) {
  100804. if (dot2 > 0) {
  100805. index = numAddedClipVertices * 3;
  100806. numAddedClipVertices++;
  100807. this.clipVertices2[index] = x2;
  100808. this.clipVertices2[index + 1] = y2;
  100809. this.clipVertices2[index + 2] = z2;
  100810. } else {
  100811. index = numAddedClipVertices * 3;
  100812. numAddedClipVertices++;
  100813. t = dot1 / (dot1 - dot2);
  100814. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100815. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100816. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100817. }
  100818. } else {
  100819. if (dot2 > 0) {
  100820. index = numAddedClipVertices * 3;
  100821. numAddedClipVertices++;
  100822. t = dot1 / (dot1 - dot2);
  100823. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100824. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100825. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100826. index = numAddedClipVertices * 3;
  100827. numAddedClipVertices++;
  100828. this.clipVertices2[index] = x2;
  100829. this.clipVertices2[index + 1] = y2;
  100830. this.clipVertices2[index + 2] = z2;
  100831. }
  100832. }
  100833. x1 = x2;
  100834. y1 = y2;
  100835. z1 = z2;
  100836. dot1 = dot2;
  100837. }
  100838. numClipVertices = numAddedClipVertices;
  100839. if (numClipVertices == 0) return;
  100840. numAddedClipVertices = 0;
  100841. index = (numClipVertices - 1) * 3;
  100842. x1 = this.clipVertices2[index];
  100843. y1 = this.clipVertices2[index + 1];
  100844. z1 = this.clipVertices2[index + 2];
  100845. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  100846. //i = numClipVertices;
  100847. //while(i--){
  100848. for (i = 0; i < numClipVertices; i++) {
  100849. index = i * 3;
  100850. x2 = this.clipVertices2[index];
  100851. y2 = this.clipVertices2[index + 1];
  100852. z2 = this.clipVertices2[index + 2];
  100853. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  100854. if (dot1 > 0) {
  100855. if (dot2 > 0) {
  100856. index = numAddedClipVertices * 3;
  100857. numAddedClipVertices++;
  100858. this.clipVertices1[index] = x2;
  100859. this.clipVertices1[index + 1] = y2;
  100860. this.clipVertices1[index + 2] = z2;
  100861. } else {
  100862. index = numAddedClipVertices * 3;
  100863. numAddedClipVertices++;
  100864. t = dot1 / (dot1 - dot2);
  100865. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100866. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100867. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100868. }
  100869. } else {
  100870. if (dot2 > 0) {
  100871. index = numAddedClipVertices * 3;
  100872. numAddedClipVertices++;
  100873. t = dot1 / (dot1 - dot2);
  100874. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100875. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100876. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100877. index = numAddedClipVertices * 3;
  100878. numAddedClipVertices++;
  100879. this.clipVertices1[index] = x2;
  100880. this.clipVertices1[index + 1] = y2;
  100881. this.clipVertices1[index + 2] = z2;
  100882. }
  100883. }
  100884. x1 = x2;
  100885. y1 = y2;
  100886. z1 = z2;
  100887. dot1 = dot2;
  100888. }
  100889. numClipVertices = numAddedClipVertices;
  100890. if (swap) {
  100891. var tb = b1;
  100892. b1 = b2;
  100893. b2 = tb;
  100894. }
  100895. if (numClipVertices == 0) return;
  100896. var flipped = b1 != shape1;
  100897. if (numClipVertices > 4) {
  100898. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  100899. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  100900. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  100901. n1x = q1x - x1;
  100902. n1y = q1y - y1;
  100903. n1z = q1z - z1;
  100904. n2x = q2x - x1;
  100905. n2y = q2y - y1;
  100906. n2z = q2z - z1;
  100907. var index1 = 0;
  100908. var index2 = 0;
  100909. var index3 = 0;
  100910. var index4 = 0;
  100911. var maxDot = -this.INF;
  100912. minDot = this.INF;
  100913. //i = numClipVertices;
  100914. //while(i--){
  100915. for (i = 0; i < numClipVertices; i++) {
  100916. this.used[i] = false;
  100917. index = i * 3;
  100918. x1 = this.clipVertices1[index];
  100919. y1 = this.clipVertices1[index + 1];
  100920. z1 = this.clipVertices1[index + 2];
  100921. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  100922. if (dot < minDot) {
  100923. minDot = dot;
  100924. index1 = i;
  100925. }
  100926. if (dot > maxDot) {
  100927. maxDot = dot;
  100928. index3 = i;
  100929. }
  100930. }
  100931. this.used[index1] = true;
  100932. this.used[index3] = true;
  100933. maxDot = -this.INF;
  100934. minDot = this.INF;
  100935. //i = numClipVertices;
  100936. //while(i--){
  100937. for (i = 0; i < numClipVertices; i++) {
  100938. if (this.used[i]) continue;
  100939. index = i * 3;
  100940. x1 = this.clipVertices1[index];
  100941. y1 = this.clipVertices1[index + 1];
  100942. z1 = this.clipVertices1[index + 2];
  100943. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  100944. if (dot < minDot) {
  100945. minDot = dot;
  100946. index2 = i;
  100947. }
  100948. if (dot > maxDot) {
  100949. maxDot = dot;
  100950. index4 = i;
  100951. }
  100952. }
  100953. index = index1 * 3;
  100954. x1 = this.clipVertices1[index];
  100955. y1 = this.clipVertices1[index + 1];
  100956. z1 = this.clipVertices1[index + 2];
  100957. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100958. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100959. index = index2 * 3;
  100960. x1 = this.clipVertices1[index];
  100961. y1 = this.clipVertices1[index + 1];
  100962. z1 = this.clipVertices1[index + 2];
  100963. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100964. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100965. index = index3 * 3;
  100966. x1 = this.clipVertices1[index];
  100967. y1 = this.clipVertices1[index + 1];
  100968. z1 = this.clipVertices1[index + 2];
  100969. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100970. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100971. index = index4 * 3;
  100972. x1 = this.clipVertices1[index];
  100973. y1 = this.clipVertices1[index + 1];
  100974. z1 = this.clipVertices1[index + 2];
  100975. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100976. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100977. } else {
  100978. //i = numClipVertices;
  100979. //while(i--){
  100980. for (i = 0; i < numClipVertices; i++) {
  100981. index = i * 3;
  100982. x1 = this.clipVertices1[index];
  100983. y1 = this.clipVertices1[index + 1];
  100984. z1 = this.clipVertices1[index + 2];
  100985. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100986. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100987. }
  100988. }
  100989. };
  100990. /**
  100991. * A collision detector which detects collisions between sphere and box.
  100992. * @author saharan
  100993. */
  100994. OIMO.SphereBoxCollisionDetector = function (flip) {
  100995. OIMO.CollisionDetector.call(this);
  100996. this.flip = flip;
  100997. };
  100998. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100999. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  101000. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101001. var s;
  101002. var b;
  101003. if (this.flip) {
  101004. s = (shape2);
  101005. b = (shape1);
  101006. } else {
  101007. s = (shape1);
  101008. b = (shape2);
  101009. }
  101010. var D = b.dimentions;
  101011. var ps = s.position;
  101012. var psx = ps.x;
  101013. var psy = ps.y;
  101014. var psz = ps.z;
  101015. var pb = b.position;
  101016. var pbx = pb.x;
  101017. var pby = pb.y;
  101018. var pbz = pb.z;
  101019. var rad = s.radius;
  101020. var hw = b.halfWidth;
  101021. var hh = b.halfHeight;
  101022. var hd = b.halfDepth;
  101023. var dx = psx - pbx;
  101024. var dy = psy - pby;
  101025. var dz = psz - pbz;
  101026. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  101027. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  101028. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  101029. var cx;
  101030. var cy;
  101031. var cz;
  101032. var len;
  101033. var invLen;
  101034. var overlap = 0;
  101035. if (sx > hw) {
  101036. sx = hw;
  101037. } else if (sx < -hw) {
  101038. sx = -hw;
  101039. } else {
  101040. overlap = 1;
  101041. }
  101042. if (sy > hh) {
  101043. sy = hh;
  101044. } else if (sy < -hh) {
  101045. sy = -hh;
  101046. } else {
  101047. overlap |= 2;
  101048. }
  101049. if (sz > hd) {
  101050. sz = hd;
  101051. } else if (sz < -hd) {
  101052. sz = -hd;
  101053. } else {
  101054. overlap |= 4;
  101055. }
  101056. if (overlap == 7) {
  101057. // center of sphere is in the box
  101058. if (sx < 0) {
  101059. dx = hw + sx;
  101060. } else {
  101061. dx = hw - sx;
  101062. }
  101063. if (sy < 0) {
  101064. dy = hh + sy;
  101065. } else {
  101066. dy = hh - sy;
  101067. }
  101068. if (sz < 0) {
  101069. dz = hd + sz;
  101070. } else {
  101071. dz = hd - sz;
  101072. }
  101073. if (dx < dy) {
  101074. if (dx < dz) {
  101075. len = dx - hw;
  101076. if (sx < 0) {
  101077. sx = -hw;
  101078. dx = D[0];
  101079. dy = D[1];
  101080. dz = D[2];
  101081. } else {
  101082. sx = hw;
  101083. dx = -D[0];
  101084. dy = -D[1];
  101085. dz = -D[2];
  101086. }
  101087. } else {
  101088. len = dz - hd;
  101089. if (sz < 0) {
  101090. sz = -hd;
  101091. dx = D[6];
  101092. dy = D[7];
  101093. dz = D[8];
  101094. } else {
  101095. sz = hd;
  101096. dx = -D[6];
  101097. dy = -D[7];
  101098. dz = -D[8];
  101099. }
  101100. }
  101101. } else {
  101102. if (dy < dz) {
  101103. len = dy - hh;
  101104. if (sy < 0) {
  101105. sy = -hh;
  101106. dx = D[3];
  101107. dy = D[4];
  101108. dz = D[5];
  101109. } else {
  101110. sy = hh;
  101111. dx = -D[3];
  101112. dy = -D[4];
  101113. dz = -D[5];
  101114. }
  101115. } else {
  101116. len = dz - hd;
  101117. if (sz < 0) {
  101118. sz = -hd;
  101119. dx = D[6];
  101120. dy = D[7];
  101121. dz = D[8];
  101122. } else {
  101123. sz = hd;
  101124. dx = -D[6];
  101125. dy = -D[7];
  101126. dz = -D[8];
  101127. }
  101128. }
  101129. }
  101130. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  101131. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  101132. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  101133. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  101134. } else {
  101135. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  101136. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  101137. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  101138. dx = cx - ps.x;
  101139. dy = cy - ps.y;
  101140. dz = cz - ps.z;
  101141. len = dx * dx + dy * dy + dz * dz;
  101142. if (len > 0 && len < rad * rad) {
  101143. len = OIMO.sqrt(len);
  101144. invLen = 1 / len;
  101145. dx *= invLen;
  101146. dy *= invLen;
  101147. dz *= invLen;
  101148. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  101149. }
  101150. }
  101151. };
  101152. /**
  101153. * A collision detector which detects collisions between two spheres.
  101154. * @author saharan
  101155. */
  101156. OIMO.SphereSphereCollisionDetector = function () {
  101157. OIMO.CollisionDetector.call(this);
  101158. };
  101159. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101160. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  101161. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101162. var s1 = shape1;
  101163. var s2 = shape2;
  101164. var p1 = s1.position;
  101165. var p2 = s2.position;
  101166. var dx = p2.x - p1.x;
  101167. var dy = p2.y - p1.y;
  101168. var dz = p2.z - p1.z;
  101169. var len = dx * dx + dy * dy + dz * dz;
  101170. var r1 = s1.radius;
  101171. var r2 = s2.radius;
  101172. var rad = r1 + r2;
  101173. if (len > 0 && len < rad * rad) {
  101174. len = OIMO.sqrt(len);
  101175. var invLen = 1 / len;
  101176. dx *= invLen;
  101177. dy *= invLen;
  101178. dz *= invLen;
  101179. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  101180. }
  101181. };
  101182. OIMO.BoxCylinderCollisionDetector = function (flip) {
  101183. OIMO.CollisionDetector.call(this);
  101184. this.flip = flip;
  101185. };
  101186. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101187. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  101188. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  101189. var t1x;
  101190. var t1y;
  101191. var t1z;
  101192. var t2x;
  101193. var t2y;
  101194. var t2z;
  101195. var sup = new OIMO.Vec3();
  101196. var len;
  101197. var p1x;
  101198. var p1y;
  101199. var p1z;
  101200. var p2x;
  101201. var p2y;
  101202. var p2z;
  101203. var v01x = c1.position.x;
  101204. var v01y = c1.position.y;
  101205. var v01z = c1.position.z;
  101206. var v02x = c2.position.x;
  101207. var v02y = c2.position.y;
  101208. var v02z = c2.position.z;
  101209. var v0x = v02x - v01x;
  101210. var v0y = v02y - v01y;
  101211. var v0z = v02z - v01z;
  101212. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  101213. var nx = -v0x;
  101214. var ny = -v0y;
  101215. var nz = -v0z;
  101216. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101217. var v11x = sup.x;
  101218. var v11y = sup.y;
  101219. var v11z = sup.z;
  101220. this.supportPointC(c2, nx, ny, nz, sup);
  101221. var v12x = sup.x;
  101222. var v12y = sup.y;
  101223. var v12z = sup.z;
  101224. var v1x = v12x - v11x;
  101225. var v1y = v12y - v11y;
  101226. var v1z = v12z - v11z;
  101227. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  101228. return false;
  101229. }
  101230. nx = v1y * v0z - v1z * v0y;
  101231. ny = v1z * v0x - v1x * v0z;
  101232. nz = v1x * v0y - v1y * v0x;
  101233. if (nx * nx + ny * ny + nz * nz == 0) {
  101234. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  101235. sep.normalize(sep);
  101236. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  101237. return true;
  101238. }
  101239. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101240. var v21x = sup.x;
  101241. var v21y = sup.y;
  101242. var v21z = sup.z;
  101243. this.supportPointC(c2, nx, ny, nz, sup);
  101244. var v22x = sup.x;
  101245. var v22y = sup.y;
  101246. var v22z = sup.z;
  101247. var v2x = v22x - v21x;
  101248. var v2y = v22y - v21y;
  101249. var v2z = v22z - v21z;
  101250. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  101251. return false;
  101252. }
  101253. t1x = v1x - v0x;
  101254. t1y = v1y - v0y;
  101255. t1z = v1z - v0z;
  101256. t2x = v2x - v0x;
  101257. t2y = v2y - v0y;
  101258. t2z = v2z - v0z;
  101259. nx = t1y * t2z - t1z * t2y;
  101260. ny = t1z * t2x - t1x * t2z;
  101261. nz = t1x * t2y - t1y * t2x;
  101262. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  101263. t1x = v1x;
  101264. t1y = v1y;
  101265. t1z = v1z;
  101266. v1x = v2x;
  101267. v1y = v2y;
  101268. v1z = v2z;
  101269. v2x = t1x;
  101270. v2y = t1y;
  101271. v2z = t1z;
  101272. t1x = v11x;
  101273. t1y = v11y;
  101274. t1z = v11z;
  101275. v11x = v21x;
  101276. v11y = v21y;
  101277. v11z = v21z;
  101278. v21x = t1x;
  101279. v21y = t1y;
  101280. v21z = t1z;
  101281. t1x = v12x;
  101282. t1y = v12y;
  101283. t1z = v12z;
  101284. v12x = v22x;
  101285. v12y = v22y;
  101286. v12z = v22z;
  101287. v22x = t1x;
  101288. v22y = t1y;
  101289. v22z = t1z;
  101290. nx = -nx;
  101291. ny = -ny;
  101292. nz = -nz;
  101293. }
  101294. var iterations = 0;
  101295. while (true) {
  101296. if (++iterations > 100) {
  101297. return false;
  101298. }
  101299. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101300. var v31x = sup.x;
  101301. var v31y = sup.y;
  101302. var v31z = sup.z;
  101303. this.supportPointC(c2, nx, ny, nz, sup);
  101304. var v32x = sup.x;
  101305. var v32y = sup.y;
  101306. var v32z = sup.z;
  101307. var v3x = v32x - v31x;
  101308. var v3y = v32y - v31y;
  101309. var v3z = v32z - v31z;
  101310. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  101311. return false;
  101312. }
  101313. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  101314. v2x = v3x;
  101315. v2y = v3y;
  101316. v2z = v3z;
  101317. v21x = v31x;
  101318. v21y = v31y;
  101319. v21z = v31z;
  101320. v22x = v32x;
  101321. v22y = v32y;
  101322. v22z = v32z;
  101323. t1x = v1x - v0x;
  101324. t1y = v1y - v0y;
  101325. t1z = v1z - v0z;
  101326. t2x = v3x - v0x;
  101327. t2y = v3y - v0y;
  101328. t2z = v3z - v0z;
  101329. nx = t1y * t2z - t1z * t2y;
  101330. ny = t1z * t2x - t1x * t2z;
  101331. nz = t1x * t2y - t1y * t2x;
  101332. continue;
  101333. }
  101334. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  101335. v1x = v3x;
  101336. v1y = v3y;
  101337. v1z = v3z;
  101338. v11x = v31x;
  101339. v11y = v31y;
  101340. v11z = v31z;
  101341. v12x = v32x;
  101342. v12y = v32y;
  101343. v12z = v32z;
  101344. t1x = v3x - v0x;
  101345. t1y = v3y - v0y;
  101346. t1z = v3z - v0z;
  101347. t2x = v2x - v0x;
  101348. t2y = v2y - v0y;
  101349. t2z = v2z - v0z;
  101350. nx = t1y * t2z - t1z * t2y;
  101351. ny = t1z * t2x - t1x * t2z;
  101352. nz = t1x * t2y - t1y * t2x;
  101353. continue;
  101354. }
  101355. var hit = false;
  101356. while (true) {
  101357. t1x = v2x - v1x;
  101358. t1y = v2y - v1y;
  101359. t1z = v2z - v1z;
  101360. t2x = v3x - v1x;
  101361. t2y = v3y - v1y;
  101362. t2z = v3z - v1z;
  101363. nx = t1y * t2z - t1z * t2y;
  101364. ny = t1z * t2x - t1x * t2z;
  101365. nz = t1x * t2y - t1y * t2x;
  101366. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  101367. nx *= len;
  101368. ny *= len;
  101369. nz *= len;
  101370. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  101371. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  101372. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  101373. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  101374. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  101375. var sum = b0 + b1 + b2 + b3;
  101376. if (sum <= 0) {
  101377. b0 = 0;
  101378. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  101379. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  101380. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  101381. sum = b1 + b2 + b3;
  101382. }
  101383. var inv = 1 / sum;
  101384. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  101385. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  101386. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  101387. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  101388. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  101389. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  101390. hit = true;
  101391. }
  101392. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101393. var v41x = sup.x;
  101394. var v41y = sup.y;
  101395. var v41z = sup.z;
  101396. this.supportPointC(c2, nx, ny, nz, sup);
  101397. var v42x = sup.x;
  101398. var v42y = sup.y;
  101399. var v42z = sup.z;
  101400. var v4x = v42x - v41x;
  101401. var v4y = v42y - v41y;
  101402. var v4z = v42z - v41z;
  101403. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  101404. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  101405. if (hit) {
  101406. sep.init(-nx, -ny, -nz);
  101407. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  101408. dep.x = separation;
  101409. return true;
  101410. }
  101411. return false;
  101412. }
  101413. if (
  101414. (v4y * v1z - v4z * v1y) * v0x +
  101415. (v4z * v1x - v4x * v1z) * v0y +
  101416. (v4x * v1y - v4y * v1x) * v0z < 0
  101417. ) {
  101418. if (
  101419. (v4y * v2z - v4z * v2y) * v0x +
  101420. (v4z * v2x - v4x * v2z) * v0y +
  101421. (v4x * v2y - v4y * v2x) * v0z < 0
  101422. ) {
  101423. v1x = v4x;
  101424. v1y = v4y;
  101425. v1z = v4z;
  101426. v11x = v41x;
  101427. v11y = v41y;
  101428. v11z = v41z;
  101429. v12x = v42x;
  101430. v12y = v42y;
  101431. v12z = v42z;
  101432. } else {
  101433. v3x = v4x;
  101434. v3y = v4y;
  101435. v3z = v4z;
  101436. v31x = v41x;
  101437. v31y = v41y;
  101438. v31z = v41z;
  101439. v32x = v42x;
  101440. v32y = v42y;
  101441. v32z = v42z;
  101442. }
  101443. } else {
  101444. if (
  101445. (v4y * v3z - v4z * v3y) * v0x +
  101446. (v4z * v3x - v4x * v3z) * v0y +
  101447. (v4x * v3y - v4y * v3x) * v0z < 0
  101448. ) {
  101449. v2x = v4x;
  101450. v2y = v4y;
  101451. v2z = v4z;
  101452. v21x = v41x;
  101453. v21y = v41y;
  101454. v21z = v41z;
  101455. v22x = v42x;
  101456. v22y = v42y;
  101457. v22z = v42z;
  101458. } else {
  101459. v1x = v4x;
  101460. v1y = v4y;
  101461. v1z = v4z;
  101462. v11x = v41x;
  101463. v11y = v41y;
  101464. v11z = v41z;
  101465. v12x = v42x;
  101466. v12y = v42y;
  101467. v12z = v42z;
  101468. }
  101469. }
  101470. }
  101471. }
  101472. //return false;
  101473. };
  101474. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  101475. var rot = c.rotation.elements;
  101476. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101477. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101478. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101479. var w = c.halfWidth;
  101480. var h = c.halfHeight;
  101481. var d = c.halfDepth;
  101482. var ox;
  101483. var oy;
  101484. var oz;
  101485. if (ldx < 0) ox = -w;
  101486. else ox = w;
  101487. if (ldy < 0) oy = -h;
  101488. else oy = h;
  101489. if (ldz < 0) oz = -d;
  101490. else oz = d;
  101491. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101492. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101493. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101494. out.init(ldx, ldy, ldz);
  101495. };
  101496. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  101497. var rot = c.rotation.elements;
  101498. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101499. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101500. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101501. var radx = ldx;
  101502. var radz = ldz;
  101503. var len = radx * radx + radz * radz;
  101504. var rad = c.radius;
  101505. var hh = c.halfHeight;
  101506. var ox;
  101507. var oy;
  101508. var oz;
  101509. if (len == 0) {
  101510. if (ldy < 0) {
  101511. ox = rad;
  101512. oy = -hh;
  101513. oz = 0;
  101514. } else {
  101515. ox = rad;
  101516. oy = hh;
  101517. oz = 0;
  101518. }
  101519. } else {
  101520. len = c.radius / OIMO.sqrt(len);
  101521. if (ldy < 0) {
  101522. ox = radx * len;
  101523. oy = -hh;
  101524. oz = radz * len;
  101525. } else {
  101526. ox = radx * len;
  101527. oy = hh;
  101528. oz = radz * len;
  101529. }
  101530. }
  101531. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101532. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101533. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101534. out.init(ldx, ldy, ldz);
  101535. };
  101536. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101537. var b;
  101538. var c;
  101539. if (this.flip) {
  101540. b = shape2;
  101541. c = shape1;
  101542. } else {
  101543. b = shape1;
  101544. c = shape2;
  101545. }
  101546. var sep = new OIMO.Vec3();
  101547. var pos = new OIMO.Vec3();
  101548. var dep = new OIMO.Vec3();
  101549. var co;
  101550. if (!this.getSep(b, c, sep, pos, dep)) return;
  101551. var pbx = b.position.x;
  101552. var pby = b.position.y;
  101553. var pbz = b.position.z;
  101554. var pcx = c.position.x;
  101555. var pcy = c.position.y;
  101556. var pcz = c.position.z;
  101557. var bw = b.halfWidth;
  101558. var bh = b.halfHeight;
  101559. var bd = b.halfDepth;
  101560. var ch = c.halfHeight;
  101561. var r = c.radius;
  101562. var D = b.dimentions;
  101563. var nwx = D[0];//b.normalDirectionWidth.x;
  101564. var nwy = D[1];//b.normalDirectionWidth.y;
  101565. var nwz = D[2];//b.normalDirectionWidth.z;
  101566. var nhx = D[3];//b.normalDirectionHeight.x;
  101567. var nhy = D[4];//b.normalDirectionHeight.y;
  101568. var nhz = D[5];//b.normalDirectionHeight.z;
  101569. var ndx = D[6];//b.normalDirectionDepth.x;
  101570. var ndy = D[7];//b.normalDirectionDepth.y;
  101571. var ndz = D[8];//b.normalDirectionDepth.z;
  101572. var dwx = D[9];//b.halfDirectionWidth.x;
  101573. var dwy = D[10];//b.halfDirectionWidth.y;
  101574. var dwz = D[11];//b.halfDirectionWidth.z;
  101575. var dhx = D[12];//b.halfDirectionHeight.x;
  101576. var dhy = D[13];//b.halfDirectionHeight.y;
  101577. var dhz = D[14];//b.halfDirectionHeight.z;
  101578. var ddx = D[15];//b.halfDirectionDepth.x;
  101579. var ddy = D[16];//b.halfDirectionDepth.y;
  101580. var ddz = D[17];//b.halfDirectionDepth.z;
  101581. var ncx = c.normalDirection.x;
  101582. var ncy = c.normalDirection.y;
  101583. var ncz = c.normalDirection.z;
  101584. var dcx = c.halfDirection.x;
  101585. var dcy = c.halfDirection.y;
  101586. var dcz = c.halfDirection.z;
  101587. var nx = sep.x;
  101588. var ny = sep.y;
  101589. var nz = sep.z;
  101590. var dotw = nx * nwx + ny * nwy + nz * nwz;
  101591. var doth = nx * nhx + ny * nhy + nz * nhz;
  101592. var dotd = nx * ndx + ny * ndy + nz * ndz;
  101593. var dotc = nx * ncx + ny * ncy + nz * ncz;
  101594. var right1 = dotw > 0;
  101595. var right2 = doth > 0;
  101596. var right3 = dotd > 0;
  101597. var right4 = dotc > 0;
  101598. if (!right1) dotw = -dotw;
  101599. if (!right2) doth = -doth;
  101600. if (!right3) dotd = -dotd;
  101601. if (!right4) dotc = -dotc;
  101602. var state = 0;
  101603. if (dotc > 0.999) {
  101604. if (dotw > 0.999) {
  101605. if (dotw > dotc) state = 1;
  101606. else state = 4;
  101607. } else if (doth > 0.999) {
  101608. if (doth > dotc) state = 2;
  101609. else state = 4;
  101610. } else if (dotd > 0.999) {
  101611. if (dotd > dotc) state = 3;
  101612. else state = 4;
  101613. } else state = 4;
  101614. } else {
  101615. if (dotw > 0.999) state = 1;
  101616. else if (doth > 0.999) state = 2;
  101617. else if (dotd > 0.999) state = 3;
  101618. }
  101619. var cbx;
  101620. var cby;
  101621. var cbz;
  101622. var ccx;
  101623. var ccy;
  101624. var ccz;
  101625. var r00;
  101626. var r01;
  101627. var r02;
  101628. var r10;
  101629. var r11;
  101630. var r12;
  101631. var r20;
  101632. var r21;
  101633. var r22;
  101634. var px;
  101635. var py;
  101636. var pz;
  101637. var pd;
  101638. var dot;
  101639. var len;
  101640. var tx;
  101641. var ty;
  101642. var tz;
  101643. var td;
  101644. var dx;
  101645. var dy;
  101646. var dz;
  101647. var d1x;
  101648. var d1y;
  101649. var d1z;
  101650. var d2x;
  101651. var d2y;
  101652. var d2z;
  101653. var sx;
  101654. var sy;
  101655. var sz;
  101656. var sd;
  101657. var ex;
  101658. var ey;
  101659. var ez;
  101660. var ed;
  101661. var dot1;
  101662. var dot2;
  101663. var t1;
  101664. var t2;
  101665. var dir1x;
  101666. var dir1y;
  101667. var dir1z;
  101668. var dir2x;
  101669. var dir2y;
  101670. var dir2z;
  101671. var dir1l;
  101672. var dir2l;
  101673. if (state == 0) {
  101674. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  101675. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  101676. } else if (state == 4) {
  101677. if (right4) {
  101678. ccx = pcx - dcx;
  101679. ccy = pcy - dcy;
  101680. ccz = pcz - dcz;
  101681. nx = -ncx;
  101682. ny = -ncy;
  101683. nz = -ncz;
  101684. } else {
  101685. ccx = pcx + dcx;
  101686. ccy = pcy + dcy;
  101687. ccz = pcz + dcz;
  101688. nx = ncx;
  101689. ny = ncy;
  101690. nz = ncz;
  101691. }
  101692. var v1x;
  101693. var v1y;
  101694. var v1z;
  101695. var v2x;
  101696. var v2y;
  101697. var v2z;
  101698. var v3x;
  101699. var v3y;
  101700. var v3z;
  101701. var v4x;
  101702. var v4y;
  101703. var v4z;
  101704. dot = 1;
  101705. state = 0;
  101706. dot1 = nwx * nx + nwy * ny + nwz * nz;
  101707. if (dot1 < dot) {
  101708. dot = dot1;
  101709. state = 0;
  101710. }
  101711. if (-dot1 < dot) {
  101712. dot = -dot1;
  101713. state = 1;
  101714. }
  101715. dot1 = nhx * nx + nhy * ny + nhz * nz;
  101716. if (dot1 < dot) {
  101717. dot = dot1;
  101718. state = 2;
  101719. }
  101720. if (-dot1 < dot) {
  101721. dot = -dot1;
  101722. state = 3;
  101723. }
  101724. dot1 = ndx * nx + ndy * ny + ndz * nz;
  101725. if (dot1 < dot) {
  101726. dot = dot1;
  101727. state = 4;
  101728. }
  101729. if (-dot1 < dot) {
  101730. dot = -dot1;
  101731. state = 5;
  101732. }
  101733. var v = b.elements;
  101734. switch (state) {
  101735. case 0:
  101736. //v=b.vertex1;
  101737. v1x = v[0];//v.x;
  101738. v1y = v[1];//v.y;
  101739. v1z = v[2];//v.z;
  101740. //v=b.vertex3;
  101741. v2x = v[6];//v.x;
  101742. v2y = v[7];//v.y;
  101743. v2z = v[8];//v.z;
  101744. //v=b.vertex4;
  101745. v3x = v[9];//v.x;
  101746. v3y = v[10];//v.y;
  101747. v3z = v[11];//v.z;
  101748. //v=b.vertex2;
  101749. v4x = v[3];//v.x;
  101750. v4y = v[4];//v.y;
  101751. v4z = v[5];//v.z;
  101752. break;
  101753. case 1:
  101754. //v=b.vertex6;
  101755. v1x = v[15];//v.x;
  101756. v1y = v[16];//v.y;
  101757. v1z = v[17];//v.z;
  101758. //v=b.vertex8;
  101759. v2x = v[21];//v.x;
  101760. v2y = v[22];//v.y;
  101761. v2z = v[23];//v.z;
  101762. //v=b.vertex7;
  101763. v3x = v[18];//v.x;
  101764. v3y = v[19];//v.y;
  101765. v3z = v[20];//v.z;
  101766. //v=b.vertex5;
  101767. v4x = v[12];//v.x;
  101768. v4y = v[13];//v.y;
  101769. v4z = v[14];//v.z;
  101770. break;
  101771. case 2:
  101772. //v=b.vertex5;
  101773. v1x = v[12];//v.x;
  101774. v1y = v[13];//v.y;
  101775. v1z = v[14];//v.z;
  101776. //v=b.vertex1;
  101777. v2x = v[0];//v.x;
  101778. v2y = v[1];//v.y;
  101779. v2z = v[2];//v.z;
  101780. //v=b.vertex2;
  101781. v3x = v[3];//v.x;
  101782. v3y = v[4];//v.y;
  101783. v3z = v[5];//v.z;
  101784. //v=b.vertex6;
  101785. v4x = v[15];//v.x;
  101786. v4y = v[16];//v.y;
  101787. v4z = v[17];//v.z;
  101788. break;
  101789. case 3:
  101790. //v=b.vertex8;
  101791. v1x = v[21];//v.x;
  101792. v1y = v[22];//v.y;
  101793. v1z = v[23];//v.z;
  101794. //v=b.vertex4;
  101795. v2x = v[9];//v.x;
  101796. v2y = v[10];//v.y;
  101797. v2z = v[11];//v.z;
  101798. //v=b.vertex3;
  101799. v3x = v[6];//v.x;
  101800. v3y = v[7];//v.y;
  101801. v3z = v[8];//v.z;
  101802. //v=b.vertex7;
  101803. v4x = v[18];//v.x;
  101804. v4y = v[19];//v.y;
  101805. v4z = v[20];//v.z;
  101806. break;
  101807. case 4:
  101808. //v=b.vertex5;
  101809. v1x = v[12];//v.x;
  101810. v1y = v[13];//v.y;
  101811. v1z = v[14];//v.z;
  101812. //v=b.vertex7;
  101813. v2x = v[18];//v.x;
  101814. v2y = v[19];//v.y;
  101815. v2z = v[20];//v.z;
  101816. //v=b.vertex3;
  101817. v3x = v[6];//v.x;
  101818. v3y = v[7];//v.y;
  101819. v3z = v[8];//v.z;
  101820. //v=b.vertex1;
  101821. v4x = v[0];//v.x;
  101822. v4y = v[1];//v.y;
  101823. v4z = v[2];//v.z;
  101824. break;
  101825. case 5:
  101826. //v=b.vertex2;
  101827. v1x = v[3];//v.x;
  101828. v1y = v[4];//v.y;
  101829. v1z = v[5];//v.z;
  101830. //v=b.vertex4;
  101831. v2x = v[9];//v.x;
  101832. v2y = v[10];//v.y;
  101833. v2z = v[11];//v.z;
  101834. //v=b.vertex8;
  101835. v3x = v[21];//v.x;
  101836. v3y = v[22];//v.y;
  101837. v3z = v[23];//v.z;
  101838. //v=b.vertex6;
  101839. v4x = v[15];//v.x;
  101840. v4y = v[16];//v.y;
  101841. v4z = v[17];//v.z;
  101842. break;
  101843. }
  101844. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  101845. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  101846. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  101847. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  101848. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  101849. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  101850. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  101851. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  101852. } else {
  101853. switch (state) {
  101854. case 1:
  101855. if (right1) {
  101856. cbx = pbx + dwx;
  101857. cby = pby + dwy;
  101858. cbz = pbz + dwz;
  101859. nx = nwx;
  101860. ny = nwy;
  101861. nz = nwz;
  101862. } else {
  101863. cbx = pbx - dwx;
  101864. cby = pby - dwy;
  101865. cbz = pbz - dwz;
  101866. nx = -nwx;
  101867. ny = -nwy;
  101868. nz = -nwz;
  101869. }
  101870. dir1x = nhx;
  101871. dir1y = nhy;
  101872. dir1z = nhz;
  101873. dir1l = bh;
  101874. dir2x = ndx;
  101875. dir2y = ndy;
  101876. dir2z = ndz;
  101877. dir2l = bd;
  101878. break;
  101879. case 2:
  101880. if (right2) {
  101881. cbx = pbx + dhx;
  101882. cby = pby + dhy;
  101883. cbz = pbz + dhz;
  101884. nx = nhx;
  101885. ny = nhy;
  101886. nz = nhz;
  101887. } else {
  101888. cbx = pbx - dhx;
  101889. cby = pby - dhy;
  101890. cbz = pbz - dhz;
  101891. nx = -nhx;
  101892. ny = -nhy;
  101893. nz = -nhz;
  101894. }
  101895. dir1x = nwx;
  101896. dir1y = nwy;
  101897. dir1z = nwz;
  101898. dir1l = bw;
  101899. dir2x = ndx;
  101900. dir2y = ndy;
  101901. dir2z = ndz;
  101902. dir2l = bd;
  101903. break;
  101904. case 3:
  101905. if (right3) {
  101906. cbx = pbx + ddx;
  101907. cby = pby + ddy;
  101908. cbz = pbz + ddz;
  101909. nx = ndx;
  101910. ny = ndy;
  101911. nz = ndz;
  101912. } else {
  101913. cbx = pbx - ddx;
  101914. cby = pby - ddy;
  101915. cbz = pbz - ddz;
  101916. nx = -ndx;
  101917. ny = -ndy;
  101918. nz = -ndz;
  101919. }
  101920. dir1x = nwx;
  101921. dir1y = nwy;
  101922. dir1z = nwz;
  101923. dir1l = bw;
  101924. dir2x = nhx;
  101925. dir2y = nhy;
  101926. dir2z = nhz;
  101927. dir2l = bh;
  101928. break;
  101929. }
  101930. dot = nx * ncx + ny * ncy + nz * ncz;
  101931. if (dot < 0) len = ch;
  101932. else len = -ch;
  101933. ccx = pcx + len * ncx;
  101934. ccy = pcy + len * ncy;
  101935. ccz = pcz + len * ncz;
  101936. if (dotc >= 0.999999) {
  101937. tx = -ny;
  101938. ty = nz;
  101939. tz = nx;
  101940. } else {
  101941. tx = nx;
  101942. ty = ny;
  101943. tz = nz;
  101944. }
  101945. len = tx * ncx + ty * ncy + tz * ncz;
  101946. dx = len * ncx - tx;
  101947. dy = len * ncy - ty;
  101948. dz = len * ncz - tz;
  101949. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101950. if (len == 0) return;
  101951. len = r / len;
  101952. dx *= len;
  101953. dy *= len;
  101954. dz *= len;
  101955. tx = ccx + dx;
  101956. ty = ccy + dy;
  101957. tz = ccz + dz;
  101958. if (dot < -0.96 || dot > 0.96) {
  101959. r00 = ncx * ncx * 1.5 - 0.5;
  101960. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  101961. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  101962. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  101963. r11 = ncy * ncy * 1.5 - 0.5;
  101964. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  101965. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  101966. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  101967. r22 = ncz * ncz * 1.5 - 0.5;
  101968. px = tx;
  101969. py = ty;
  101970. pz = tz;
  101971. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101972. tx = px - pd * nx - cbx;
  101973. ty = py - pd * ny - cby;
  101974. tz = pz - pd * nz - cbz;
  101975. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101976. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101977. if (sd < -dir1l) sd = -dir1l;
  101978. else if (sd > dir1l) sd = dir1l;
  101979. if (ed < -dir2l) ed = -dir2l;
  101980. else if (ed > dir2l) ed = dir2l;
  101981. tx = sd * dir1x + ed * dir2x;
  101982. ty = sd * dir1y + ed * dir2y;
  101983. tz = sd * dir1z + ed * dir2z;
  101984. px = cbx + tx;
  101985. py = cby + ty;
  101986. pz = cbz + tz;
  101987. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101988. px = dx * r00 + dy * r01 + dz * r02;
  101989. py = dx * r10 + dy * r11 + dz * r12;
  101990. pz = dx * r20 + dy * r21 + dz * r22;
  101991. px = (dx = px) + ccx;
  101992. py = (dy = py) + ccy;
  101993. pz = (dz = pz) + ccz;
  101994. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101995. if (pd <= 0) {
  101996. tx = px - pd * nx - cbx;
  101997. ty = py - pd * ny - cby;
  101998. tz = pz - pd * nz - cbz;
  101999. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  102000. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  102001. if (sd < -dir1l) sd = -dir1l;
  102002. else if (sd > dir1l) sd = dir1l;
  102003. if (ed < -dir2l) ed = -dir2l;
  102004. else if (ed > dir2l) ed = dir2l;
  102005. tx = sd * dir1x + ed * dir2x;
  102006. ty = sd * dir1y + ed * dir2y;
  102007. tz = sd * dir1z + ed * dir2z;
  102008. px = cbx + tx;
  102009. py = cby + ty;
  102010. pz = cbz + tz;
  102011. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  102012. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  102013. }
  102014. px = dx * r00 + dy * r01 + dz * r02;
  102015. py = dx * r10 + dy * r11 + dz * r12;
  102016. pz = dx * r20 + dy * r21 + dz * r22;
  102017. px = (dx = px) + ccx;
  102018. py = (dy = py) + ccy;
  102019. pz = (dz = pz) + ccz;
  102020. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  102021. if (pd <= 0) {
  102022. tx = px - pd * nx - cbx;
  102023. ty = py - pd * ny - cby;
  102024. tz = pz - pd * nz - cbz;
  102025. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  102026. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  102027. if (sd < -dir1l) sd = -dir1l;
  102028. else if (sd > dir1l) sd = dir1l;
  102029. if (ed < -dir2l) ed = -dir2l;
  102030. else if (ed > dir2l) ed = dir2l;
  102031. tx = sd * dir1x + ed * dir2x;
  102032. ty = sd * dir1y + ed * dir2y;
  102033. tz = sd * dir1z + ed * dir2z;
  102034. px = cbx + tx;
  102035. py = cby + ty;
  102036. pz = cbz + tz;
  102037. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  102038. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  102039. }
  102040. } else {
  102041. sx = tx;
  102042. sy = ty;
  102043. sz = tz;
  102044. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  102045. sx -= sd * nx;
  102046. sy -= sd * ny;
  102047. sz -= sd * nz;
  102048. if (dot > 0) {
  102049. ex = tx + dcx * 2;
  102050. ey = ty + dcy * 2;
  102051. ez = tz + dcz * 2;
  102052. } else {
  102053. ex = tx - dcx * 2;
  102054. ey = ty - dcy * 2;
  102055. ez = tz - dcz * 2;
  102056. }
  102057. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  102058. ex -= ed * nx;
  102059. ey -= ed * ny;
  102060. ez -= ed * nz;
  102061. d1x = sx - cbx;
  102062. d1y = sy - cby;
  102063. d1z = sz - cbz;
  102064. d2x = ex - cbx;
  102065. d2y = ey - cby;
  102066. d2z = ez - cbz;
  102067. tx = ex - sx;
  102068. ty = ey - sy;
  102069. tz = ez - sz;
  102070. td = ed - sd;
  102071. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  102072. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  102073. dot1 = dotw - dir1l;
  102074. dot2 = doth - dir1l;
  102075. if (dot1 > 0) {
  102076. if (dot2 > 0) return;
  102077. t1 = dot1 / (dot1 - dot2);
  102078. sx = sx + tx * t1;
  102079. sy = sy + ty * t1;
  102080. sz = sz + tz * t1;
  102081. sd = sd + td * t1;
  102082. d1x = sx - cbx;
  102083. d1y = sy - cby;
  102084. d1z = sz - cbz;
  102085. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  102086. tx = ex - sx;
  102087. ty = ey - sy;
  102088. tz = ez - sz;
  102089. td = ed - sd;
  102090. } else if (dot2 > 0) {
  102091. t1 = dot1 / (dot1 - dot2);
  102092. ex = sx + tx * t1;
  102093. ey = sy + ty * t1;
  102094. ez = sz + tz * t1;
  102095. ed = sd + td * t1;
  102096. d2x = ex - cbx;
  102097. d2y = ey - cby;
  102098. d2z = ez - cbz;
  102099. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  102100. tx = ex - sx;
  102101. ty = ey - sy;
  102102. tz = ez - sz;
  102103. td = ed - sd;
  102104. }
  102105. dot1 = dotw + dir1l;
  102106. dot2 = doth + dir1l;
  102107. if (dot1 < 0) {
  102108. if (dot2 < 0) return;
  102109. t1 = dot1 / (dot1 - dot2);
  102110. sx = sx + tx * t1;
  102111. sy = sy + ty * t1;
  102112. sz = sz + tz * t1;
  102113. sd = sd + td * t1;
  102114. d1x = sx - cbx;
  102115. d1y = sy - cby;
  102116. d1z = sz - cbz;
  102117. tx = ex - sx;
  102118. ty = ey - sy;
  102119. tz = ez - sz;
  102120. td = ed - sd;
  102121. } else if (dot2 < 0) {
  102122. t1 = dot1 / (dot1 - dot2);
  102123. ex = sx + tx * t1;
  102124. ey = sy + ty * t1;
  102125. ez = sz + tz * t1;
  102126. ed = sd + td * t1;
  102127. d2x = ex - cbx;
  102128. d2y = ey - cby;
  102129. d2z = ez - cbz;
  102130. tx = ex - sx;
  102131. ty = ey - sy;
  102132. tz = ez - sz;
  102133. td = ed - sd;
  102134. }
  102135. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  102136. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  102137. dot1 = dotw - dir2l;
  102138. dot2 = doth - dir2l;
  102139. if (dot1 > 0) {
  102140. if (dot2 > 0) return;
  102141. t1 = dot1 / (dot1 - dot2);
  102142. sx = sx + tx * t1;
  102143. sy = sy + ty * t1;
  102144. sz = sz + tz * t1;
  102145. sd = sd + td * t1;
  102146. d1x = sx - cbx;
  102147. d1y = sy - cby;
  102148. d1z = sz - cbz;
  102149. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  102150. tx = ex - sx;
  102151. ty = ey - sy;
  102152. tz = ez - sz;
  102153. td = ed - sd;
  102154. } else if (dot2 > 0) {
  102155. t1 = dot1 / (dot1 - dot2);
  102156. ex = sx + tx * t1;
  102157. ey = sy + ty * t1;
  102158. ez = sz + tz * t1;
  102159. ed = sd + td * t1;
  102160. d2x = ex - cbx;
  102161. d2y = ey - cby;
  102162. d2z = ez - cbz;
  102163. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  102164. tx = ex - sx;
  102165. ty = ey - sy;
  102166. tz = ez - sz;
  102167. td = ed - sd;
  102168. }
  102169. dot1 = dotw + dir2l;
  102170. dot2 = doth + dir2l;
  102171. if (dot1 < 0) {
  102172. if (dot2 < 0) return;
  102173. t1 = dot1 / (dot1 - dot2);
  102174. sx = sx + tx * t1;
  102175. sy = sy + ty * t1;
  102176. sz = sz + tz * t1;
  102177. sd = sd + td * t1;
  102178. } else if (dot2 < 0) {
  102179. t1 = dot1 / (dot1 - dot2);
  102180. ex = sx + tx * t1;
  102181. ey = sy + ty * t1;
  102182. ez = sz + tz * t1;
  102183. ed = sd + td * t1;
  102184. }
  102185. if (sd < 0) {
  102186. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  102187. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  102188. }
  102189. if (ed < 0) {
  102190. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  102191. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  102192. }
  102193. }
  102194. }
  102195. };
  102196. OIMO.CylinderCylinderCollisionDetector = function () {
  102197. OIMO.CollisionDetector.call(this);
  102198. };
  102199. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102200. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  102201. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  102202. var t1x;
  102203. var t1y;
  102204. var t1z;
  102205. var t2x;
  102206. var t2y;
  102207. var t2z;
  102208. var sup = new OIMO.Vec3();
  102209. var len;
  102210. var p1x;
  102211. var p1y;
  102212. var p1z;
  102213. var p2x;
  102214. var p2y;
  102215. var p2z;
  102216. var v01x = c1.position.x;
  102217. var v01y = c1.position.y;
  102218. var v01z = c1.position.z;
  102219. var v02x = c2.position.x;
  102220. var v02y = c2.position.y;
  102221. var v02z = c2.position.z;
  102222. var v0x = v02x - v01x;
  102223. var v0y = v02y - v01y;
  102224. var v0z = v02z - v01z;
  102225. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  102226. var nx = -v0x;
  102227. var ny = -v0y;
  102228. var nz = -v0z;
  102229. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102230. var v11x = sup.x;
  102231. var v11y = sup.y;
  102232. var v11z = sup.z;
  102233. this.supportPoint(c2, nx, ny, nz, sup);
  102234. var v12x = sup.x;
  102235. var v12y = sup.y;
  102236. var v12z = sup.z;
  102237. var v1x = v12x - v11x;
  102238. var v1y = v12y - v11y;
  102239. var v1z = v12z - v11z;
  102240. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  102241. return false;
  102242. }
  102243. nx = v1y * v0z - v1z * v0y;
  102244. ny = v1z * v0x - v1x * v0z;
  102245. nz = v1x * v0y - v1y * v0x;
  102246. if (nx * nx + ny * ny + nz * nz == 0) {
  102247. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  102248. sep.normalize(sep);
  102249. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  102250. return true;
  102251. }
  102252. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102253. var v21x = sup.x;
  102254. var v21y = sup.y;
  102255. var v21z = sup.z;
  102256. this.supportPoint(c2, nx, ny, nz, sup);
  102257. var v22x = sup.x;
  102258. var v22y = sup.y;
  102259. var v22z = sup.z;
  102260. var v2x = v22x - v21x;
  102261. var v2y = v22y - v21y;
  102262. var v2z = v22z - v21z;
  102263. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  102264. return false;
  102265. }
  102266. t1x = v1x - v0x;
  102267. t1y = v1y - v0y;
  102268. t1z = v1z - v0z;
  102269. t2x = v2x - v0x;
  102270. t2y = v2y - v0y;
  102271. t2z = v2z - v0z;
  102272. nx = t1y * t2z - t1z * t2y;
  102273. ny = t1z * t2x - t1x * t2z;
  102274. nz = t1x * t2y - t1y * t2x;
  102275. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  102276. t1x = v1x;
  102277. t1y = v1y;
  102278. t1z = v1z;
  102279. v1x = v2x;
  102280. v1y = v2y;
  102281. v1z = v2z;
  102282. v2x = t1x;
  102283. v2y = t1y;
  102284. v2z = t1z;
  102285. t1x = v11x;
  102286. t1y = v11y;
  102287. t1z = v11z;
  102288. v11x = v21x;
  102289. v11y = v21y;
  102290. v11z = v21z;
  102291. v21x = t1x;
  102292. v21y = t1y;
  102293. v21z = t1z;
  102294. t1x = v12x;
  102295. t1y = v12y;
  102296. t1z = v12z;
  102297. v12x = v22x;
  102298. v12y = v22y;
  102299. v12z = v22z;
  102300. v22x = t1x;
  102301. v22y = t1y;
  102302. v22z = t1z;
  102303. nx = -nx;
  102304. ny = -ny;
  102305. nz = -nz;
  102306. }
  102307. var iterations = 0;
  102308. while (true) {
  102309. if (++iterations > 100) {
  102310. return false;
  102311. }
  102312. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102313. var v31x = sup.x;
  102314. var v31y = sup.y;
  102315. var v31z = sup.z;
  102316. this.supportPoint(c2, nx, ny, nz, sup);
  102317. var v32x = sup.x;
  102318. var v32y = sup.y;
  102319. var v32z = sup.z;
  102320. var v3x = v32x - v31x;
  102321. var v3y = v32y - v31y;
  102322. var v3z = v32z - v31z;
  102323. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  102324. return false;
  102325. }
  102326. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  102327. v2x = v3x;
  102328. v2y = v3y;
  102329. v2z = v3z;
  102330. v21x = v31x;
  102331. v21y = v31y;
  102332. v21z = v31z;
  102333. v22x = v32x;
  102334. v22y = v32y;
  102335. v22z = v32z;
  102336. t1x = v1x - v0x;
  102337. t1y = v1y - v0y;
  102338. t1z = v1z - v0z;
  102339. t2x = v3x - v0x;
  102340. t2y = v3y - v0y;
  102341. t2z = v3z - v0z;
  102342. nx = t1y * t2z - t1z * t2y;
  102343. ny = t1z * t2x - t1x * t2z;
  102344. nz = t1x * t2y - t1y * t2x;
  102345. continue;
  102346. }
  102347. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  102348. v1x = v3x;
  102349. v1y = v3y;
  102350. v1z = v3z;
  102351. v11x = v31x;
  102352. v11y = v31y;
  102353. v11z = v31z;
  102354. v12x = v32x;
  102355. v12y = v32y;
  102356. v12z = v32z;
  102357. t1x = v3x - v0x;
  102358. t1y = v3y - v0y;
  102359. t1z = v3z - v0z;
  102360. t2x = v2x - v0x;
  102361. t2y = v2y - v0y;
  102362. t2z = v2z - v0z;
  102363. nx = t1y * t2z - t1z * t2y;
  102364. ny = t1z * t2x - t1x * t2z;
  102365. nz = t1x * t2y - t1y * t2x;
  102366. continue;
  102367. }
  102368. var hit = false;
  102369. while (true) {
  102370. t1x = v2x - v1x;
  102371. t1y = v2y - v1y;
  102372. t1z = v2z - v1z;
  102373. t2x = v3x - v1x;
  102374. t2y = v3y - v1y;
  102375. t2z = v3z - v1z;
  102376. nx = t1y * t2z - t1z * t2y;
  102377. ny = t1z * t2x - t1x * t2z;
  102378. nz = t1x * t2y - t1y * t2x;
  102379. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  102380. nx *= len;
  102381. ny *= len;
  102382. nz *= len;
  102383. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  102384. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  102385. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  102386. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  102387. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  102388. var sum = b0 + b1 + b2 + b3;
  102389. if (sum <= 0) {
  102390. b0 = 0;
  102391. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  102392. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  102393. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  102394. sum = b1 + b2 + b3;
  102395. }
  102396. var inv = 1 / sum;
  102397. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  102398. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  102399. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  102400. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  102401. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  102402. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  102403. hit = true;
  102404. }
  102405. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102406. var v41x = sup.x;
  102407. var v41y = sup.y;
  102408. var v41z = sup.z;
  102409. this.supportPoint(c2, nx, ny, nz, sup);
  102410. var v42x = sup.x;
  102411. var v42y = sup.y;
  102412. var v42z = sup.z;
  102413. var v4x = v42x - v41x;
  102414. var v4y = v42y - v41y;
  102415. var v4z = v42z - v41z;
  102416. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  102417. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  102418. if (hit) {
  102419. sep.init(-nx, -ny, -nz);
  102420. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  102421. dep.x = separation;
  102422. return true;
  102423. }
  102424. return false;
  102425. }
  102426. if (
  102427. (v4y * v1z - v4z * v1y) * v0x +
  102428. (v4z * v1x - v4x * v1z) * v0y +
  102429. (v4x * v1y - v4y * v1x) * v0z < 0
  102430. ) {
  102431. if (
  102432. (v4y * v2z - v4z * v2y) * v0x +
  102433. (v4z * v2x - v4x * v2z) * v0y +
  102434. (v4x * v2y - v4y * v2x) * v0z < 0
  102435. ) {
  102436. v1x = v4x;
  102437. v1y = v4y;
  102438. v1z = v4z;
  102439. v11x = v41x;
  102440. v11y = v41y;
  102441. v11z = v41z;
  102442. v12x = v42x;
  102443. v12y = v42y;
  102444. v12z = v42z;
  102445. } else {
  102446. v3x = v4x;
  102447. v3y = v4y;
  102448. v3z = v4z;
  102449. v31x = v41x;
  102450. v31y = v41y;
  102451. v31z = v41z;
  102452. v32x = v42x;
  102453. v32y = v42y;
  102454. v32z = v42z;
  102455. }
  102456. } else {
  102457. if (
  102458. (v4y * v3z - v4z * v3y) * v0x +
  102459. (v4z * v3x - v4x * v3z) * v0y +
  102460. (v4x * v3y - v4y * v3x) * v0z < 0
  102461. ) {
  102462. v2x = v4x;
  102463. v2y = v4y;
  102464. v2z = v4z;
  102465. v21x = v41x;
  102466. v21y = v41y;
  102467. v21z = v41z;
  102468. v22x = v42x;
  102469. v22y = v42y;
  102470. v22z = v42z;
  102471. } else {
  102472. v1x = v4x;
  102473. v1y = v4y;
  102474. v1z = v4z;
  102475. v11x = v41x;
  102476. v11y = v41y;
  102477. v11z = v41z;
  102478. v12x = v42x;
  102479. v12y = v42y;
  102480. v12z = v42z;
  102481. }
  102482. }
  102483. }
  102484. }
  102485. //return false;
  102486. };
  102487. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  102488. var rot = c.rotation.elements;
  102489. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  102490. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  102491. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  102492. var radx = ldx;
  102493. var radz = ldz;
  102494. var len = radx * radx + radz * radz;
  102495. var rad = c.radius;
  102496. var hh = c.halfHeight;
  102497. var ox;
  102498. var oy;
  102499. var oz;
  102500. if (len == 0) {
  102501. if (ldy < 0) {
  102502. ox = rad;
  102503. oy = -hh;
  102504. oz = 0;
  102505. } else {
  102506. ox = rad;
  102507. oy = hh;
  102508. oz = 0;
  102509. }
  102510. } else {
  102511. len = c.radius / OIMO.sqrt(len);
  102512. if (ldy < 0) {
  102513. ox = radx * len;
  102514. oy = -hh;
  102515. oz = radz * len;
  102516. } else {
  102517. ox = radx * len;
  102518. oy = hh;
  102519. oz = radz * len;
  102520. }
  102521. }
  102522. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  102523. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  102524. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  102525. out.init(ldx, ldy, ldz);
  102526. };
  102527. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  102528. var c1;
  102529. var c2;
  102530. if (shape1.id < shape2.id) {
  102531. c1 = shape1;
  102532. c2 = shape2;
  102533. } else {
  102534. c1 = shape2;
  102535. c2 = shape1;
  102536. }
  102537. var p1 = c1.position;
  102538. var p2 = c2.position;
  102539. var p1x = p1.x;
  102540. var p1y = p1.y;
  102541. var p1z = p1.z;
  102542. var p2x = p2.x;
  102543. var p2y = p2.y;
  102544. var p2z = p2.z;
  102545. var h1 = c1.halfHeight;
  102546. var h2 = c2.halfHeight;
  102547. var n1 = c1.normalDirection;
  102548. var n2 = c2.normalDirection;
  102549. var d1 = c1.halfDirection;
  102550. var d2 = c2.halfDirection;
  102551. var r1 = c1.radius;
  102552. var r2 = c2.radius;
  102553. var n1x = n1.x;
  102554. var n1y = n1.y;
  102555. var n1z = n1.z;
  102556. var n2x = n2.x;
  102557. var n2y = n2.y;
  102558. var n2z = n2.z;
  102559. var d1x = d1.x;
  102560. var d1y = d1.y;
  102561. var d1z = d1.z;
  102562. var d2x = d2.x;
  102563. var d2y = d2.y;
  102564. var d2z = d2.z;
  102565. var dx = p1x - p2x;
  102566. var dy = p1y - p2y;
  102567. var dz = p1z - p2z;
  102568. var len;
  102569. var len1;
  102570. var len2;
  102571. var c;
  102572. var c1x;
  102573. var c1y;
  102574. var c1z;
  102575. var c2x;
  102576. var c2y;
  102577. var c2z;
  102578. var tx;
  102579. var ty;
  102580. var tz;
  102581. var sx;
  102582. var sy;
  102583. var sz;
  102584. var ex;
  102585. var ey;
  102586. var ez;
  102587. var depth1;
  102588. var depth2;
  102589. var dot;
  102590. var t1;
  102591. var t2;
  102592. var sep = new OIMO.Vec3();
  102593. var pos = new OIMO.Vec3();
  102594. var dep = new OIMO.Vec3();
  102595. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  102596. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  102597. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  102598. var right1 = dot1 > 0;
  102599. var right2 = dot2 > 0;
  102600. if (!right1) dot1 = -dot1;
  102601. if (!right2) dot2 = -dot2;
  102602. var state = 0;
  102603. if (dot1 > 0.999 || dot2 > 0.999) {
  102604. if (dot1 > dot2) state = 1;
  102605. else state = 2;
  102606. }
  102607. var nx;
  102608. var ny;
  102609. var nz;
  102610. var depth = dep.x;
  102611. var r00;
  102612. var r01;
  102613. var r02;
  102614. var r10;
  102615. var r11;
  102616. var r12;
  102617. var r20;
  102618. var r21;
  102619. var r22;
  102620. var px;
  102621. var py;
  102622. var pz;
  102623. var pd;
  102624. var a;
  102625. var b;
  102626. var e;
  102627. var f;
  102628. nx = sep.x;
  102629. ny = sep.y;
  102630. nz = sep.z;
  102631. switch (state) {
  102632. case 0:
  102633. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  102634. break;
  102635. case 1:
  102636. if (right1) {
  102637. c1x = p1x + d1x;
  102638. c1y = p1y + d1y;
  102639. c1z = p1z + d1z;
  102640. nx = n1x;
  102641. ny = n1y;
  102642. nz = n1z;
  102643. } else {
  102644. c1x = p1x - d1x;
  102645. c1y = p1y - d1y;
  102646. c1z = p1z - d1z;
  102647. nx = -n1x;
  102648. ny = -n1y;
  102649. nz = -n1z;
  102650. }
  102651. dot = nx * n2x + ny * n2y + nz * n2z;
  102652. if (dot < 0) len = h2;
  102653. else len = -h2;
  102654. c2x = p2x + len * n2x;
  102655. c2y = p2y + len * n2y;
  102656. c2z = p2z + len * n2z;
  102657. if (dot2 >= 0.999999) {
  102658. tx = -ny;
  102659. ty = nz;
  102660. tz = nx;
  102661. } else {
  102662. tx = nx;
  102663. ty = ny;
  102664. tz = nz;
  102665. }
  102666. len = tx * n2x + ty * n2y + tz * n2z;
  102667. dx = len * n2x - tx;
  102668. dy = len * n2y - ty;
  102669. dz = len * n2z - tz;
  102670. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102671. if (len == 0) break;
  102672. len = r2 / len;
  102673. dx *= len;
  102674. dy *= len;
  102675. dz *= len;
  102676. tx = c2x + dx;
  102677. ty = c2y + dy;
  102678. tz = c2z + dz;
  102679. if (dot < -0.96 || dot > 0.96) {
  102680. r00 = n2x * n2x * 1.5 - 0.5;
  102681. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  102682. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  102683. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  102684. r11 = n2y * n2y * 1.5 - 0.5;
  102685. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  102686. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  102687. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  102688. r22 = n2z * n2z * 1.5 - 0.5;
  102689. px = tx;
  102690. py = ty;
  102691. pz = tz;
  102692. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102693. tx = px - pd * nx - c1x;
  102694. ty = py - pd * ny - c1y;
  102695. tz = pz - pd * nz - c1z;
  102696. len = tx * tx + ty * ty + tz * tz;
  102697. if (len > r1 * r1) {
  102698. len = r1 / OIMO.sqrt(len);
  102699. tx *= len;
  102700. ty *= len;
  102701. tz *= len;
  102702. }
  102703. px = c1x + tx;
  102704. py = c1y + ty;
  102705. pz = c1z + tz;
  102706. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102707. px = dx * r00 + dy * r01 + dz * r02;
  102708. py = dx * r10 + dy * r11 + dz * r12;
  102709. pz = dx * r20 + dy * r21 + dz * r22;
  102710. px = (dx = px) + c2x;
  102711. py = (dy = py) + c2y;
  102712. pz = (dz = pz) + c2z;
  102713. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102714. if (pd <= 0) {
  102715. tx = px - pd * nx - c1x;
  102716. ty = py - pd * ny - c1y;
  102717. tz = pz - pd * nz - c1z;
  102718. len = tx * tx + ty * ty + tz * tz;
  102719. if (len > r1 * r1) {
  102720. len = r1 / OIMO.sqrt(len);
  102721. tx *= len;
  102722. ty *= len;
  102723. tz *= len;
  102724. }
  102725. px = c1x + tx;
  102726. py = c1y + ty;
  102727. pz = c1z + tz;
  102728. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102729. }
  102730. px = dx * r00 + dy * r01 + dz * r02;
  102731. py = dx * r10 + dy * r11 + dz * r12;
  102732. pz = dx * r20 + dy * r21 + dz * r22;
  102733. px = (dx = px) + c2x;
  102734. py = (dy = py) + c2y;
  102735. pz = (dz = pz) + c2z;
  102736. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102737. if (pd <= 0) {
  102738. tx = px - pd * nx - c1x;
  102739. ty = py - pd * ny - c1y;
  102740. tz = pz - pd * nz - c1z;
  102741. len = tx * tx + ty * ty + tz * tz;
  102742. if (len > r1 * r1) {
  102743. len = r1 / OIMO.sqrt(len);
  102744. tx *= len;
  102745. ty *= len;
  102746. tz *= len;
  102747. }
  102748. px = c1x + tx;
  102749. py = c1y + ty;
  102750. pz = c1z + tz;
  102751. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102752. }
  102753. } else {
  102754. sx = tx;
  102755. sy = ty;
  102756. sz = tz;
  102757. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  102758. sx -= depth1 * nx;
  102759. sy -= depth1 * ny;
  102760. sz -= depth1 * nz;
  102761. if (dot > 0) {
  102762. ex = tx + n2x * h2 * 2;
  102763. ey = ty + n2y * h2 * 2;
  102764. ez = tz + n2z * h2 * 2;
  102765. } else {
  102766. ex = tx - n2x * h2 * 2;
  102767. ey = ty - n2y * h2 * 2;
  102768. ez = tz - n2z * h2 * 2;
  102769. }
  102770. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  102771. ex -= depth2 * nx;
  102772. ey -= depth2 * ny;
  102773. ez -= depth2 * nz;
  102774. dx = c1x - sx;
  102775. dy = c1y - sy;
  102776. dz = c1z - sz;
  102777. tx = ex - sx;
  102778. ty = ey - sy;
  102779. tz = ez - sz;
  102780. a = dx * dx + dy * dy + dz * dz;
  102781. b = dx * tx + dy * ty + dz * tz;
  102782. e = tx * tx + ty * ty + tz * tz;
  102783. f = b * b - e * (a - r1 * r1);
  102784. if (f < 0) break;
  102785. f = OIMO.sqrt(f);
  102786. t1 = (b + f) / e;
  102787. t2 = (b - f) / e;
  102788. if (t2 < t1) {
  102789. len = t1;
  102790. t1 = t2;
  102791. t2 = len;
  102792. }
  102793. if (t2 > 1) t2 = 1;
  102794. if (t1 < 0) t1 = 0;
  102795. tx = sx + (ex - sx) * t1;
  102796. ty = sy + (ey - sy) * t1;
  102797. tz = sz + (ez - sz) * t1;
  102798. ex = sx + (ex - sx) * t2;
  102799. ey = sy + (ey - sy) * t2;
  102800. ez = sz + (ez - sz) * t2;
  102801. sx = tx;
  102802. sy = ty;
  102803. sz = tz;
  102804. len = depth1 + (depth2 - depth1) * t1;
  102805. depth2 = depth1 + (depth2 - depth1) * t2;
  102806. depth1 = len;
  102807. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  102808. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  102809. }
  102810. break;
  102811. case 2:
  102812. if (right2) {
  102813. c2x = p2x - d2x;
  102814. c2y = p2y - d2y;
  102815. c2z = p2z - d2z;
  102816. nx = -n2x;
  102817. ny = -n2y;
  102818. nz = -n2z;
  102819. } else {
  102820. c2x = p2x + d2x;
  102821. c2y = p2y + d2y;
  102822. c2z = p2z + d2z;
  102823. nx = n2x;
  102824. ny = n2y;
  102825. nz = n2z;
  102826. }
  102827. dot = nx * n1x + ny * n1y + nz * n1z;
  102828. if (dot < 0) len = h1;
  102829. else len = -h1;
  102830. c1x = p1x + len * n1x;
  102831. c1y = p1y + len * n1y;
  102832. c1z = p1z + len * n1z;
  102833. if (dot1 >= 0.999999) {
  102834. tx = -ny;
  102835. ty = nz;
  102836. tz = nx;
  102837. } else {
  102838. tx = nx;
  102839. ty = ny;
  102840. tz = nz;
  102841. }
  102842. len = tx * n1x + ty * n1y + tz * n1z;
  102843. dx = len * n1x - tx;
  102844. dy = len * n1y - ty;
  102845. dz = len * n1z - tz;
  102846. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102847. if (len == 0) break;
  102848. len = r1 / len;
  102849. dx *= len;
  102850. dy *= len;
  102851. dz *= len;
  102852. tx = c1x + dx;
  102853. ty = c1y + dy;
  102854. tz = c1z + dz;
  102855. if (dot < -0.96 || dot > 0.96) {
  102856. r00 = n1x * n1x * 1.5 - 0.5;
  102857. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  102858. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  102859. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  102860. r11 = n1y * n1y * 1.5 - 0.5;
  102861. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  102862. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  102863. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  102864. r22 = n1z * n1z * 1.5 - 0.5;
  102865. px = tx;
  102866. py = ty;
  102867. pz = tz;
  102868. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102869. tx = px - pd * nx - c2x;
  102870. ty = py - pd * ny - c2y;
  102871. tz = pz - pd * nz - c2z;
  102872. len = tx * tx + ty * ty + tz * tz;
  102873. if (len > r2 * r2) {
  102874. len = r2 / OIMO.sqrt(len);
  102875. tx *= len;
  102876. ty *= len;
  102877. tz *= len;
  102878. }
  102879. px = c2x + tx;
  102880. py = c2y + ty;
  102881. pz = c2z + tz;
  102882. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102883. px = dx * r00 + dy * r01 + dz * r02;
  102884. py = dx * r10 + dy * r11 + dz * r12;
  102885. pz = dx * r20 + dy * r21 + dz * r22;
  102886. px = (dx = px) + c1x;
  102887. py = (dy = py) + c1y;
  102888. pz = (dz = pz) + c1z;
  102889. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102890. if (pd <= 0) {
  102891. tx = px - pd * nx - c2x;
  102892. ty = py - pd * ny - c2y;
  102893. tz = pz - pd * nz - c2z;
  102894. len = tx * tx + ty * ty + tz * tz;
  102895. if (len > r2 * r2) {
  102896. len = r2 / OIMO.sqrt(len);
  102897. tx *= len;
  102898. ty *= len;
  102899. tz *= len;
  102900. }
  102901. px = c2x + tx;
  102902. py = c2y + ty;
  102903. pz = c2z + tz;
  102904. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102905. }
  102906. px = dx * r00 + dy * r01 + dz * r02;
  102907. py = dx * r10 + dy * r11 + dz * r12;
  102908. pz = dx * r20 + dy * r21 + dz * r22;
  102909. px = (dx = px) + c1x;
  102910. py = (dy = py) + c1y;
  102911. pz = (dz = pz) + c1z;
  102912. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102913. if (pd <= 0) {
  102914. tx = px - pd * nx - c2x;
  102915. ty = py - pd * ny - c2y;
  102916. tz = pz - pd * nz - c2z;
  102917. len = tx * tx + ty * ty + tz * tz;
  102918. if (len > r2 * r2) {
  102919. len = r2 / OIMO.sqrt(len);
  102920. tx *= len;
  102921. ty *= len;
  102922. tz *= len;
  102923. }
  102924. px = c2x + tx;
  102925. py = c2y + ty;
  102926. pz = c2z + tz;
  102927. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102928. }
  102929. } else {
  102930. sx = tx;
  102931. sy = ty;
  102932. sz = tz;
  102933. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  102934. sx -= depth1 * nx;
  102935. sy -= depth1 * ny;
  102936. sz -= depth1 * nz;
  102937. if (dot > 0) {
  102938. ex = tx + n1x * h1 * 2;
  102939. ey = ty + n1y * h1 * 2;
  102940. ez = tz + n1z * h1 * 2;
  102941. } else {
  102942. ex = tx - n1x * h1 * 2;
  102943. ey = ty - n1y * h1 * 2;
  102944. ez = tz - n1z * h1 * 2;
  102945. }
  102946. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  102947. ex -= depth2 * nx;
  102948. ey -= depth2 * ny;
  102949. ez -= depth2 * nz;
  102950. dx = c2x - sx;
  102951. dy = c2y - sy;
  102952. dz = c2z - sz;
  102953. tx = ex - sx;
  102954. ty = ey - sy;
  102955. tz = ez - sz;
  102956. a = dx * dx + dy * dy + dz * dz;
  102957. b = dx * tx + dy * ty + dz * tz;
  102958. e = tx * tx + ty * ty + tz * tz;
  102959. f = b * b - e * (a - r2 * r2);
  102960. if (f < 0) break;
  102961. f = OIMO.sqrt(f);
  102962. t1 = (b + f) / e;
  102963. t2 = (b - f) / e;
  102964. if (t2 < t1) {
  102965. len = t1;
  102966. t1 = t2;
  102967. t2 = len;
  102968. }
  102969. if (t2 > 1) t2 = 1;
  102970. if (t1 < 0) t1 = 0;
  102971. tx = sx + (ex - sx) * t1;
  102972. ty = sy + (ey - sy) * t1;
  102973. tz = sz + (ez - sz) * t1;
  102974. ex = sx + (ex - sx) * t2;
  102975. ey = sy + (ey - sy) * t2;
  102976. ez = sz + (ez - sz) * t2;
  102977. sx = tx;
  102978. sy = ty;
  102979. sz = tz;
  102980. len = depth1 + (depth2 - depth1) * t1;
  102981. depth2 = depth1 + (depth2 - depth1) * t2;
  102982. depth1 = len;
  102983. if (depth1 < 0) {
  102984. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  102985. }
  102986. if (depth2 < 0) {
  102987. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  102988. }
  102989. }
  102990. break;
  102991. }
  102992. };
  102993. OIMO.SphereCylinderCollisionDetector = function (flip) {
  102994. OIMO.CollisionDetector.call(this);
  102995. this.flip = flip;
  102996. };
  102997. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102998. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  102999. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  103000. var s;
  103001. var c;
  103002. if (this.flip) {
  103003. s = shape2;
  103004. c = shape1;
  103005. } else {
  103006. s = shape1;
  103007. c = shape2;
  103008. }
  103009. var ps = s.position;
  103010. var psx = ps.x;
  103011. var psy = ps.y;
  103012. var psz = ps.z;
  103013. var pc = c.position;
  103014. var pcx = pc.x;
  103015. var pcy = pc.y;
  103016. var pcz = pc.z;
  103017. var dirx = c.normalDirection.x;
  103018. var diry = c.normalDirection.y;
  103019. var dirz = c.normalDirection.z;
  103020. var rads = s.radius;
  103021. var radc = c.radius;
  103022. var rad2 = rads + radc;
  103023. var halfh = c.halfHeight;
  103024. var dx = psx - pcx;
  103025. var dy = psy - pcy;
  103026. var dz = psz - pcz;
  103027. var dot = dx * dirx + dy * diry + dz * dirz;
  103028. if (dot < -halfh - rads || dot > halfh + rads) return;
  103029. var cx = pcx + dot * dirx;
  103030. var cy = pcy + dot * diry;
  103031. var cz = pcz + dot * dirz;
  103032. var d2x = psx - cx;
  103033. var d2y = psy - cy;
  103034. var d2z = psz - cz;
  103035. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  103036. if (len > rad2 * rad2) return;
  103037. if (len > radc * radc) {
  103038. len = radc / OIMO.sqrt(len);
  103039. d2x *= len;
  103040. d2y *= len;
  103041. d2z *= len;
  103042. }
  103043. if (dot < -halfh) dot = -halfh;
  103044. else if (dot > halfh) dot = halfh;
  103045. cx = pcx + dot * dirx + d2x;
  103046. cy = pcy + dot * diry + d2y;
  103047. cz = pcz + dot * dirz + d2z;
  103048. dx = cx - psx;
  103049. dy = cy - psy;
  103050. dz = cz - psz;
  103051. len = dx * dx + dy * dy + dz * dz;
  103052. var invLen;
  103053. if (len > 0 && len < rads * rads) {
  103054. len = OIMO.sqrt(len);
  103055. invLen = 1 / len;
  103056. dx *= invLen;
  103057. dy *= invLen;
  103058. dz *= invLen;
  103059. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  103060. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  103061. }
  103062. };
  103063. /**
  103064. * Class for checking collisions between 2 tetras,
  103065. * a shape that is made with 4 vertices and 4 faces
  103066. * arranged in triangles. With this algorigthm, soft
  103067. * body physics are possible and easier to implement.
  103068. * @author xprogram
  103069. */
  103070. OIMO.TetraTetraCollisionDetector = function () {
  103071. OIMO.CollisionDetector.call(this);
  103072. };
  103073. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  103074. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  103075. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  103076. /*
  103077. * What we are doing:
  103078. * Each tetra is represented by four 3D triangles. The only
  103079. * quick way of finding if another tetra is within the other
  103080. * tetra is to see if a single vertex is within the triangles
  103081. * of the other tetra. So, for example, a tetra is represented
  103082. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  103083. * There is another tetra with a vertex A which was detected for
  103084. * collision by the broadphase. Now, if the point A is between ALL
  103085. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  103086. * is valid and we can pass point A to the manifold. Since the only
  103087. * points on the tetra are the 4 vertices, collision detection is
  103088. * not so complex. However, it can be time-consuming because we
  103089. * need to split the 3D triangles into three 2D triangles each for
  103090. * collision detection.
  103091. */
  103092. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  103093. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  103094. // fs is undeclared
  103095. var fs = fs1;
  103096. for (i = 0; i < 4; i++) {
  103097. vec = vs1[i];
  103098. for (j = 0; j < 4; j++) {
  103099. j1 = vs2[fs[i].a];
  103100. j2 = vs2[fs[i].b];
  103101. j3 = vs2[fs[i].c];
  103102. if (
  103103. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  103104. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  103105. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  103106. )
  103107. ts++;
  103108. if (ts === 4) // Only add point if it is inside all 4 triangles
  103109. manifold.addPoint(vec);
  103110. }
  103111. }
  103112. };
  103113. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  103114. function tricheck(p, p0, p1, p2) {
  103115. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  103116. var sg = A < 0 ? -1 : 1;
  103117. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  103118. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  103119. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  103120. }
  103121. function pt(x, y) { return { x: x, y: y }; }
  103122. /**
  103123. * An axis-aligned bounding box.
  103124. * @author saharan
  103125. * @author lo-th
  103126. */
  103127. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  103128. this.elements = new OIMO_ARRAY_TYPE(6);
  103129. var te = this.elements;
  103130. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  103131. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  103132. };
  103133. OIMO.AABB.prototype = {
  103134. constructor: OIMO.AABB,
  103135. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  103136. var te = this.elements;
  103137. te[0] = minX; te[3] = maxX;
  103138. te[1] = minY; te[4] = maxY;
  103139. te[2] = minZ; te[5] = maxZ;
  103140. return this;
  103141. },
  103142. intersectTest: function (aabb) {
  103143. var te = this.elements;
  103144. var ue = aabb.elements;
  103145. return te[0] > ue[3] || te[1] > ue[4] || te[2] > ue[5] || te[3] < ue[0] || te[4] < ue[1] || te[5] < ue[2];
  103146. },
  103147. intersectTestTwo: function (aabb) {
  103148. var te = this.elements;
  103149. var ue = aabb.elements;
  103150. return te[0] < ue[0] || te[1] < ue[1] || te[2] < ue[2] || te[3] > ue[3] || te[4] > ue[4] || te[5] > ue[5];
  103151. },
  103152. clone: function () {
  103153. return new this.constructor().fromArray(this.elements);
  103154. },
  103155. copy: function (aabb, margin) {
  103156. var m = margin || 0;
  103157. var me = aabb.elements;
  103158. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  103159. return this;
  103160. },
  103161. fromArray: function (array) {
  103162. this.elements.set(array);
  103163. return this;
  103164. },
  103165. // Set this AABB to the combined AABB of aabb1 and aabb2.
  103166. combine: function (aabb1, aabb2) {
  103167. var a = aabb1.elements;
  103168. var b = aabb2.elements;
  103169. var te = this.elements;
  103170. te[0] = a[0] < b[0] ? a[0] : b[0];
  103171. te[1] = a[1] < b[1] ? a[1] : b[1];
  103172. te[2] = a[2] < b[2] ? a[2] : b[2];
  103173. te[3] = a[3] > b[3] ? a[3] : b[3];
  103174. te[4] = a[4] > b[4] ? a[4] : b[4];
  103175. te[5] = a[5] > b[5] ? a[5] : b[5];
  103176. return this;
  103177. },
  103178. // Get the surface area.
  103179. surfaceArea: function () {
  103180. var te = this.elements;
  103181. var a = te[3] - te[0];
  103182. var h = te[4] - te[1];
  103183. var d = te[5] - te[2];
  103184. return 2 * (a * (h + d) + h * d);
  103185. },
  103186. // Get whether the AABB intersects with the point or not.
  103187. intersectsWithPoint: function (x, y, z) {
  103188. var te = this.elements;
  103189. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  103190. },
  103191. /**
  103192. * Set the AABB from an array
  103193. * of vertices. From THREE.
  103194. * @author mrdoob
  103195. * @author xprogram
  103196. */
  103197. setFromPoints: function (arr) {
  103198. this.makeEmpty();
  103199. for (var i = 0; i < arr.length; i++) {
  103200. this.expandByPoint(arr[i]);
  103201. }
  103202. },
  103203. makeEmpty: function () {
  103204. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  103205. },
  103206. expandByPoint: function (pt) {
  103207. var te = this.elements;
  103208. this.set(
  103209. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  103210. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  103211. );
  103212. }
  103213. };
  103214. /**
  103215. * A proxy is used for broad-phase collecting pairs that can be colliding.
  103216. */
  103217. OIMO.Proxy = function (shape) {
  103218. // The parent shape.
  103219. this.shape = shape;
  103220. // The axis-aligned bounding box.
  103221. this.aabb = shape.aabb;
  103222. };
  103223. OIMO.Proxy.prototype = {
  103224. constructor: OIMO.Proxy,
  103225. // Update the proxy.
  103226. update: function () {
  103227. OIMO.Error("Proxy", "Inheritance error.");
  103228. }
  103229. };
  103230. /**
  103231. * A basic implementation of proxies.
  103232. * @author saharan
  103233. */
  103234. OIMO.BasicProxy = function (shape) {
  103235. OIMO.Proxy.call(this, shape);
  103236. this.id = OIMO.proxyID++;
  103237. };
  103238. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103239. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  103240. OIMO.BasicProxy.prototype.update = function () {
  103241. };
  103242. /**
  103243. * The broad-phase is used for collecting all possible pairs for collision.
  103244. */
  103245. OIMO.BroadPhase = function () {
  103246. this.types = OIMO.BR_NULL;
  103247. this.numPairChecks = 0;
  103248. this.numPairs = 0;
  103249. this.pairs = [];
  103250. };
  103251. OIMO.BroadPhase.prototype = {
  103252. constructor: OIMO.BroadPhase,
  103253. /**
  103254. * Create a new proxy.
  103255. * @param shape
  103256. * @return
  103257. */
  103258. createProxy: function (shape) {
  103259. OIMO.Error("BroadPhase", "Inheritance error.");
  103260. },
  103261. /**
  103262. * Add the proxy into the broad-phase.
  103263. * @param proxy
  103264. */
  103265. addProxy: function (proxy) {
  103266. OIMO.Error("BroadPhase", "Inheritance error.");
  103267. },
  103268. /**
  103269. * Remove the proxy from the broad-phase.
  103270. * @param proxy
  103271. */
  103272. removeProxy: function (proxy) {
  103273. OIMO.Error("BroadPhase", "Inheritance error.");
  103274. },
  103275. /**
  103276. * Returns whether the pair is available or not.
  103277. * @param s1
  103278. * @param s2
  103279. * @return
  103280. */
  103281. isAvailablePair: function (s1, s2) {
  103282. var b1 = s1.parent;
  103283. var b2 = s2.parent;
  103284. if (b1 == b2 || // same parents
  103285. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  103286. (s1.belongsTo & s2.collidesWith) == 0 ||
  103287. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  103288. ) { return false; }
  103289. var js;
  103290. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  103291. else js = b2.jointLink;
  103292. while (js !== null) {
  103293. var joint = js.joint;
  103294. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  103295. js = js.next;
  103296. }
  103297. return true;
  103298. },
  103299. // Detect overlapping pairs.
  103300. detectPairs: function () {
  103301. // clear old
  103302. this.pairs = [];
  103303. this.numPairs = 0;
  103304. this.numPairChecks = 0;
  103305. this.collectPairs();
  103306. },
  103307. collectPairs: function () {
  103308. OIMO.Error("BroadPhase", "Inheritance error.");
  103309. },
  103310. addPair: function (s1, s2) {
  103311. var pair = new OIMO.Pair(s1, s2);
  103312. this.pairs.push(pair);
  103313. this.numPairs++;
  103314. }
  103315. };
  103316. /**
  103317. * A broad-phase algorithm with brute-force search.
  103318. * This always checks for all possible pairs.
  103319. */
  103320. OIMO.BruteForceBroadPhase = function () {
  103321. OIMO.BroadPhase.call(this);
  103322. this.types = OIMO.BR_BRUTE_FORCE;;
  103323. //this.numProxies=0;
  103324. ///this.maxProxies = 256;
  103325. this.proxies = [];
  103326. //this.proxies.length = 256;
  103327. };
  103328. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103329. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  103330. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  103331. return new OIMO.BasicProxy(shape);
  103332. };
  103333. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  103334. /*if(this.numProxies==this.maxProxies){
  103335. //this.maxProxies<<=1;
  103336. this.maxProxies*=2;
  103337. var newProxies=[];
  103338. newProxies.length = this.maxProxies;
  103339. var i = this.numProxies;
  103340. while(i--){
  103341. //for(var i=0, l=this.numProxies;i<l;i++){
  103342. newProxies[i]=this.proxies[i];
  103343. }
  103344. this.proxies=newProxies;
  103345. }*/
  103346. //this.proxies[this.numProxies++] = proxy;
  103347. this.proxies.push(proxy);
  103348. //this.numProxies++;
  103349. };
  103350. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  103351. var n = this.proxies.indexOf(proxy);
  103352. if (n > -1) {
  103353. this.proxies.splice(n, 1);
  103354. //this.numProxies--;
  103355. }
  103356. /*var i = this.numProxies;
  103357. while(i--){
  103358. //for(var i=0, l=this.numProxies;i<l;i++){
  103359. if(this.proxies[i] == proxy){
  103360. this.proxies[i] = this.proxies[--this.numProxies];
  103361. this.proxies[this.numProxies] = null;
  103362. return;
  103363. }
  103364. }*/
  103365. };
  103366. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  103367. var i = 0, j, p1, p2;
  103368. var px = this.proxies;
  103369. var l = px.length;//this.numProxies;
  103370. //var ar1 = [];
  103371. //var ar2 = [];
  103372. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  103373. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  103374. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  103375. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  103376. this.numPairChecks = l * (l - 1) >> 1;
  103377. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  103378. while (i < l) {
  103379. p1 = px[i++];
  103380. j = i + 1;
  103381. while (j < l) {
  103382. p2 = px[j++];
  103383. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  103384. this.addPair(p1.shape, p2.shape);
  103385. }
  103386. }
  103387. };
  103388. /**
  103389. * A pair of shapes that may collide.
  103390. * @author saharan
  103391. */
  103392. OIMO.Pair = function (s1, s2) {
  103393. // The first shape.
  103394. this.shape1 = s1 || null;
  103395. // The second shape.
  103396. this.shape2 = s2 || null;
  103397. };
  103398. /**
  103399. * A projection axis for sweep and prune broad-phase.
  103400. * @author saharan
  103401. */
  103402. OIMO.SAPAxis = function () {
  103403. this.numElements = 0;
  103404. this.bufferSize = 256;
  103405. this.elements = [];
  103406. this.elements.length = this.bufferSize;
  103407. this.stack = new OIMO_ARRAY_TYPE(64);
  103408. };
  103409. OIMO.SAPAxis.prototype = {
  103410. constructor: OIMO.SAPAxis,
  103411. addElements: function (min, max) {
  103412. if (this.numElements + 2 >= this.bufferSize) {
  103413. //this.bufferSize<<=1;
  103414. this.bufferSize *= 2;
  103415. var newElements = [];
  103416. var i = this.numElements;
  103417. while (i--) {
  103418. //for(var i=0, l=this.numElements; i<l; i++){
  103419. newElements[i] = this.elements[i];
  103420. }
  103421. }
  103422. this.elements[this.numElements++] = min;
  103423. this.elements[this.numElements++] = max;
  103424. },
  103425. removeElements: function (min, max) {
  103426. var minIndex = -1;
  103427. var maxIndex = -1;
  103428. for (var i = 0, l = this.numElements; i < l; i++) {
  103429. var e = this.elements[i];
  103430. if (e == min || e == max) {
  103431. if (minIndex == -1) {
  103432. minIndex = i;
  103433. } else {
  103434. maxIndex = i;
  103435. break;
  103436. }
  103437. }
  103438. }
  103439. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  103440. this.elements[i - 1] = this.elements[i];
  103441. }
  103442. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  103443. this.elements[i - 2] = this.elements[i];
  103444. }
  103445. this.elements[--this.numElements] = null;
  103446. this.elements[--this.numElements] = null;
  103447. },
  103448. sort: function () {
  103449. var count = 0;
  103450. var threshold = 1;
  103451. while ((this.numElements >> threshold) != 0) threshold++;
  103452. threshold = threshold * this.numElements >> 2;
  103453. count = 0;
  103454. var giveup = false;
  103455. var elements = this.elements;
  103456. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  103457. var tmp = elements[i];
  103458. var pivot = tmp.value;
  103459. var tmp2 = elements[i - 1];
  103460. if (tmp2.value > pivot) {
  103461. var j = i;
  103462. do {
  103463. elements[j] = tmp2;
  103464. if (--j == 0) break;
  103465. tmp2 = elements[j - 1];
  103466. } while (tmp2.value > pivot);
  103467. elements[j] = tmp;
  103468. count += i - j;
  103469. if (count > threshold) {
  103470. giveup = true; // stop and use quick sort
  103471. break;
  103472. }
  103473. }
  103474. }
  103475. if (!giveup) return;
  103476. count = 2; var stack = this.stack;
  103477. stack[0] = 0;
  103478. stack[1] = this.numElements - 1;
  103479. while (count > 0) {
  103480. var right = stack[--count];
  103481. var left = stack[--count];
  103482. var diff = right - left;
  103483. if (diff > 16) { // quick sort
  103484. //var mid=left+(diff>>1);
  103485. var mid = left + (OIMO.floor(diff * 0.5));
  103486. tmp = elements[mid];
  103487. elements[mid] = elements[right];
  103488. elements[right] = tmp;
  103489. pivot = tmp.value;
  103490. i = left - 1;
  103491. j = right;
  103492. while (true) {
  103493. var ei;
  103494. var ej;
  103495. do { ei = elements[++i]; } while (ei.value < pivot);
  103496. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  103497. if (i >= j) break;
  103498. elements[i] = ej;
  103499. elements[j] = ei;
  103500. }
  103501. elements[right] = elements[i];
  103502. elements[i] = tmp;
  103503. if (i - left > right - i) {
  103504. stack[count++] = left;
  103505. stack[count++] = i - 1;
  103506. stack[count++] = i + 1;
  103507. stack[count++] = right;
  103508. } else {
  103509. stack[count++] = i + 1;
  103510. stack[count++] = right;
  103511. stack[count++] = left;
  103512. stack[count++] = i - 1;
  103513. }
  103514. } else {
  103515. for (i = left + 1; i <= right; i++) {
  103516. tmp = elements[i];
  103517. pivot = tmp.value;
  103518. tmp2 = elements[i - 1];
  103519. if (tmp2.value > pivot) {
  103520. j = i;
  103521. do {
  103522. elements[j] = tmp2;
  103523. if (--j == 0) break;
  103524. tmp2 = elements[j - 1];
  103525. } while (tmp2.value > pivot);
  103526. elements[j] = tmp;
  103527. }
  103528. }
  103529. }
  103530. }
  103531. },
  103532. calculateTestCount: function () {
  103533. var num = 1;
  103534. var sum = 0;
  103535. for (var i = 1, l = this.numElements; i < l; i++) {
  103536. if (this.elements[i].max) {
  103537. num--;
  103538. } else {
  103539. sum += num;
  103540. num++;
  103541. }
  103542. }
  103543. return sum;
  103544. }
  103545. }
  103546. /**
  103547. * A broad-phase collision detection algorithm using sweep and prune.
  103548. * @author saharan
  103549. * @author lo-th
  103550. */
  103551. OIMO.SAPBroadPhase = function () {
  103552. OIMO.BroadPhase.call(this);
  103553. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  103554. this.numElementsD = 0;
  103555. this.numElementsS = 0;
  103556. // dynamic proxies
  103557. this.axesD = [
  103558. new OIMO.SAPAxis(),
  103559. new OIMO.SAPAxis(),
  103560. new OIMO.SAPAxis()
  103561. ];
  103562. // static or sleeping proxies
  103563. this.axesS = [
  103564. new OIMO.SAPAxis(),
  103565. new OIMO.SAPAxis(),
  103566. new OIMO.SAPAxis()
  103567. ];
  103568. this.index1 = 0;
  103569. this.index2 = 1;
  103570. };
  103571. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103572. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  103573. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  103574. return new OIMO.SAPProxy(this, shape);
  103575. };
  103576. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  103577. var p = proxy;
  103578. if (p.isDynamic()) {
  103579. this.axesD[0].addElements(p.min[0], p.max[0]);
  103580. this.axesD[1].addElements(p.min[1], p.max[1]);
  103581. this.axesD[2].addElements(p.min[2], p.max[2]);
  103582. p.belongsTo = 1;
  103583. this.numElementsD += 2;
  103584. } else {
  103585. this.axesS[0].addElements(p.min[0], p.max[0]);
  103586. this.axesS[1].addElements(p.min[1], p.max[1]);
  103587. this.axesS[2].addElements(p.min[2], p.max[2]);
  103588. p.belongsTo = 2;
  103589. this.numElementsS += 2;
  103590. }
  103591. };
  103592. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  103593. var p = proxy;
  103594. if (p.belongsTo == 0) return;
  103595. /*else if ( p.belongsTo == 1 ) {
  103596. this.axesD[0].removeElements( p.min[0], p.max[0] );
  103597. this.axesD[1].removeElements( p.min[1], p.max[1] );
  103598. this.axesD[2].removeElements( p.min[2], p.max[2] );
  103599. this.numElementsD -= 2;
  103600. } else if ( p.belongsTo == 2 ) {
  103601. this.axesS[0].removeElements( p.min[0], p.max[0] );
  103602. this.axesS[1].removeElements( p.min[1], p.max[1] );
  103603. this.axesS[2].removeElements( p.min[2], p.max[2] );
  103604. this.numElementsS -= 2;
  103605. }*/
  103606. switch (p.belongsTo) {
  103607. case 1:
  103608. this.axesD[0].removeElements(p.min[0], p.max[0]);
  103609. this.axesD[1].removeElements(p.min[1], p.max[1]);
  103610. this.axesD[2].removeElements(p.min[2], p.max[2]);
  103611. this.numElementsD -= 2;
  103612. break;
  103613. case 2:
  103614. this.axesS[0].removeElements(p.min[0], p.max[0]);
  103615. this.axesS[1].removeElements(p.min[1], p.max[1]);
  103616. this.axesS[2].removeElements(p.min[2], p.max[2]);
  103617. this.numElementsS -= 2;
  103618. break;
  103619. }
  103620. p.belongsTo = 0;
  103621. };
  103622. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  103623. if (this.numElementsD == 0) return;
  103624. var axis1 = this.axesD[this.index1];
  103625. var axis2 = this.axesD[this.index2];
  103626. axis1.sort();
  103627. axis2.sort();
  103628. var count1 = axis1.calculateTestCount();
  103629. var count2 = axis2.calculateTestCount();
  103630. var elementsD;
  103631. var elementsS;
  103632. if (count1 <= count2) {// select the best axis
  103633. axis2 = this.axesS[this.index1];
  103634. axis2.sort();
  103635. elementsD = axis1.elements;
  103636. elementsS = axis2.elements;
  103637. } else {
  103638. axis1 = this.axesS[this.index2];
  103639. axis1.sort();
  103640. elementsD = axis2.elements;
  103641. elementsS = axis1.elements;
  103642. this.index1 ^= this.index2;
  103643. this.index2 ^= this.index1;
  103644. this.index1 ^= this.index2;
  103645. }
  103646. var activeD;
  103647. var activeS;
  103648. var p = 0;
  103649. var q = 0;
  103650. while (p < this.numElementsD) {
  103651. var e1;
  103652. var dyn;
  103653. if (q == this.numElementsS) {
  103654. e1 = elementsD[p];
  103655. dyn = true;
  103656. p++;
  103657. } else {
  103658. var d = elementsD[p];
  103659. var s = elementsS[q];
  103660. if (d.value < s.value) {
  103661. e1 = d;
  103662. dyn = true;
  103663. p++;
  103664. } else {
  103665. e1 = s;
  103666. dyn = false;
  103667. q++;
  103668. }
  103669. }
  103670. if (!e1.max) {
  103671. var s1 = e1.proxy.shape;
  103672. var min1 = e1.min1.value;
  103673. var max1 = e1.max1.value;
  103674. var min2 = e1.min2.value;
  103675. var max2 = e1.max2.value;
  103676. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  103677. var s2 = e2.proxy.shape;
  103678. this.numPairChecks++;
  103679. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  103680. this.addPair(s1, s2);
  103681. }
  103682. if (dyn) {
  103683. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  103684. s2 = e2.proxy.shape;
  103685. this.numPairChecks++;
  103686. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  103687. this.addPair(s1, s2);
  103688. }
  103689. e1.pair = activeD;
  103690. activeD = e1;
  103691. } else {
  103692. e1.pair = activeS;
  103693. activeS = e1;
  103694. }
  103695. } else {
  103696. var min = e1.pair;
  103697. if (dyn) {
  103698. if (min == activeD) {
  103699. activeD = activeD.pair;
  103700. continue;
  103701. } else {
  103702. e1 = activeD;
  103703. }
  103704. } else {
  103705. if (min == activeS) {
  103706. activeS = activeS.pair;
  103707. continue;
  103708. } else {
  103709. e1 = activeS;
  103710. }
  103711. }
  103712. do {
  103713. e2 = e1.pair;
  103714. if (e2 == min) {
  103715. e1.pair = e2.pair;
  103716. break;
  103717. }
  103718. e1 = e2;
  103719. } while (e1 != null);
  103720. }
  103721. }
  103722. this.index2 = (this.index1 | this.index2) ^ 3;
  103723. };
  103724. /**
  103725. * An element of proxies.
  103726. * @author saharan
  103727. */
  103728. OIMO.SAPElement = function (proxy, max) {
  103729. // The parent proxy
  103730. this.proxy = proxy;
  103731. // The pair element.
  103732. this.pair = null;
  103733. // The minimum element on other axis.
  103734. this.min1 = null;
  103735. // The maximum element on other axis.
  103736. this.max1 = null;
  103737. // The minimum element on other axis.
  103738. this.min2 = null;
  103739. // The maximum element on other axis.
  103740. this.max2 = null;
  103741. // Whether the element has maximum value or not.
  103742. this.max = max;
  103743. // The value of the element.
  103744. this.value = 0;
  103745. };
  103746. /**
  103747. * A proxy for sweep and prune broad-phase.
  103748. * @author saharan
  103749. * @author lo-th
  103750. */
  103751. OIMO.SAPProxy = function (sap, shape) {
  103752. OIMO.Proxy.call(this, shape);
  103753. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  103754. this.belongsTo = 0;
  103755. // The maximum elements on each axis.
  103756. this.max = [];
  103757. // The minimum elements on each axis.
  103758. this.min = [];
  103759. this.sap = sap;
  103760. this.min[0] = new OIMO.SAPElement(this, false);
  103761. this.max[0] = new OIMO.SAPElement(this, true);
  103762. this.min[1] = new OIMO.SAPElement(this, false);
  103763. this.max[1] = new OIMO.SAPElement(this, true);
  103764. this.min[2] = new OIMO.SAPElement(this, false);
  103765. this.max[2] = new OIMO.SAPElement(this, true);
  103766. this.max[0].pair = this.min[0];
  103767. this.max[1].pair = this.min[1];
  103768. this.max[2].pair = this.min[2];
  103769. this.min[0].min1 = this.min[1];
  103770. this.min[0].max1 = this.max[1];
  103771. this.min[0].min2 = this.min[2];
  103772. this.min[0].max2 = this.max[2];
  103773. this.min[1].min1 = this.min[0];
  103774. this.min[1].max1 = this.max[0];
  103775. this.min[1].min2 = this.min[2];
  103776. this.min[1].max2 = this.max[2];
  103777. this.min[2].min1 = this.min[0];
  103778. this.min[2].max1 = this.max[0];
  103779. this.min[2].min2 = this.min[1];
  103780. this.min[2].max2 = this.max[1];
  103781. };
  103782. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103783. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  103784. // Returns whether the proxy is dynamic or not.
  103785. OIMO.SAPProxy.prototype.isDynamic = function () {
  103786. var body = this.shape.parent;
  103787. return body.isDynamic && !body.sleeping;
  103788. };
  103789. OIMO.SAPProxy.prototype.update = function () {
  103790. var te = this.aabb.elements;
  103791. this.min[0].value = te[0];
  103792. this.min[1].value = te[1];
  103793. this.min[2].value = te[2];
  103794. this.max[0].value = te[3];
  103795. this.max[1].value = te[4];
  103796. this.max[2].value = te[5];
  103797. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  103798. this.sap.removeProxy(this);
  103799. this.sap.addProxy(this);
  103800. }
  103801. };
  103802. /**
  103803. * A dynamic bounding volume tree for the broad-phase algorithm.
  103804. * @author saharan
  103805. * @author lo-th
  103806. */
  103807. OIMO.DBVT = function () {
  103808. // The root of the tree.
  103809. this.root = null;
  103810. this.freeNodes = [];
  103811. this.freeNodes.length = 16384;
  103812. this.numFreeNodes = 0;
  103813. this.aabb = new OIMO.AABB();
  103814. };
  103815. OIMO.DBVT.prototype = {
  103816. constructor: OIMO.DBVT,
  103817. /**
  103818. * Move a leaf.
  103819. * @param leaf
  103820. */
  103821. moveLeaf: function (leaf) {
  103822. this.deleteLeaf(leaf);
  103823. this.insertLeaf(leaf);
  103824. },
  103825. /**
  103826. * Insert a leaf to the tree.
  103827. * @param node
  103828. */
  103829. insertLeaf: function (leaf) {
  103830. if (this.root == null) {
  103831. this.root = leaf;
  103832. return;
  103833. }
  103834. var lb = leaf.aabb;
  103835. var sibling = this.root;
  103836. var oldArea;
  103837. var newArea;
  103838. while (sibling.proxy == null) { // descend the node to search the best pair
  103839. var c1 = sibling.child1;
  103840. var c2 = sibling.child2;
  103841. var b = sibling.aabb;
  103842. var c1b = c1.aabb;
  103843. var c2b = c2.aabb;
  103844. oldArea = b.surfaceArea();
  103845. this.aabb.combine(lb, b);
  103846. newArea = this.aabb.surfaceArea();
  103847. var creatingCost = newArea * 2;
  103848. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  103849. var discendingCost1 = incrementalCost;
  103850. this.aabb.combine(lb, c1b);
  103851. if (c1.proxy != null) {
  103852. // leaf cost = area(combined aabb)
  103853. discendingCost1 += this.aabb.surfaceArea();
  103854. } else {
  103855. // node cost = area(combined aabb) - area(old aabb)
  103856. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  103857. }
  103858. var discendingCost2 = incrementalCost;
  103859. this.aabb.combine(lb, c2b);
  103860. if (c2.proxy != null) {
  103861. // leaf cost = area(combined aabb)
  103862. discendingCost2 += this.aabb.surfaceArea();
  103863. } else {
  103864. // node cost = area(combined aabb) - area(old aabb)
  103865. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  103866. }
  103867. if (discendingCost1 < discendingCost2) {
  103868. if (creatingCost < discendingCost1) {
  103869. break;// stop descending
  103870. } else {
  103871. sibling = c1;// descend into first child
  103872. }
  103873. } else {
  103874. if (creatingCost < discendingCost2) {
  103875. break;// stop descending
  103876. } else {
  103877. sibling = c2;// descend into second child
  103878. }
  103879. }
  103880. }
  103881. var oldParent = sibling.parent;
  103882. var newParent;
  103883. if (this.numFreeNodes > 0) {
  103884. newParent = this.freeNodes[--this.numFreeNodes];
  103885. } else {
  103886. newParent = new OIMO.DBVTNode();
  103887. }
  103888. newParent.parent = oldParent;
  103889. newParent.child1 = leaf;
  103890. newParent.child2 = sibling;
  103891. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  103892. newParent.height = sibling.height + 1;
  103893. sibling.parent = newParent;
  103894. leaf.parent = newParent;
  103895. if (sibling == this.root) {
  103896. // replace root
  103897. this.root = newParent;
  103898. } else {
  103899. // replace child
  103900. if (oldParent.child1 == sibling) {
  103901. oldParent.child1 = newParent;
  103902. } else {
  103903. oldParent.child2 = newParent;
  103904. }
  103905. }
  103906. // update whole tree
  103907. do {
  103908. newParent = this.balance(newParent);
  103909. this.fix(newParent);
  103910. newParent = newParent.parent;
  103911. } while (newParent != null);
  103912. },
  103913. getBalance: function (node) {
  103914. if (node.proxy != null) return 0;
  103915. return node.child1.height - node.child2.height;
  103916. },
  103917. /*print:function(node,indent,text){
  103918. var hasChild=node.proxy==null;
  103919. if(hasChild)text=this.print(node.child1,indent+1,text);
  103920. for(var i=indent*2;i>=0;i--){
  103921. text+=" ";
  103922. }
  103923. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  103924. if(hasChild)text=this.print(node.child2,indent+1,text);
  103925. return text;
  103926. },*/
  103927. /**
  103928. * Delete a leaf from the tree.
  103929. * @param node
  103930. */
  103931. deleteLeaf: function (leaf) {
  103932. if (leaf == this.root) {
  103933. this.root = null;
  103934. return;
  103935. }
  103936. var parent = leaf.parent;
  103937. var sibling;
  103938. if (parent.child1 == leaf) {
  103939. sibling = parent.child2;
  103940. } else {
  103941. sibling = parent.child1;
  103942. }
  103943. if (parent == this.root) {
  103944. this.root = sibling;
  103945. sibling.parent = null;
  103946. return;
  103947. }
  103948. var grandParent = parent.parent;
  103949. sibling.parent = grandParent;
  103950. if (grandParent.child1 == parent) {
  103951. grandParent.child1 = sibling;
  103952. } else {
  103953. grandParent.child2 = sibling;
  103954. }
  103955. if (this.numFreeNodes < 16384) {
  103956. this.freeNodes[this.numFreeNodes++] = parent;
  103957. }
  103958. do {
  103959. grandParent = this.balance(grandParent);
  103960. this.fix(grandParent);
  103961. grandParent = grandParent.parent;
  103962. } while (grandParent != null);
  103963. },
  103964. balance: function (node) {
  103965. var nh = node.height;
  103966. if (nh < 2) {
  103967. return node;
  103968. }
  103969. var p = node.parent;
  103970. var l = node.child1;
  103971. var r = node.child2;
  103972. var lh = l.height;
  103973. var rh = r.height;
  103974. var balance = lh - rh;
  103975. var t;// for bit operation
  103976. // [ N ]
  103977. // / \
  103978. // [ L ] [ R ]
  103979. // / \ / \
  103980. // [L-L] [L-R] [R-L] [R-R]
  103981. // Is the tree balanced?
  103982. if (balance > 1) {
  103983. var ll = l.child1;
  103984. var lr = l.child2;
  103985. var llh = ll.height;
  103986. var lrh = lr.height;
  103987. // Is L-L higher than L-R?
  103988. if (llh > lrh) {
  103989. // set N to L-R
  103990. l.child2 = node;
  103991. node.parent = l;
  103992. // [ L ]
  103993. // / \
  103994. // [L-L] [ N ]
  103995. // / \ / \
  103996. // [...] [...] [ L ] [ R ]
  103997. // set L-R
  103998. node.child1 = lr;
  103999. lr.parent = node;
  104000. // [ L ]
  104001. // / \
  104002. // [L-L] [ N ]
  104003. // / \ / \
  104004. // [...] [...] [L-R] [ R ]
  104005. // fix bounds and heights
  104006. node.aabb.combine(lr.aabb, r.aabb);
  104007. t = lrh - rh;
  104008. node.height = lrh - (t & t >> 31) + 1;
  104009. l.aabb.combine(ll.aabb, node.aabb);
  104010. t = llh - nh;
  104011. l.height = llh - (t & t >> 31) + 1;
  104012. } else {
  104013. // set N to L-L
  104014. l.child1 = node;
  104015. node.parent = l;
  104016. // [ L ]
  104017. // / \
  104018. // [ N ] [L-R]
  104019. // / \ / \
  104020. // [ L ] [ R ] [...] [...]
  104021. // set L-L
  104022. node.child1 = ll;
  104023. ll.parent = node;
  104024. // [ L ]
  104025. // / \
  104026. // [ N ] [L-R]
  104027. // / \ / \
  104028. // [L-L] [ R ] [...] [...]
  104029. // fix bounds and heights
  104030. node.aabb.combine(ll.aabb, r.aabb);
  104031. t = llh - rh;
  104032. node.height = llh - (t & t >> 31) + 1;
  104033. l.aabb.combine(node.aabb, lr.aabb);
  104034. t = nh - lrh;
  104035. l.height = nh - (t & t >> 31) + 1;
  104036. }
  104037. // set new parent of L
  104038. if (p != null) {
  104039. if (p.child1 == node) {
  104040. p.child1 = l;
  104041. } else {
  104042. p.child2 = l;
  104043. }
  104044. } else {
  104045. this.root = l;
  104046. }
  104047. l.parent = p;
  104048. return l;
  104049. } else if (balance < -1) {
  104050. var rl = r.child1;
  104051. var rr = r.child2;
  104052. var rlh = rl.height;
  104053. var rrh = rr.height;
  104054. // Is R-L higher than R-R?
  104055. if (rlh > rrh) {
  104056. // set N to R-R
  104057. r.child2 = node;
  104058. node.parent = r;
  104059. // [ R ]
  104060. // / \
  104061. // [R-L] [ N ]
  104062. // / \ / \
  104063. // [...] [...] [ L ] [ R ]
  104064. // set R-R
  104065. node.child2 = rr;
  104066. rr.parent = node;
  104067. // [ R ]
  104068. // / \
  104069. // [R-L] [ N ]
  104070. // / \ / \
  104071. // [...] [...] [ L ] [R-R]
  104072. // fix bounds and heights
  104073. node.aabb.combine(l.aabb, rr.aabb);
  104074. t = lh - rrh;
  104075. node.height = lh - (t & t >> 31) + 1;
  104076. r.aabb.combine(rl.aabb, node.aabb);
  104077. t = rlh - nh;
  104078. r.height = rlh - (t & t >> 31) + 1;
  104079. } else {
  104080. // set N to R-L
  104081. r.child1 = node;
  104082. node.parent = r;
  104083. // [ R ]
  104084. // / \
  104085. // [ N ] [R-R]
  104086. // / \ / \
  104087. // [ L ] [ R ] [...] [...]
  104088. // set R-L
  104089. node.child2 = rl;
  104090. rl.parent = node;
  104091. // [ R ]
  104092. // / \
  104093. // [ N ] [R-R]
  104094. // / \ / \
  104095. // [ L ] [R-L] [...] [...]
  104096. // fix bounds and heights
  104097. node.aabb.combine(l.aabb, rl.aabb);
  104098. t = lh - rlh;
  104099. node.height = lh - (t & t >> 31) + 1;
  104100. r.aabb.combine(node.aabb, rr.aabb);
  104101. t = nh - rrh;
  104102. r.height = nh - (t & t >> 31) + 1;
  104103. }
  104104. // set new parent of R
  104105. if (p != null) {
  104106. if (p.child1 == node) {
  104107. p.child1 = r;
  104108. } else {
  104109. p.child2 = r;
  104110. }
  104111. } else {
  104112. this.root = r;
  104113. }
  104114. r.parent = p;
  104115. return r;
  104116. }
  104117. return node;
  104118. },
  104119. fix: function (node) {
  104120. var c1 = node.child1;
  104121. var c2 = node.child2;
  104122. node.aabb.combine(c1.aabb, c2.aabb);
  104123. //var h1 = c1.height;
  104124. //var h2 = c2.height;
  104125. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  104126. /*if( h1 < h2 ) {
  104127. node.height = h2+1;
  104128. }else{
  104129. node.height = h1+1;
  104130. }*/
  104131. }
  104132. }
  104133. /**
  104134. * A broad-phase algorithm using dynamic bounding volume tree.
  104135. * @author saharan
  104136. * @author lo-th
  104137. */
  104138. OIMO.DBVTBroadPhase = function () {
  104139. OIMO.BroadPhase.call(this);
  104140. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  104141. this.tree = new OIMO.DBVT();
  104142. this.stack = [];
  104143. this.leaves = [];
  104144. this.numLeaves = 0;
  104145. };
  104146. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  104147. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  104148. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  104149. return new OIMO.DBVTProxy(shape);
  104150. };
  104151. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  104152. this.tree.insertLeaf(proxy.leaf);
  104153. this.leaves.push(proxy.leaf);
  104154. this.numLeaves++;
  104155. };
  104156. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  104157. this.tree.deleteLeaf(proxy.leaf);
  104158. var n = this.leaves.indexOf(proxy.leaf);
  104159. if (n > -1) {
  104160. this.leaves.splice(n, 1);
  104161. this.numLeaves--;
  104162. }
  104163. };
  104164. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  104165. if (this.numLeaves < 2) return;
  104166. var leaf, margin = 0.1, i = this.numLeaves;
  104167. while (i--) {
  104168. leaf = this.leaves[i];
  104169. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  104170. leaf.aabb.copy(leaf.proxy.aabb, margin);
  104171. this.tree.deleteLeaf(leaf);
  104172. this.tree.insertLeaf(leaf);
  104173. this.collide(leaf, this.tree.root);
  104174. }
  104175. }
  104176. };
  104177. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  104178. var stackCount = 2;
  104179. var s1, s2, n1, n2, l1, l2;
  104180. this.stack[0] = node1;
  104181. this.stack[1] = node2;
  104182. while (stackCount > 0) {
  104183. n1 = this.stack[--stackCount];
  104184. n2 = this.stack[--stackCount];
  104185. l1 = n1.proxy != null;
  104186. l2 = n2.proxy != null;
  104187. this.numPairChecks++;
  104188. if (l1 && l2) {
  104189. s1 = n1.proxy.shape;
  104190. s2 = n2.proxy.shape;
  104191. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  104192. this.addPair(s1, s2);
  104193. } else {
  104194. if (n1.aabb.intersectTest(n2.aabb)) continue;
  104195. /*if(stackCount+4>=this.maxStack){// expand the stack
  104196. //this.maxStack<<=1;
  104197. this.maxStack*=2;
  104198. var newStack = [];// vector
  104199. newStack.length = this.maxStack;
  104200. for(var i=0;i<stackCount;i++){
  104201. newStack[i] = this.stack[i];
  104202. }
  104203. this.stack = newStack;
  104204. }*/
  104205. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  104206. this.stack[stackCount++] = n1.child1;
  104207. this.stack[stackCount++] = n2;
  104208. this.stack[stackCount++] = n1.child2;
  104209. this.stack[stackCount++] = n2;
  104210. } else {
  104211. this.stack[stackCount++] = n1;
  104212. this.stack[stackCount++] = n2.child1;
  104213. this.stack[stackCount++] = n1;
  104214. this.stack[stackCount++] = n2.child2;
  104215. }
  104216. }
  104217. }
  104218. };
  104219. /**
  104220. * A node of the dynamic bounding volume tree.
  104221. * @author saharan
  104222. */
  104223. OIMO.DBVTNode = function () {
  104224. // The first child node of this node.
  104225. this.child1 = null;
  104226. // The second child node of this node.
  104227. this.child2 = null;
  104228. // The parent node of this tree.
  104229. this.parent = null;
  104230. // The proxy of this node. This has no value if this node is not leaf.
  104231. this.proxy = null;
  104232. // The maximum distance from leaf nodes.
  104233. this.height = 0;
  104234. // The AABB of this node.
  104235. this.aabb = new OIMO.AABB();
  104236. };
  104237. /**
  104238. * A proxy for dynamic bounding volume tree broad-phase.
  104239. * @author saharan
  104240. */
  104241. OIMO.DBVTProxy = function (shape) {
  104242. OIMO.Proxy.call(this, shape);
  104243. // The leaf of the proxy.
  104244. this.leaf = new OIMO.DBVTNode();
  104245. this.leaf.proxy = this;
  104246. };
  104247. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  104248. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  104249. OIMO.DBVTProxy.prototype.update = function () {
  104250. };
  104251. OIMO.World.prototype.add = function (obj) {
  104252. obj = obj || {};
  104253. var type = obj.type || "box";
  104254. if (typeof type === 'string') type = [type];// single shape
  104255. if (type[0].substring(0, 5) == 'joint') { // is joint
  104256. if (type[0] === 'joint') type[0] = 'jointHinge';
  104257. var axe1 = obj.axe1 || [1, 0, 0];
  104258. var axe2 = obj.axe2 || [1, 0, 0];
  104259. var pos1 = obj.pos1 || [0, 0, 0];
  104260. var pos2 = obj.pos2 || [0, 0, 0];
  104261. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  104262. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  104263. var min, max;
  104264. if (type[0] === "jointDistance") {
  104265. min = obj.min || 0;
  104266. max = obj.max || 10;
  104267. min = min * OIMO.INV_SCALE;
  104268. max = max * OIMO.INV_SCALE;
  104269. } else {
  104270. min = obj.min || 57.29578;
  104271. max = obj.max || 0;
  104272. min = min * OIMO.degtorad;
  104273. max = max * OIMO.degtorad;
  104274. }
  104275. var limit = obj.limit || null;
  104276. var spring = obj.spring || null;
  104277. var motor = obj.motor || null;
  104278. // joint setting
  104279. var jc = new OIMO.JointConfig();
  104280. jc.allowCollision = obj.collision || false;;
  104281. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  104282. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  104283. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  104284. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  104285. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  104286. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  104287. jc.body1 = obj.body1;
  104288. jc.body2 = obj.body2;
  104289. var joint;
  104290. switch (type[0]) {
  104291. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  104292. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  104293. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  104294. break;
  104295. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  104296. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  104297. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  104298. break;
  104299. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  104300. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  104301. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  104302. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  104303. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  104304. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  104305. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  104306. break;
  104307. }
  104308. joint.name = obj.name || '';
  104309. // finaly add to physics world
  104310. this.addJoint(joint);
  104311. return joint;
  104312. } else { // is body
  104313. // I'm dynamique or not
  104314. var move = obj.move || false;
  104315. // I can sleep or not
  104316. var noSleep = obj.noSleep || false;
  104317. // My start position
  104318. var p = obj.pos || [0, 0, 0];
  104319. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  104320. // My size
  104321. var s = obj.size || [1, 1, 1];
  104322. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  104323. // My rotation in degre
  104324. var rot = obj.rot || [0, 0, 0];
  104325. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  104326. var r = [];
  104327. for (var i = 0; i < rot.length / 3; i++) {
  104328. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  104329. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  104330. }
  104331. // My physics setting
  104332. var sc = new OIMO.ShapeConfig();
  104333. if (obj.sc !== undefined) sc = obj.sc;
  104334. if (obj.config) {
  104335. // The density of the shape.
  104336. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  104337. // The coefficient of friction of the shape.
  104338. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  104339. // The coefficient of restitution of the shape.
  104340. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  104341. // The bits of the collision groups to which the shape belongs.
  104342. sc.belongsTo = obj.config[3] || 1;
  104343. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  104344. // The bits of the collision groups with which the shape collides.
  104345. sc.collidesWith = obj.config[4] || 0xffffffff;
  104346. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  104347. }
  104348. // direct physics setting
  104349. if (obj.density !== undefined) sc.density = obj.density;
  104350. if (obj.friction !== undefined) sc.friction = obj.friction;
  104351. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  104352. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  104353. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  104354. if (obj.massPos) {
  104355. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  104356. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  104357. }
  104358. if (obj.massRot) {
  104359. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  104360. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  104361. }
  104362. // My rigidbody
  104363. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  104364. // My shapes
  104365. var shapes = [];
  104366. //if( typeof type === 'string' ) type = [type];// single shape
  104367. var n, n2;
  104368. for (var i = 0; i < type.length; i++) {
  104369. n = i * 3;
  104370. n2 = i * 4;
  104371. switch (type[i]) {
  104372. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  104373. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  104374. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  104375. }
  104376. body.addShape(shapes[i]);
  104377. if (i > 0) {
  104378. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  104379. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  104380. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  104381. }
  104382. }
  104383. // I'm static or i move
  104384. if (move) {
  104385. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  104386. else body.setupMass(0x1, true);
  104387. if (noSleep) body.allowSleep = false;
  104388. else body.allowSleep = true;
  104389. } else {
  104390. body.setupMass(0x2);
  104391. }
  104392. body.name = obj.name || ' ';
  104393. // finaly add to physics world
  104394. this.addRigidBody(body);
  104395. return body;
  104396. }
  104397. }
  104398. //UMD simplified
  104399. var root = this;
  104400. if (!root['OIMO']) {
  104401. if (true)
  104402. module.exports = OIMO;
  104403. else if (typeof define === 'function' && define.amd)
  104404. define([], function () {
  104405. return OIMO;
  104406. });
  104407. else if (typeof exports === 'object')
  104408. exports["OIMO"] = OIMO;
  104409. else {
  104410. root["OIMO"] = OIMO;
  104411. }
  104412. }
  104413. /***/ }),
  104414. /* 19 */
  104415. /***/ (function(module, exports, __webpack_require__) {
  104416. "use strict";
  104417. Object.defineProperty(exports, "__esModule", { value: true });
  104418. var babylonjs_1 = __webpack_require__(0);
  104419. var helper_1 = __webpack_require__(2);
  104420. var TemplateManager = (function () {
  104421. function TemplateManager(containerElement) {
  104422. this.containerElement = containerElement;
  104423. this.templates = {};
  104424. this.onInit = new babylonjs_1.Observable();
  104425. this.onLoaded = new babylonjs_1.Observable();
  104426. this.onStateChange = new babylonjs_1.Observable();
  104427. this.onAllLoaded = new babylonjs_1.Observable();
  104428. this.onEventTriggered = new babylonjs_1.Observable();
  104429. this.eventManager = new eventManager_1.EventManager(this);
  104430. }
  104431. TemplateManager.prototype.initTemplate = function (templates) {
  104432. var _this = this;
  104433. var internalInit = function (dependencyMap, name, parentTemplate) {
  104434. var template = _this.templates[name];
  104435. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  104436. return internalInit(dependencyMap[childName], childName, template);
  104437. });
  104438. var addToParent = function () {
  104439. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  104440. template.appendTo(containingElement);
  104441. _this.checkLoadedState();
  104442. };
  104443. if (parentTemplate && !parentTemplate.parent) {
  104444. parentTemplate.onAppended.add(function () {
  104445. addToParent();
  104446. });
  104447. }
  104448. else {
  104449. addToParent();
  104450. }
  104451. return template;
  104452. };
  104453. return this.buildHTMLTree(templates).then(function (htmlTree) {
  104454. if (_this.templates['main']) {
  104455. internalInit(htmlTree, 'main');
  104456. }
  104457. else {
  104458. _this.checkLoadedState();
  104459. }
  104460. return;
  104461. });
  104462. };
  104463. TemplateManager.prototype.buildHTMLTree = function (templates) {
  104464. var _this = this;
  104465. var promises = Object.keys(templates).map(function (name) {
  104466. if (!templates[name])
  104467. return Promise.resolve(false);
  104468. var template = new Template(name, templates[name]);
  104469. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  104470. _this.templates[name] = template;
  104471. return template.initPromise;
  104472. });
  104473. return Promise.all(promises).then(function () {
  104474. var templateStructure = {};
  104475. var buildTree = function (parentObject, name) {
  104476. _this.templates[name].isInHtmlTree = true;
  104477. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  104478. childNodes.forEach(function (element) {
  104479. parentObject[element] = {};
  104480. buildTree(parentObject[element], element);
  104481. });
  104482. };
  104483. if (_this.templates['main']) {
  104484. buildTree(templateStructure, "main");
  104485. }
  104486. return templateStructure;
  104487. });
  104488. };
  104489. TemplateManager.prototype.getCanvas = function () {
  104490. return this.containerElement.querySelector('canvas');
  104491. };
  104492. TemplateManager.prototype.getTemplate = function (name) {
  104493. return this.templates[name];
  104494. };
  104495. TemplateManager.prototype.checkLoadedState = function () {
  104496. var _this = this;
  104497. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  104498. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  104499. });
  104500. if (done) {
  104501. this.onAllLoaded.notifyObservers(this);
  104502. }
  104503. };
  104504. TemplateManager.prototype.dispose = function () {
  104505. var _this = this;
  104506. Object.keys(this.templates).forEach(function (template) {
  104507. _this.templates[template].dispose();
  104508. });
  104509. this.onInit.clear();
  104510. this.onAllLoaded.clear();
  104511. this.onEventTriggered.clear();
  104512. this.onLoaded.clear();
  104513. this.onStateChange.clear();
  104514. };
  104515. return TemplateManager;
  104516. }());
  104517. exports.TemplateManager = TemplateManager;
  104518. var Handlebars = __webpack_require__(20);
  104519. var eventManager_1 = __webpack_require__(21);
  104520. Handlebars.registerHelper('eachInMap', function (map, block) {
  104521. var out = '';
  104522. Object.keys(map).map(function (prop) {
  104523. var data = map[prop];
  104524. if (typeof data === 'object') {
  104525. data.id = data.id || prop;
  104526. out += block.fn(data);
  104527. }
  104528. else {
  104529. out += block.fn({ id: prop, value: data });
  104530. }
  104531. });
  104532. return out;
  104533. });
  104534. var Template = (function () {
  104535. function Template(name, _configuration) {
  104536. var _this = this;
  104537. this.name = name;
  104538. this._configuration = _configuration;
  104539. this.onInit = new babylonjs_1.Observable();
  104540. this.onLoaded = new babylonjs_1.Observable();
  104541. this.onAppended = new babylonjs_1.Observable();
  104542. this.onStateChange = new babylonjs_1.Observable();
  104543. this.onEventTriggered = new babylonjs_1.Observable();
  104544. this.loadRequests = [];
  104545. this.isLoaded = false;
  104546. this.isShown = false;
  104547. this.isInHtmlTree = false;
  104548. this.onInit.notifyObservers(this);
  104549. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  104550. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  104551. if (htmlTemplate) {
  104552. _this.htmlTemplate = htmlTemplate;
  104553. var compiledTemplate = Handlebars.compile(htmlTemplate);
  104554. var config = _this._configuration.params || {};
  104555. var rawHtml = compiledTemplate(config);
  104556. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  104557. _this.isLoaded = true;
  104558. _this.isShown = true;
  104559. _this.onLoaded.notifyObservers(_this);
  104560. }
  104561. return _this;
  104562. });
  104563. }
  104564. Template.prototype.updateParams = function (params) {
  104565. this._configuration.params = params;
  104566. if (this.isLoaded) {
  104567. this.dispose();
  104568. }
  104569. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  104570. var config = this._configuration.params || {};
  104571. var rawHtml = compiledTemplate(config);
  104572. this.fragment = document.createRange().createContextualFragment(rawHtml);
  104573. if (this.parent) {
  104574. this.appendTo(this.parent, true);
  104575. }
  104576. };
  104577. Object.defineProperty(Template.prototype, "configuration", {
  104578. get: function () {
  104579. return this._configuration;
  104580. },
  104581. enumerable: true,
  104582. configurable: true
  104583. });
  104584. Template.prototype.getChildElements = function () {
  104585. var childrenArray = [];
  104586. var children = this.fragment.children;
  104587. if (!children) {
  104588. children = this.fragment.querySelectorAll('*');
  104589. }
  104590. for (var i = 0; i < children.length; ++i) {
  104591. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  104592. }
  104593. return childrenArray;
  104594. };
  104595. Template.prototype.appendTo = function (parent, forceRemove) {
  104596. var _this = this;
  104597. if (this.parent) {
  104598. if (forceRemove) {
  104599. this.parent.removeChild(this.fragment);
  104600. }
  104601. else {
  104602. return;
  104603. }
  104604. }
  104605. this.parent = parent;
  104606. if (this._configuration.id) {
  104607. this.parent.id = this._configuration.id;
  104608. }
  104609. this.fragment = this.parent.appendChild(this.fragment);
  104610. setTimeout(function () {
  104611. _this.registerEvents();
  104612. _this.onAppended.notifyObservers(_this);
  104613. });
  104614. };
  104615. Template.prototype.show = function (visibilityFunction) {
  104616. var _this = this;
  104617. if (this.isHiding)
  104618. return Promise.resolve(this);
  104619. return Promise.resolve().then(function () {
  104620. _this.isShowing = true;
  104621. if (visibilityFunction) {
  104622. return visibilityFunction(_this);
  104623. }
  104624. else {
  104625. _this.parent.style.display = 'flex';
  104626. return _this;
  104627. }
  104628. }).then(function () {
  104629. _this.isShown = true;
  104630. _this.isShowing = false;
  104631. _this.onStateChange.notifyObservers(_this);
  104632. return _this;
  104633. });
  104634. };
  104635. Template.prototype.hide = function (visibilityFunction) {
  104636. var _this = this;
  104637. if (this.isShowing)
  104638. return Promise.resolve(this);
  104639. return Promise.resolve().then(function () {
  104640. _this.isHiding = true;
  104641. if (visibilityFunction) {
  104642. return visibilityFunction(_this);
  104643. }
  104644. else {
  104645. _this.parent.style.display = 'hide';
  104646. return _this;
  104647. }
  104648. }).then(function () {
  104649. _this.isShown = false;
  104650. _this.isHiding = false;
  104651. _this.onStateChange.notifyObservers(_this);
  104652. return _this;
  104653. });
  104654. };
  104655. Template.prototype.dispose = function () {
  104656. this.onAppended.clear();
  104657. this.onEventTriggered.clear();
  104658. this.onInit.clear();
  104659. this.onLoaded.clear();
  104660. this.onStateChange.clear();
  104661. this.isLoaded = false;
  104662. this.parent.removeChild(this.fragment);
  104663. this.loadRequests.forEach(function (request) {
  104664. request.abort();
  104665. });
  104666. };
  104667. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  104668. var _this = this;
  104669. if (!templateConfig) {
  104670. return Promise.reject('No templateConfig provided');
  104671. }
  104672. else if (templateConfig.html !== undefined) {
  104673. return Promise.resolve(templateConfig.html);
  104674. }
  104675. else {
  104676. var location_1 = getTemplateLocation(templateConfig);
  104677. if (helper_1.isUrl(location_1)) {
  104678. return new Promise(function (resolve, reject) {
  104679. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  104680. resolve(data);
  104681. }, undefined, undefined, false, function (request, error) {
  104682. reject(error);
  104683. });
  104684. _this.loadRequests.push(fileRequest);
  104685. });
  104686. }
  104687. else {
  104688. location_1 = location_1.replace('#', '');
  104689. var element = document.getElementById(location_1);
  104690. if (element) {
  104691. return Promise.resolve(element.innerHTML);
  104692. }
  104693. else {
  104694. return Promise.reject('Template ID not found');
  104695. }
  104696. }
  104697. }
  104698. };
  104699. Template.prototype.registerEvents = function () {
  104700. var _this = this;
  104701. this.registeredEvents = this.registeredEvents || [];
  104702. if (this.registeredEvents.length) {
  104703. this.registeredEvents.forEach(function (evt) {
  104704. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  104705. });
  104706. }
  104707. if (this._configuration.events) {
  104708. var _loop_1 = function (eventName) {
  104709. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  104710. var functionToFire_1 = function (selector, event) {
  104711. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  104712. };
  104713. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  104714. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  104715. }
  104716. else if (typeof this_1._configuration.events[eventName] === 'object') {
  104717. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  104718. var event_1 = this_1._configuration.events[eventName] || {};
  104719. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  104720. if (selector && selector.indexOf('#') !== 0) {
  104721. selector = '#' + selector;
  104722. }
  104723. var htmlElement = _this.parent.querySelector(selector);
  104724. if (htmlElement) {
  104725. var binding = functionToFire_1.bind(_this, selector);
  104726. htmlElement.addEventListener(eventName, binding, false);
  104727. _this.registeredEvents.push({
  104728. htmlElement: htmlElement,
  104729. eventName: eventName,
  104730. function: binding
  104731. });
  104732. }
  104733. });
  104734. }
  104735. }
  104736. };
  104737. var this_1 = this;
  104738. for (var eventName in this._configuration.events) {
  104739. _loop_1(eventName);
  104740. }
  104741. }
  104742. };
  104743. return Template;
  104744. }());
  104745. exports.Template = Template;
  104746. function getTemplateLocation(templateConfig) {
  104747. if (!templateConfig || typeof templateConfig === 'string') {
  104748. return templateConfig;
  104749. }
  104750. else {
  104751. return templateConfig.location;
  104752. }
  104753. }
  104754. exports.getTemplateLocation = getTemplateLocation;
  104755. /***/ }),
  104756. /* 20 */
  104757. /***/ (function(module, exports, __webpack_require__) {
  104758. /**!
  104759. @license
  104760. handlebars v4.0.11
  104761. Copyright (C) 2011-2017 by Yehuda Katz
  104762. Permission is hereby granted, free of charge, to any person obtaining a copy
  104763. of this software and associated documentation files (the "Software"), to deal
  104764. in the Software without restriction, including without limitation the rights
  104765. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  104766. copies of the Software, and to permit persons to whom the Software is
  104767. furnished to do so, subject to the following conditions:
  104768. The above copyright notice and this permission notice shall be included in
  104769. all copies or substantial portions of the Software.
  104770. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  104771. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  104772. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  104773. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  104774. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  104775. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  104776. THE SOFTWARE.
  104777. */
  104778. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}var e=c(1)["default"];b.__esModule=!0;var f=c(2),g=e(f),h=c(35),i=e(h),j=c(36),k=c(41),l=c(42),m=e(l),n=c(39),o=e(n),p=c(34),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(3)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(4),h=e(g),i=c(21),j=f(i),k=c(6),l=f(k),m=c(5),n=e(m),o=c(22),p=e(o),q=c(34),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(1)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(5),g=c(6),h=e(g),i=c(10),j=c(18),k=c(20),l=e(k),m="4.0.11";b.VERSION=m;var n=7;b.COMPILER_REVISION=n;var o={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0"};b.REVISION_CHANGES=o;var p="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===p)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]}};var q=l["default"].log;b.log=q,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0;c&&(g=c.start.line,h=c.start.column,a+=" - "+g+":"+h);for(var i=Error.prototype.constructor.call(this,a),j=0;j<f.length;j++)this[f[j]]=i[f[j]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,e?Object.defineProperty(this,"column",{value:h,enumerable:!0}):this.column=h)}catch(k){}}var e=c(7)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(8),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){g["default"](a),i["default"](a),k["default"](a),m["default"](a),o["default"](a),q["default"](a),s["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultHelpers=d;var f=c(11),g=e(f),h=c(12),i=e(h),j=c(13),k=e(j),l=c(14),m=e(l),n=c(15),o=e(n),p=c(16),q=e(p),r=c(17),s=e(r)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,f){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!f,k&&(j.contextPath=k+b)),i+=d(a[b],{data:j,blockParams:e.blockParams([a[b],b],[k+b,null])})}if(!b)throw new g["default"]("Must pass iterator to #each");var d=b.fn,f=b.inverse,h=0,i="",j=void 0,k=void 0;if(b.data&&b.ids&&(k=e.appendContextPath(b.data.contextPath,b.ids[0])+"."),e.isFunction(a)&&(a=a.call(this)),b.data&&(j=e.createFrame(b.data)),a&&"object"==typeof a)if(e.isArray(a))for(var l=a.length;h<l;h++)h in a&&c(h,h,h===a.length-1);else{var m=void 0;for(var n in a)a.hasOwnProperty(n)&&(void 0!==m&&c(m,h-1),m=n,h++);void 0!==m&&c(m,h-1,!0)}return 0===h&&(i=f(this)),i})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(6),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("if",function(a,b){return d.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||d.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b){return a&&a[b]})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("with",function(a,b){d.isFunction(a)&&(a=a.call(this));var c=b.fn;if(d.isEmpty(a))return b.inverse(this);var e=b.data;return b.data&&b.ids&&(e=d.createFrame(b.data),e.contextPath=d.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:e,blockParams:d.blockParams([a],[e&&e.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(19),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=s.COMPILER_REVISION;if(b!==c){if(b<c){var d=s.REVISION_CHANGES[c],e=s.REVISION_CHANGES[b];throw new r["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new r["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=p.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;h<i&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new r["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(e,b,e.helpers,e.partials,g,i,h)}var f=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],g=f.data;d._setup(f),!f.partial&&a.useData&&(g=j(b,g));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=f.depths?b!=f.depths[0]?[b].concat(f.depths):f.depths:[b]),(c=k(a.main,c,e,f.depths||[],g,i))(b,f)}if(!b)throw new r["default"]("No environment passed to template");if(!a||!a.main)throw new r["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new r["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:p.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=p.extend({},b,a)),c},nullContext:l({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials,e.decorators=c.decorators):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(e.decorators=e.merge(c.decorators,b.decorators)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new r["default"]("must pass block params");if(a.useDepths&&!g)throw new r["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=s.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=s.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=p.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new r["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?s.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),p.extend(b,g)}return b}var l=c(23)["default"],m=c(3)["default"],n=c(1)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var o=c(5),p=m(o),q=c(6),r=n(q),s=c(4)},function(a,b,c){a.exports={"default":c(24),__esModule:!0}},function(a,b,c){c(25),a.exports=c(30).Object.seal},function(a,b,c){var d=c(26);c(27)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b,c){var d=c(28),e=c(30),f=c(33);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){var d=c(29),e=c(30),f=c(31),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(32);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&&!!(a.params&&a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;h["default"].yy=n,n.locInfo=function(a){return new n.SourceLocation(b&&b.srcName,a)};var c=new j["default"](b);return c.accept(h["default"].parse(a))}var e=c(1)["default"],f=c(3)["default"];b.__esModule=!0,b.parse=d;var g=c(37),h=e(g),i=c(38),j=e(i),k=c(40),l=f(k),m=c(5);b.parser=h["default"];var n={};m.extend(n,l)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition_plus0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,1],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:this.$=f[h];break;case 4:this.$=f[h];break;case 5:this.$=f[h];break;case 6:this.$=f[h];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 20:this.$=f[h];break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 27:this.$=f[h];break;case 28:this.$=f[h];break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 33:this.$=f[h];break;case 34:this.$=f[h];break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:this.$=[];break;case 47:f[h-1].push(f[h]);break;case 48:this.$=[f[h]];break;case 49:f[h-1].push(f[h]);break;case 50:this.$=[];break;case 51:f[h-1].push(f[h]);break;case 58:this.$=[];break;case 59:f[h-1].push(f[h]);break;case 64:this.$=[];break;case 65:f[h-1].push(f[h]);break;case 70:this.$=[];break;case 71:f[h-1].push(f[h]);break;case 78:this.$=[];break;case 79:f[h-1].push(f[h]);break;case 82:this.$=[];break;case 83:f[h-1].push(f[h]);break;case 86:this.$=[];break;case 87:f[h-1].push(f[h]);break;case 90:this.$=[];break;case 91:f[h-1].push(f[h]);break;case 94:this.$=[];break;case 95:f[h-1].push(f[h]);break;case 98:this.$=[f[h]];break;case 99:f[h-1].push(f[h]);break;case 100:this.$=[f[h]];break;case 101:f[h-1].push(f[h])}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{13:40,15:[1,20],17:39},{20:42,56:41,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:45,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:48,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:42,56:49,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:50,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,51]},{72:[1,35],86:52},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:53,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:54,38:56,39:[1,58],43:57,44:[1,59],45:55,47:[2,54]},{28:60,43:61,44:[1,59],47:[2,56]},{13:63,15:[1,20],18:[1,62]},{15:[2,48],18:[2,48]},{33:[2,86],57:64,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:65,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:66,47:[1,67]},{30:68,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:69,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:70,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:71,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:75,33:[2,80],50:72,63:73,64:76,65:[1,44],69:74,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,80]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,51]},{20:75,53:81,54:[2,84],63:82,64:76,65:[1,44],69:83,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:84,47:[1,67]},{47:[2,55]},{4:85,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:86,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:87,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:88,47:[1,67]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:75,33:[2,88],58:89,63:90,64:76,65:[1,44],69:91,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:92,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:93,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,31:94,33:[2,60],63:95,64:76,65:[1,44],69:96,70:77,71:78,72:[1,79],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,66],36:97,63:98,64:76,65:[1,44],69:99,70:77,71:78,72:[1,79],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,22:100,23:[2,52],63:101,64:76,65:[1,44],69:102,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,92],62:103,63:104,64:76,65:[1,44],69:105,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,106]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:107,72:[1,108],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,109],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,110]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:56,39:[1,58],43:57,44:[1,59],45:112,46:111,47:[2,76]},{33:[2,70],40:113,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,114]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],
  104779. 85:[2,87]},{33:[2,89]},{20:75,63:116,64:76,65:[1,44],67:115,68:[2,96],69:117,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,118]},{32:119,33:[2,62],74:120,75:[1,121]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:122,74:123,75:[1,121]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,124]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,125]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,109]},{20:75,63:126,64:76,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:75,33:[2,72],41:127,63:128,64:76,65:[1,44],69:129,70:77,71:78,72:[1,79],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,130]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,131]},{33:[2,63]},{72:[1,133],76:132},{33:[1,134]},{33:[2,69]},{15:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:135,74:136,75:[1,121]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,138],77:[1,137]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,139]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],55:[2,55],57:[2,20],61:[2,57],74:[2,81],83:[2,85],87:[2,18],91:[2,89],102:[2,53],105:[2,93],111:[2,19],112:[2,77],117:[2,97],120:[2,63],123:[2,69],124:[2,12],136:[2,75],137:[2,32]},parseError:function(a,b){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:(null!==n&&"undefined"!=typeof n||(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(b.yytext=b.yytext.substr(5,b.yyleng-9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(1)["default"];b.__esModule=!0;var j=c(39),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,i=0,j=d.length;i<j;i++){var k=d[i],l=this.accept(k);if(l){var m=e(d,i,c),n=f(d,i,c),o=l.openStandalone&&m,p=l.closeStandalone&&n,q=l.inlineStandalone&&m&&n;l.close&&g(d,i,!0),l.open&&h(d,i,!0),b&&q&&(g(d,i),h(d,i)&&"PartialStatement"===k.type&&(k.indent=/([ \t]+$)/.exec(d[i-1].original)[1])),b&&o&&(g((k.program||k.inverse).body),h(d,i)),b&&p&&(g(d,i),h((k.inverse||k.program).body))}}return a},d.prototype.BlockStatement=d.prototype.DecoratorBlock=d.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),!this.options.ignoreStandalone&&e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.Decorator=d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}function e(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function f(a){e.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function g(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}var h=c(1)["default"];b.__esModule=!0;var i=c(6),j=h(i);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&!d.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;b<c;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:e,Decorator:e,BlockStatement:f,DecoratorBlock:f,PartialStatement:g,PartialBlockStatement:function(a){g.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:e,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function e(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function f(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function g(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function h(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function i(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g="",h=0,i=b.length;h<i;h++){var j=b[h].part,k=b[h].original!==j;if(d+=(b[h].separator||"")+j,k||".."!==j&&"."!==j&&"this"!==j)e.push(j);else{if(e.length>0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===j&&(f++,g+="../")}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function j(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function k(a,b,c,e){d(a,c),e=this.locInfo(e);var f={type:"Program",body:b,strip:{},loc:e};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:e}}function l(a,b,c,e,f,g){e&&e.path&&d(a,e);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&&(c.program.body[0].closeStrip=e.strip),j=c.strip,i=c.program}return f&&(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:e&&e.strip,loc:this.locInfo(g)}}function m(a,b){if(!b&&a.length){var c=a[0].loc,d=a[a.length-1].loc;c&&d&&(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function n(a,b,c,e){return d(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&&c.strip,loc:this.locInfo(e)}}var o=c(1)["default"];b.__esModule=!0,b.SourceLocation=e,b.id=f,b.stripFlags=g,b.stripComment=h,b.preparePath=i,b.prepareMustache=j,b.prepareRawBlock=k,b.prepareBlock=l,b.prepareProgram=m,b.preparePartialBlock=n;var p=c(6),q=o(p)},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var d=c.parse(a,b),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}function e(a,b){return f||(f=d()),f.call(this,a,b)}if(void 0===b&&(b={}),null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=l.extend({},b),"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var f=void 0;return e._setup=function(a){return f||(f=d()),f._setup(a)},e._child=function(a,b,c,e){return f||(f=d()),f._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(l.isArray(a)&&l.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path={type:"PathExpression",data:!1,depth:0,parts:[b.original+""],original:b.original+"",loc:b.loc}}}var i=c(1)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var j=c(6),k=i(j),l=c(5),m=c(35),n=i(m),o=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;c<b;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;c<b;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&&(this.options.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new k["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;d<c;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&&this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&&(b=this.compileProgram(a.program));var c=a.params;if(c.length>1)throw new k["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&&this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&&f&&(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new k["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,n["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=n["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");c<d;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:o.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=n["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&n["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;b<c;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||n["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;b<c;b++){var d=this.options.blockParams[b],e=d&&l.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;f<g;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}var g=c(1)["default"];b.__esModule=!0;var h=c(4),i=c(6),j=g(i),k=c(5),l=c(43),m=g(l);e.prototype={nameLookup:function(a,b){return e.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"[",JSON.stringify(b),"]"]},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;h<i;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend("var decorators = container.decorators;\n"),this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k};this.decorators&&(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;h<i;h++)n[h]&&(l[h]=n[h],o[h]&&(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName),this.decorators=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&&f.children&&f.referenceCount>1&&(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&g.push("blockParams"),this.useDepths&&g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend(" + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var g=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict&&e,this,b,a));for(var h=b.length;c<h;c++)this.replaceStack(function(e){
  104780. var f=g.nameLookup(e,b[c],a);return d?[" && ",f]:[" != null ? ",f," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):"SubExpression"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;f<g;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);if(null==h){this.context.programs.push("");var i=this.context.programs.length;d.index=i,d.name="program"+i,this.context.programs[i]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[i]=e.decorators,this.context.environments[i]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams,d.useDepths=this.useDepths,d.useBlockParams=this.useBlockParams}else d.index=h.index,d.name="program"+h.index,this.useDepths=this.useDepths||h.useDepths,this.useBlockParams=this.useBlockParams||h.useBlockParams}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;b<c;b++){var d=this.context.environments[b];if(d&&d.equals(a))return d}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;b<c;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=!c,i=void 0;h&&(c=[]),d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var j=this.popStack(),k=this.popStack();(k||j)&&(d.fn=k||"container.noop",d.inverse=j||"container.noop");for(var l=b;l--;)i=this.popStack(),c[l]=i,this.trackIds&&(g[l]=this.popStack()),this.stringParams&&(f[l]=this.popStack(),e[l]=this.popStack());return h&&(d.args=this.source.generateArray(c)),this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;c<d;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;e<g;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(5),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&&this.add(d)},g.prototype={add:function(a){f.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add([" ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;b<c;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length<=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&&b.push([this.quotedString(c),":",e])}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;c<e;c++)c&&b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])});
  104781. /***/ }),
  104782. /* 21 */
  104783. /***/ (function(module, exports, __webpack_require__) {
  104784. "use strict";
  104785. Object.defineProperty(exports, "__esModule", { value: true });
  104786. var EventManager = (function () {
  104787. function EventManager(templateManager) {
  104788. var _this = this;
  104789. this.templateManager = templateManager;
  104790. this.callbacksContainer = {};
  104791. this.templateManager.onEventTriggered.add(function (eventData) {
  104792. _this.eventTriggered(eventData);
  104793. });
  104794. }
  104795. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  104796. if (!this.callbacksContainer[templateName]) {
  104797. this.callbacksContainer[templateName] = [];
  104798. }
  104799. this.callbacksContainer[templateName].push({
  104800. eventType: eventType,
  104801. callback: callback
  104802. });
  104803. };
  104804. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  104805. var callbackDefs = this.callbacksContainer[templateName] || [];
  104806. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  104807. };
  104808. EventManager.prototype.eventTriggered = function (data) {
  104809. var templateName = data.template.name;
  104810. var eventType = data.event.type;
  104811. var selector = data.selector;
  104812. var callbackDefs = this.callbacksContainer[templateName] || [];
  104813. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  104814. callbackDef.callback(data);
  104815. });
  104816. };
  104817. return EventManager;
  104818. }());
  104819. exports.EventManager = EventManager;
  104820. /***/ }),
  104821. /* 22 */
  104822. /***/ (function(module, exports, __webpack_require__) {
  104823. "use strict";
  104824. Object.defineProperty(exports, "__esModule", { value: true });
  104825. var mappers_1 = __webpack_require__(1);
  104826. var types_1 = __webpack_require__(23);
  104827. var deepmerge = __webpack_require__(13);
  104828. var babylonjs_1 = __webpack_require__(0);
  104829. var ConfigurationLoader = (function () {
  104830. function ConfigurationLoader() {
  104831. this.configurationCache = {};
  104832. this.loadRequests = [];
  104833. }
  104834. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  104835. var _this = this;
  104836. if (initConfig === void 0) { initConfig = {}; }
  104837. var loadedConfig = deepmerge({}, initConfig);
  104838. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  104839. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  104840. if (loadedConfig.configuration) {
  104841. var mapperType_1 = "json";
  104842. return Promise.resolve().then(function () {
  104843. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  104844. var url = '';
  104845. if (typeof loadedConfig.configuration === "string") {
  104846. url = loadedConfig.configuration;
  104847. }
  104848. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  104849. url = loadedConfig.configuration.url;
  104850. var type = loadedConfig.configuration.mapper;
  104851. if (!type) {
  104852. type = loadedConfig.configuration.url.split('.').pop();
  104853. }
  104854. mapperType_1 = type || mapperType_1;
  104855. }
  104856. return _this.loadFile(url);
  104857. }
  104858. else {
  104859. if (typeof loadedConfig.configuration === "object") {
  104860. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  104861. return loadedConfig.configuration.payload || {};
  104862. }
  104863. return {};
  104864. }
  104865. }).then(function (data) {
  104866. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  104867. var parsed = mapper.map(data);
  104868. var merged = deepmerge(loadedConfig, parsed);
  104869. if (callback)
  104870. callback(merged);
  104871. return merged;
  104872. });
  104873. }
  104874. else {
  104875. if (callback)
  104876. callback(loadedConfig);
  104877. return Promise.resolve(loadedConfig);
  104878. }
  104879. };
  104880. ConfigurationLoader.prototype.dispose = function () {
  104881. this.loadRequests.forEach(function (request) {
  104882. request.abort();
  104883. });
  104884. };
  104885. ConfigurationLoader.prototype.loadFile = function (url) {
  104886. var _this = this;
  104887. var cacheReference = this.configurationCache;
  104888. if (cacheReference[url]) {
  104889. return Promise.resolve(cacheReference[url]);
  104890. }
  104891. return new Promise(function (resolve, reject) {
  104892. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  104893. reject(error);
  104894. });
  104895. _this.loadRequests.push(fileRequest);
  104896. });
  104897. };
  104898. return ConfigurationLoader;
  104899. }());
  104900. exports.ConfigurationLoader = ConfigurationLoader;
  104901. exports.configurationLoader = new ConfigurationLoader();
  104902. exports.default = exports.configurationLoader;
  104903. /***/ }),
  104904. /* 23 */
  104905. /***/ (function(module, exports, __webpack_require__) {
  104906. "use strict";
  104907. Object.defineProperty(exports, "__esModule", { value: true });
  104908. var minimal_1 = __webpack_require__(24);
  104909. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  104910. var default_1 = __webpack_require__(25);
  104911. exports.defaultConfiguration = default_1.defaultConfiguration;
  104912. var getConfigurationType = function (type) {
  104913. switch (type) {
  104914. case 'default':
  104915. return default_1.defaultConfiguration;
  104916. case 'minimal':
  104917. return minimal_1.minimalConfiguration;
  104918. case 'none':
  104919. return {};
  104920. default:
  104921. return default_1.defaultConfiguration;
  104922. }
  104923. };
  104924. exports.getConfigurationType = getConfigurationType;
  104925. /***/ }),
  104926. /* 24 */
  104927. /***/ (function(module, exports, __webpack_require__) {
  104928. "use strict";
  104929. Object.defineProperty(exports, "__esModule", { value: true });
  104930. exports.minimalConfiguration = {
  104931. version: "0.1",
  104932. templates: {
  104933. main: {
  104934. html: __webpack_require__(6)
  104935. },
  104936. loadingScreen: {
  104937. html: __webpack_require__(7),
  104938. params: {
  104939. backgroundColor: "#000000",
  104940. loadingImage: __webpack_require__(8)
  104941. }
  104942. },
  104943. viewer: {
  104944. html: __webpack_require__(9),
  104945. },
  104946. overlay: {
  104947. html: __webpack_require__(10),
  104948. params: {
  104949. closeImage: __webpack_require__(11),
  104950. closeText: 'Close'
  104951. }
  104952. },
  104953. error: {
  104954. html: __webpack_require__(12)
  104955. }
  104956. },
  104957. engine: {
  104958. antialiasing: true
  104959. }
  104960. };
  104961. /***/ }),
  104962. /* 25 */
  104963. /***/ (function(module, exports, __webpack_require__) {
  104964. "use strict";
  104965. Object.defineProperty(exports, "__esModule", { value: true });
  104966. exports.defaultConfiguration = {
  104967. version: "3.2.0-alpha4",
  104968. templates: {
  104969. main: {
  104970. html: __webpack_require__(6)
  104971. },
  104972. loadingScreen: {
  104973. html: __webpack_require__(7),
  104974. params: {
  104975. backgroundColor: "#000000",
  104976. loadingImage: __webpack_require__(8)
  104977. }
  104978. },
  104979. viewer: {
  104980. html: __webpack_require__(9),
  104981. events: {
  104982. pointerout: true,
  104983. pointerdown: true,
  104984. pointerup: true
  104985. }
  104986. },
  104987. navBar: {
  104988. html: __webpack_require__(26),
  104989. params: {
  104990. buttons: {
  104991. "fullscreen-button": {
  104992. altText: "Fullscreen",
  104993. image: __webpack_require__(27)
  104994. }
  104995. },
  104996. visibilityTimeout: 2000
  104997. },
  104998. events: {
  104999. pointerdown: { 'fullscreen-button': true },
  105000. pointerover: true
  105001. }
  105002. },
  105003. overlay: {
  105004. html: __webpack_require__(10),
  105005. params: {
  105006. closeImage: __webpack_require__(11),
  105007. closeText: 'Close'
  105008. }
  105009. },
  105010. help: {
  105011. html: __webpack_require__(28)
  105012. },
  105013. share: {
  105014. html: __webpack_require__(29)
  105015. },
  105016. error: {
  105017. html: __webpack_require__(12)
  105018. }
  105019. },
  105020. camera: {
  105021. behaviors: {
  105022. autoRotate: 0,
  105023. framing: {
  105024. type: 2,
  105025. zoomOnBoundingInfo: true,
  105026. zoomStopsAnimation: false
  105027. }
  105028. }
  105029. },
  105030. skybox: {
  105031. pbr: true,
  105032. blur: 0.7,
  105033. infiniteDIstance: false,
  105034. },
  105035. ground: true,
  105036. engine: {
  105037. antialiasing: true
  105038. },
  105039. scene: {
  105040. imageProcessingConfiguration: {
  105041. exposure: 1.4,
  105042. contrast: 1.66,
  105043. toneMappingEnabled: true
  105044. }
  105045. }
  105046. };
  105047. /***/ }),
  105048. /* 26 */
  105049. /***/ (function(module, exports) {
  105050. module.exports = "<style>nav-bar{position:absolute;height:160px;width:100%;bottom:0;background-color:rgba(0,0,0,.3);color:#fff;transition:1s;align-items:flex-start;justify-content:space-around;display:flex;flex-direction:column}@media screen and (min-width:768px){nav-bar{align-items:center;flex-direction:row;justify-content:space-between;height:80px}}div.flex-container{display:flex;width:100%}div.thumbnail{position:relative;overflow:hidden;display:block;width:40px;height:40px;background-size:cover;background-position:center;border-radius:20px;margin:0 10px}div.title-container{flex-direction:column;display:flex;justify-content:space-between}span.model-title{font-size:125%}span.model-subtitle{font-size:90%}div.button-container{align-items:center;justify-content:flex-end}div.button{cursor:pointer;height:30px;margin:0 10px}div.button img{height:100%}</style> {{#if disableOnFullscreen}} <style>viewer:fullscreen nav-bar{display:none}viewer:-moz-full-screen nav-bar{display:none}viewer:-webkit-full-screen nav-bar{display:none}</style> {{/if}} <div class=flex-container id=model-metadata> <div class=thumbnail> </div> <div class=title-container> <span class=model-title>{{#if title}}{{title}}{{/if}}</span> <span class=model-subtitle> {{#if subtitle}}{{subtitle}} {{/if}}</span> </div> </div> <div class=\"button-container flex-container\"> {{#eachInMap buttons}} <div id={{id}} class=button> {{#if text}} <span>{{text}}</span>> {{/if}} {{#if image}} <img src={{image}} alt={{altText}}> {{/if}} </div> {{/eachInMap}} </div>";
  105051. /***/ }),
  105052. /* 27 */
  105053. /***/ (function(module, exports) {
  105054. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  105055. /***/ }),
  105056. /* 28 */
  105057. /***/ (function(module, exports) {
  105058. module.exports = "HELP";
  105059. /***/ }),
  105060. /* 29 */
  105061. /***/ (function(module, exports) {
  105062. module.exports = "SHARE";
  105063. /***/ }),
  105064. /* 30 */
  105065. /***/ (function(module, exports, __webpack_require__) {
  105066. "use strict";
  105067. Object.defineProperty(exports, "__esModule", { value: true });
  105068. var babylonjs_1 = __webpack_require__(0);
  105069. var modelAnimation_1 = __webpack_require__(31);
  105070. var ViewerModel = (function () {
  105071. function ViewerModel(_modelConfiguration, _scene, disableAutoLoad) {
  105072. if (disableAutoLoad === void 0) { disableAutoLoad = false; }
  105073. this._modelConfiguration = _modelConfiguration;
  105074. this._scene = _scene;
  105075. this.onLoadedObservable = new babylonjs_1.Observable();
  105076. this.onLoadErrorObservable = new babylonjs_1.Observable();
  105077. this.onLoadProgressObservable = new babylonjs_1.Observable();
  105078. this._animations = [];
  105079. if (!disableAutoLoad) {
  105080. this._initLoad();
  105081. }
  105082. }
  105083. ViewerModel.prototype.load = function () {
  105084. if (this.loader) {
  105085. babylonjs_1.Tools.Error("Model was already loaded or in the process of loading.");
  105086. }
  105087. else {
  105088. this._initLoad();
  105089. }
  105090. };
  105091. ViewerModel.prototype.getAnimationNames = function () {
  105092. return this._animations.map(function (a) { return a.name; });
  105093. };
  105094. ViewerModel.prototype._getAnimationByName = function (name) {
  105095. var filtered = this._animations.filter(function (a) { return a.name === name; });
  105096. if (filtered.length === 1) {
  105097. return filtered[0];
  105098. }
  105099. else {
  105100. return null;
  105101. }
  105102. };
  105103. ViewerModel.prototype.playAnimation = function (name) {
  105104. var animation = this._getAnimationByName(name);
  105105. if (animation) {
  105106. if (this.currentAnimation) {
  105107. this.currentAnimation.stop();
  105108. }
  105109. this.currentAnimation = animation;
  105110. animation.start();
  105111. return animation;
  105112. }
  105113. else {
  105114. throw new Error("animation not found - " + name);
  105115. }
  105116. };
  105117. ViewerModel.prototype._initLoad = function () {
  105118. var _this = this;
  105119. if (!this._modelConfiguration || !this._modelConfiguration.url) {
  105120. return babylonjs_1.Tools.Error("No model URL to load.");
  105121. }
  105122. var parts = this._modelConfiguration.url.split('/');
  105123. var filename = parts.pop() || this._modelConfiguration.url;
  105124. var base = parts.length ? parts.join('/') + '/' : './';
  105125. var plugin = this._modelConfiguration.loader;
  105126. var animationsArray = this._scene.animationGroups.slice();
  105127. this.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._scene, function (meshes, particleSystems, skeletons) {
  105128. meshes.forEach(function (mesh) {
  105129. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  105130. });
  105131. _this.meshes = meshes;
  105132. _this.particleSystems = particleSystems;
  105133. _this.skeletons = skeletons;
  105134. if (_this.loader.name === 'gltf') {
  105135. _this._scene.animationGroups.forEach(function (ag) {
  105136. if (animationsArray.indexOf(ag) === -1) {
  105137. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  105138. }
  105139. });
  105140. }
  105141. else {
  105142. skeletons.forEach(function (skeleton, idx) {
  105143. var ag = new BABYLON.AnimationGroup("animation-" + idx, _this._scene);
  105144. skeleton.getAnimatables().forEach(function (a) {
  105145. if (a.animations[0]) {
  105146. ag.addTargetedAnimation(a.animations[0], a);
  105147. }
  105148. });
  105149. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  105150. });
  105151. }
  105152. if (_this._modelConfiguration.animation) {
  105153. if (_this._modelConfiguration.animation.playOnce) {
  105154. _this._animations.forEach(function (a) {
  105155. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  105156. });
  105157. }
  105158. if (_this._modelConfiguration.animation.autoStart && _this._animations.length) {
  105159. var animationName = _this._modelConfiguration.animation.autoStart === true ?
  105160. _this._animations[0].name : _this._modelConfiguration.animation.autoStart;
  105161. _this.playAnimation(animationName);
  105162. }
  105163. }
  105164. _this.onLoadedObservable.notifyObserversWithPromise(_this);
  105165. }, function (progressEvent) {
  105166. _this.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  105167. }, function (e, m, exception) {
  105168. _this.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  105169. }, plugin);
  105170. this.loader['animationStartMode'] = 0;
  105171. };
  105172. ViewerModel.prototype.dispose = function () {
  105173. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  105174. this.skeletons.forEach(function (s) { return s.dispose(); });
  105175. this._animations.forEach(function (ag) { return ag.dispose(); });
  105176. this.meshes.forEach(function (m) { return m.dispose(); });
  105177. };
  105178. return ViewerModel;
  105179. }());
  105180. exports.ViewerModel = ViewerModel;
  105181. /***/ }),
  105182. /* 31 */
  105183. /***/ (function(module, exports, __webpack_require__) {
  105184. "use strict";
  105185. Object.defineProperty(exports, "__esModule", { value: true });
  105186. var AnimationPlayMode;
  105187. (function (AnimationPlayMode) {
  105188. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  105189. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  105190. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  105191. var AnimationState;
  105192. (function (AnimationState) {
  105193. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  105194. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  105195. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  105196. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  105197. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  105198. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  105199. var GroupModelAnimation = (function () {
  105200. function GroupModelAnimation(_animationGroup) {
  105201. var _this = this;
  105202. this._animationGroup = _animationGroup;
  105203. this._state = AnimationState.INIT;
  105204. this._playMode = AnimationPlayMode.LOOP;
  105205. this._animationGroup.onAnimationEndObservable.add(function () {
  105206. _this.stop();
  105207. _this._state = AnimationState.ENDED;
  105208. });
  105209. }
  105210. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  105211. get: function () {
  105212. return this._animationGroup.name;
  105213. },
  105214. enumerable: true,
  105215. configurable: true
  105216. });
  105217. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  105218. get: function () {
  105219. return this._state;
  105220. },
  105221. enumerable: true,
  105222. configurable: true
  105223. });
  105224. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  105225. get: function () {
  105226. return this._animationGroup.speedRatio;
  105227. },
  105228. set: function (value) {
  105229. this._animationGroup.speedRatio = value;
  105230. },
  105231. enumerable: true,
  105232. configurable: true
  105233. });
  105234. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  105235. get: function () {
  105236. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  105237. var keys = ta.animation.getKeys();
  105238. return keys[keys.length - 1].frame;
  105239. });
  105240. return Math.max.apply(null, animationFrames);
  105241. },
  105242. enumerable: true,
  105243. configurable: true
  105244. });
  105245. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  105246. get: function () {
  105247. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  105248. var animatable = this._animationGroup.animatables[i];
  105249. var animations = animatable.getAnimations();
  105250. if (!animations || !animations.length) {
  105251. continue;
  105252. }
  105253. for (var idx = 0; idx < animations.length; ++idx) {
  105254. if (animations[idx].currentFrame) {
  105255. return animations[idx].currentFrame;
  105256. }
  105257. }
  105258. }
  105259. return 0;
  105260. },
  105261. enumerable: true,
  105262. configurable: true
  105263. });
  105264. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  105265. get: function () {
  105266. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  105267. var animatable = this._animationGroup.animatables[i];
  105268. var animations = animatable.getAnimations();
  105269. if (!animations || !animations.length) {
  105270. continue;
  105271. }
  105272. for (var idx = 0; idx < animations.length; ++idx) {
  105273. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  105274. return animations[idx].animation.framePerSecond;
  105275. }
  105276. }
  105277. }
  105278. return 0;
  105279. },
  105280. enumerable: true,
  105281. configurable: true
  105282. });
  105283. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  105284. get: function () {
  105285. return this._playMode;
  105286. },
  105287. set: function (value) {
  105288. if (value === this._playMode) {
  105289. return;
  105290. }
  105291. this._playMode = value;
  105292. if (this.state === AnimationState.PLAYING) {
  105293. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  105294. }
  105295. else {
  105296. this._animationGroup.reset();
  105297. this._state = AnimationState.INIT;
  105298. }
  105299. },
  105300. enumerable: true,
  105301. configurable: true
  105302. });
  105303. GroupModelAnimation.prototype.reset = function () {
  105304. this._animationGroup.reset();
  105305. };
  105306. GroupModelAnimation.prototype.restart = function () {
  105307. this._animationGroup.restart();
  105308. };
  105309. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  105310. this._animationGroup['_animatables'].forEach(function (a) {
  105311. a.goToFrame(frameNumber);
  105312. });
  105313. };
  105314. GroupModelAnimation.prototype.start = function () {
  105315. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  105316. if (this._animationGroup.isStarted) {
  105317. this._state = AnimationState.PLAYING;
  105318. }
  105319. };
  105320. GroupModelAnimation.prototype.pause = function () {
  105321. this._animationGroup.pause();
  105322. this._state = AnimationState.PAUSED;
  105323. };
  105324. GroupModelAnimation.prototype.stop = function () {
  105325. this._animationGroup.stop();
  105326. if (!this._animationGroup.isStarted) {
  105327. this._state = AnimationState.STOPPED;
  105328. }
  105329. };
  105330. GroupModelAnimation.prototype.dispose = function () {
  105331. this._animationGroup.dispose();
  105332. };
  105333. return GroupModelAnimation;
  105334. }());
  105335. exports.GroupModelAnimation = GroupModelAnimation;
  105336. /***/ }),
  105337. /* 32 */
  105338. /***/ (function(module, exports, __webpack_require__) {
  105339. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  105340. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  105341. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  105342. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  105343. return c > 3 && r && Object.defineProperty(target, key, r), r;
  105344. };
  105345. var __extends = (this && this.__extends) || (function () {
  105346. var extendStatics = Object.setPrototypeOf ||
  105347. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  105348. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  105349. return function (d, b) {
  105350. extendStatics(d, b);
  105351. function __() { this.constructor = d; }
  105352. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  105353. };
  105354. })();
  105355. (function universalModuleDefinition(root, factory) {
  105356. if(true)
  105357. module.exports = factory(__webpack_require__(0));
  105358. else if(typeof define === 'function' && define.amd)
  105359. define("babylonjs-loaders", ["babylonjs"], factory);
  105360. else if(typeof exports === 'object')
  105361. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  105362. else {
  105363. root["BABYLON"] = factory(root["BABYLON"]);
  105364. }
  105365. })(this, function(BABYLON) {
  105366. var BABYLON;
  105367. (function (BABYLON) {
  105368. var STLFileLoader = /** @class */ (function () {
  105369. function STLFileLoader() {
  105370. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  105371. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  105372. this.normalPattern = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  105373. this.vertexPattern = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  105374. this.name = "stl";
  105375. // force data to come in as an ArrayBuffer
  105376. // we'll convert to string if it looks like it's an ASCII .stl
  105377. this.extensions = {
  105378. ".stl": { isBinary: true },
  105379. };
  105380. }
  105381. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105382. var matches;
  105383. if (this.isBinary(data)) {
  105384. // binary .stl
  105385. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  105386. this.parseBinary(babylonMesh, data);
  105387. if (meshes) {
  105388. meshes.push(babylonMesh);
  105389. }
  105390. return true;
  105391. }
  105392. // ASCII .stl
  105393. // convert to string
  105394. var array_buffer = new Uint8Array(data);
  105395. var str = '';
  105396. for (var i = 0; i < data.byteLength; i++) {
  105397. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  105398. }
  105399. data = str;
  105400. while (matches = this.solidPattern.exec(data)) {
  105401. var meshName = matches[1];
  105402. var meshNameFromEnd = matches[3];
  105403. if (meshName != meshNameFromEnd) {
  105404. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  105405. return false;
  105406. }
  105407. // check meshesNames
  105408. if (meshesNames && meshName) {
  105409. if (meshesNames instanceof Array) {
  105410. if (!meshesNames.indexOf(meshName)) {
  105411. continue;
  105412. }
  105413. }
  105414. else {
  105415. if (meshName !== meshesNames) {
  105416. continue;
  105417. }
  105418. }
  105419. }
  105420. // stl mesh name can be empty as well
  105421. meshName = meshName || "stlmesh";
  105422. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  105423. this.parseASCII(babylonMesh, matches[2]);
  105424. if (meshes) {
  105425. meshes.push(babylonMesh);
  105426. }
  105427. }
  105428. return true;
  105429. };
  105430. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  105431. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  105432. if (result) {
  105433. scene.createDefaultCameraOrLight();
  105434. }
  105435. return result;
  105436. };
  105437. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105438. var container = new BABYLON.AssetContainer(scene);
  105439. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105440. container.removeAllFromScene();
  105441. return container;
  105442. };
  105443. STLFileLoader.prototype.isBinary = function (data) {
  105444. // check if file size is correct for binary stl
  105445. var faceSize, nFaces, reader;
  105446. reader = new DataView(data);
  105447. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  105448. nFaces = reader.getUint32(80, true);
  105449. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  105450. return true;
  105451. }
  105452. // check characters higher than ASCII to confirm binary
  105453. var fileLength = reader.byteLength;
  105454. for (var index = 0; index < fileLength; index++) {
  105455. if (reader.getUint8(index) > 127) {
  105456. return true;
  105457. }
  105458. }
  105459. return false;
  105460. };
  105461. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  105462. var reader = new DataView(data);
  105463. var faces = reader.getUint32(80, true);
  105464. var dataOffset = 84;
  105465. var faceLength = 12 * 4 + 2;
  105466. var offset = 0;
  105467. var positions = new Float32Array(faces * 3 * 3);
  105468. var normals = new Float32Array(faces * 3 * 3);
  105469. var indices = new Uint32Array(faces * 3);
  105470. var indicesCount = 0;
  105471. for (var face = 0; face < faces; face++) {
  105472. var start = dataOffset + face * faceLength;
  105473. var normalX = reader.getFloat32(start, true);
  105474. var normalY = reader.getFloat32(start + 4, true);
  105475. var normalZ = reader.getFloat32(start + 8, true);
  105476. for (var i = 1; i <= 3; i++) {
  105477. var vertexstart = start + i * 12;
  105478. // ordering is intentional to match ascii import
  105479. positions[offset] = reader.getFloat32(vertexstart, true);
  105480. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  105481. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  105482. normals[offset] = normalX;
  105483. normals[offset + 2] = normalY;
  105484. normals[offset + 1] = normalZ;
  105485. offset += 3;
  105486. }
  105487. indices[indicesCount] = indicesCount++;
  105488. indices[indicesCount] = indicesCount++;
  105489. indices[indicesCount] = indicesCount++;
  105490. }
  105491. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105492. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105493. mesh.setIndices(indices);
  105494. mesh.computeWorldMatrix(true);
  105495. };
  105496. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  105497. var positions = [];
  105498. var normals = [];
  105499. var indices = [];
  105500. var indicesCount = 0;
  105501. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  105502. var matches;
  105503. while (matches = this.facetsPattern.exec(solidData)) {
  105504. var facet = matches[1];
  105505. //one normal per face
  105506. var normalMatches = this.normalPattern.exec(facet);
  105507. this.normalPattern.lastIndex = 0;
  105508. if (!normalMatches) {
  105509. continue;
  105510. }
  105511. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  105512. var vertexMatch;
  105513. while (vertexMatch = this.vertexPattern.exec(facet)) {
  105514. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  105515. normals.push(normal[0], normal[1], normal[2]);
  105516. }
  105517. indices.push(indicesCount++, indicesCount++, indicesCount++);
  105518. this.vertexPattern.lastIndex = 0;
  105519. }
  105520. this.facetsPattern.lastIndex = 0;
  105521. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105522. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105523. mesh.setIndices(indices);
  105524. mesh.computeWorldMatrix(true);
  105525. };
  105526. return STLFileLoader;
  105527. }());
  105528. BABYLON.STLFileLoader = STLFileLoader;
  105529. if (BABYLON.SceneLoader) {
  105530. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  105531. }
  105532. })(BABYLON || (BABYLON = {}));
  105533. //# sourceMappingURL=babylon.stlFileLoader.js.map
  105534. var BABYLON;
  105535. (function (BABYLON) {
  105536. /**
  105537. * Class reading and parsing the MTL file bundled with the obj file.
  105538. */
  105539. var MTLFileLoader = /** @class */ (function () {
  105540. function MTLFileLoader() {
  105541. // All material loaded from the mtl will be set here
  105542. this.materials = [];
  105543. }
  105544. /**
  105545. * This function will read the mtl file and create each material described inside
  105546. * This function could be improve by adding :
  105547. * -some component missing (Ni, Tf...)
  105548. * -including the specific options available
  105549. *
  105550. * @param scene
  105551. * @param data
  105552. * @param rootUrl
  105553. */
  105554. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  105555. //Split the lines from the file
  105556. var lines = data.split('\n');
  105557. //Space char
  105558. var delimiter_pattern = /\s+/;
  105559. //Array with RGB colors
  105560. var color;
  105561. //New material
  105562. var material = null;
  105563. //Look at each line
  105564. for (var i = 0; i < lines.length; i++) {
  105565. var line = lines[i].trim();
  105566. // Blank line or comment
  105567. if (line.length === 0 || line.charAt(0) === '#') {
  105568. continue;
  105569. }
  105570. //Get the first parameter (keyword)
  105571. var pos = line.indexOf(' ');
  105572. var key = (pos >= 0) ? line.substring(0, pos) : line;
  105573. key = key.toLowerCase();
  105574. //Get the data following the key
  105575. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  105576. //This mtl keyword will create the new material
  105577. if (key === "newmtl") {
  105578. //Check if it is the first material.
  105579. // Materials specifications are described after this keyword.
  105580. if (material) {
  105581. //Add the previous material in the material array.
  105582. this.materials.push(material);
  105583. }
  105584. //Create a new material.
  105585. // value is the name of the material read in the mtl file
  105586. material = new BABYLON.StandardMaterial(value, scene);
  105587. }
  105588. else if (key === "kd" && material) {
  105589. // Diffuse color (color under white light) using RGB values
  105590. //value = "r g b"
  105591. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105592. //color = [r,g,b]
  105593. //Set tghe color into the material
  105594. material.diffuseColor = BABYLON.Color3.FromArray(color);
  105595. }
  105596. else if (key === "ka" && material) {
  105597. // Ambient color (color under shadow) using RGB values
  105598. //value = "r g b"
  105599. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105600. //color = [r,g,b]
  105601. //Set tghe color into the material
  105602. material.ambientColor = BABYLON.Color3.FromArray(color);
  105603. }
  105604. else if (key === "ks" && material) {
  105605. // Specular color (color when light is reflected from shiny surface) using RGB values
  105606. //value = "r g b"
  105607. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105608. //color = [r,g,b]
  105609. //Set the color into the material
  105610. material.specularColor = BABYLON.Color3.FromArray(color);
  105611. }
  105612. else if (key === "ke" && material) {
  105613. // Emissive color using RGB values
  105614. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105615. material.emissiveColor = BABYLON.Color3.FromArray(color);
  105616. }
  105617. else if (key === "ns" && material) {
  105618. //value = "Integer"
  105619. material.specularPower = parseFloat(value);
  105620. }
  105621. else if (key === "d" && material) {
  105622. //d is dissolve for current material. It mean alpha for BABYLON
  105623. material.alpha = parseFloat(value);
  105624. //Texture
  105625. //This part can be improved by adding the possible options of texture
  105626. }
  105627. else if (key === "map_ka" && material) {
  105628. // ambient texture map with a loaded image
  105629. //We must first get the folder of the image
  105630. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105631. }
  105632. else if (key === "map_kd" && material) {
  105633. // Diffuse texture map with a loaded image
  105634. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105635. }
  105636. else if (key === "map_ks" && material) {
  105637. // Specular texture map with a loaded image
  105638. //We must first get the folder of the image
  105639. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105640. }
  105641. else if (key === "map_ns") {
  105642. //Specular
  105643. //Specular highlight component
  105644. //We must first get the folder of the image
  105645. //
  105646. //Not supported by BABYLON
  105647. //
  105648. // continue;
  105649. }
  105650. else if (key === "map_bump" && material) {
  105651. //The bump texture
  105652. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105653. }
  105654. else if (key === "map_d" && material) {
  105655. // The dissolve of the material
  105656. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105657. //Options for illumination
  105658. }
  105659. else if (key === "illum") {
  105660. //Illumination
  105661. if (value === "0") {
  105662. //That mean Kd == Kd
  105663. }
  105664. else if (value === "1") {
  105665. //Color on and Ambient on
  105666. }
  105667. else if (value === "2") {
  105668. //Highlight on
  105669. }
  105670. else if (value === "3") {
  105671. //Reflection on and Ray trace on
  105672. }
  105673. else if (value === "4") {
  105674. //Transparency: Glass on, Reflection: Ray trace on
  105675. }
  105676. else if (value === "5") {
  105677. //Reflection: Fresnel on and Ray trace on
  105678. }
  105679. else if (value === "6") {
  105680. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  105681. }
  105682. else if (value === "7") {
  105683. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  105684. }
  105685. else if (value === "8") {
  105686. //Reflection on and Ray trace off
  105687. }
  105688. else if (value === "9") {
  105689. //Transparency: Glass on, Reflection: Ray trace off
  105690. }
  105691. else if (value === "10") {
  105692. //Casts shadows onto invisible surfaces
  105693. }
  105694. }
  105695. else {
  105696. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  105697. }
  105698. }
  105699. //At the end of the file, add the last material
  105700. if (material) {
  105701. this.materials.push(material);
  105702. }
  105703. };
  105704. /**
  105705. * Gets the texture for the material.
  105706. *
  105707. * If the material is imported from input file,
  105708. * We sanitize the url to ensure it takes the textre from aside the material.
  105709. *
  105710. * @param rootUrl The root url to load from
  105711. * @param value The value stored in the mtl
  105712. * @return The Texture
  105713. */
  105714. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  105715. if (!value) {
  105716. return null;
  105717. }
  105718. var url = rootUrl;
  105719. // Load from input file.
  105720. if (rootUrl === "file:") {
  105721. var lastDelimiter = value.lastIndexOf("\\");
  105722. if (lastDelimiter === -1) {
  105723. lastDelimiter = value.lastIndexOf("/");
  105724. }
  105725. if (lastDelimiter > -1) {
  105726. url += value.substr(lastDelimiter + 1);
  105727. }
  105728. else {
  105729. url += value;
  105730. }
  105731. }
  105732. else {
  105733. url += value;
  105734. }
  105735. return new BABYLON.Texture(url, scene);
  105736. };
  105737. return MTLFileLoader;
  105738. }());
  105739. BABYLON.MTLFileLoader = MTLFileLoader;
  105740. var OBJFileLoader = /** @class */ (function () {
  105741. function OBJFileLoader() {
  105742. this.name = "obj";
  105743. this.extensions = ".obj";
  105744. this.obj = /^o/;
  105745. this.group = /^g/;
  105746. this.mtllib = /^mtllib /;
  105747. this.usemtl = /^usemtl /;
  105748. this.smooth = /^s /;
  105749. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105750. // vn float float float
  105751. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105752. // vt float float
  105753. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105754. // f vertex vertex vertex ...
  105755. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  105756. // f vertex/uvs vertex/uvs vertex/uvs ...
  105757. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105758. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  105759. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105760. // f vertex//normal vertex//normal vertex//normal ...
  105761. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  105762. }
  105763. /**
  105764. * Calls synchronously the MTL file attached to this obj.
  105765. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  105766. * Without this function materials are not displayed in the first frame (but displayed after).
  105767. * In consequence it is impossible to get material information in your HTML file
  105768. *
  105769. * @param url The URL of the MTL file
  105770. * @param rootUrl
  105771. * @param onSuccess Callback function to be called when the MTL file is loaded
  105772. * @private
  105773. */
  105774. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  105775. //The complete path to the mtl file
  105776. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  105777. // Loads through the babylon tools to allow fileInput search.
  105778. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  105779. };
  105780. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105781. //get the meshes from OBJ file
  105782. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  105783. //Push meshes from OBJ file into the variable mesh of this function
  105784. if (meshes) {
  105785. loadedMeshes.forEach(function (mesh) {
  105786. meshes.push(mesh);
  105787. });
  105788. }
  105789. return true;
  105790. };
  105791. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  105792. //Get the 3D model
  105793. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  105794. };
  105795. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105796. var container = new BABYLON.AssetContainer(scene);
  105797. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105798. container.removeAllFromScene();
  105799. return container;
  105800. };
  105801. /**
  105802. * Read the OBJ file and create an Array of meshes.
  105803. * Each mesh contains all information given by the OBJ and the MTL file.
  105804. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  105805. *
  105806. * @param meshesNames
  105807. * @param scene BABYLON.Scene The scene where are displayed the data
  105808. * @param data String The content of the obj file
  105809. * @param rootUrl String The path to the folder
  105810. * @returns Array<AbstractMesh>
  105811. * @private
  105812. */
  105813. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  105814. var positions = []; //values for the positions of vertices
  105815. var normals = []; //Values for the normals
  105816. var uvs = []; //Values for the textures
  105817. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  105818. var handledMesh; //The current mesh of meshes array
  105819. var indicesForBabylon = []; //The list of indices for VertexData
  105820. var wrappedPositionForBabylon = []; //The list of position in vectors
  105821. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  105822. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  105823. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  105824. var curPositionInIndices = 0;
  105825. var hasMeshes = false; //Meshes are defined in the file
  105826. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  105827. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  105828. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  105829. var triangles = []; //Indices from new triangles coming from polygons
  105830. var materialNameFromObj = ""; //The name of the current material
  105831. var fileToLoad = ""; //The name of the mtlFile to load
  105832. var materialsFromMTLFile = new MTLFileLoader();
  105833. var objMeshName = ""; //The name of the current obj mesh
  105834. var increment = 1; //Id for meshes created by the multimaterial
  105835. var isFirstMaterial = true;
  105836. /**
  105837. * Search for obj in the given array.
  105838. * This function is called to check if a couple of data already exists in an array.
  105839. *
  105840. * If found, returns the index of the founded tuple index. Returns -1 if not found
  105841. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  105842. * @param obj Array<number>
  105843. * @returns {boolean}
  105844. */
  105845. var isInArray = function (arr, obj) {
  105846. if (!arr[obj[0]])
  105847. arr[obj[0]] = { normals: [], idx: [] };
  105848. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105849. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  105850. };
  105851. var isInArrayUV = function (arr, obj) {
  105852. if (!arr[obj[0]])
  105853. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  105854. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105855. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  105856. return arr[obj[0]].idx[idx];
  105857. }
  105858. return -1;
  105859. };
  105860. /**
  105861. * This function set the data for each triangle.
  105862. * Data are position, normals and uvs
  105863. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  105864. * If the tuple already exist, add only their indice
  105865. *
  105866. * @param indicePositionFromObj Integer The index in positions array
  105867. * @param indiceUvsFromObj Integer The index in uvs array
  105868. * @param indiceNormalFromObj Integer The index in normals array
  105869. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  105870. * @param textureVectorFromOBJ Vector3 The value of uvs
  105871. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  105872. */
  105873. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  105874. //Check if this tuple already exists in the list of tuples
  105875. var _index;
  105876. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  105877. _index = isInArrayUV(tuplePosNorm, [
  105878. indicePositionFromObj,
  105879. indiceNormalFromObj,
  105880. indiceUvsFromObj
  105881. ]);
  105882. }
  105883. else {
  105884. _index = isInArray(tuplePosNorm, [
  105885. indicePositionFromObj,
  105886. indiceNormalFromObj
  105887. ]);
  105888. }
  105889. //If it not exists
  105890. if (_index == -1) {
  105891. //Add an new indice.
  105892. //The array of indices is only an array with his length equal to the number of triangles - 1.
  105893. //We add vertices data in this order
  105894. indicesForBabylon.push(wrappedPositionForBabylon.length);
  105895. //Push the position of vertice for Babylon
  105896. //Each element is a BABYLON.Vector3(x,y,z)
  105897. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  105898. //Push the uvs for Babylon
  105899. //Each element is a BABYLON.Vector3(u,v)
  105900. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  105901. //Push the normals for Babylon
  105902. //Each element is a BABYLON.Vector3(x,y,z)
  105903. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  105904. //Add the tuple in the comparison list
  105905. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  105906. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  105907. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  105908. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  105909. }
  105910. else {
  105911. //The tuple already exists
  105912. //Add the index of the already existing tuple
  105913. //At this index we can get the value of position, normal and uvs of vertex
  105914. indicesForBabylon.push(_index);
  105915. }
  105916. };
  105917. /**
  105918. * Transform BABYLON.Vector() object onto 3 digits in an array
  105919. */
  105920. var unwrapData = function () {
  105921. //Every array has the same length
  105922. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  105923. //Push the x, y, z values of each element in the unwrapped array
  105924. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  105925. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  105926. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  105927. }
  105928. // Reset arrays for the next new meshes
  105929. wrappedPositionForBabylon = [];
  105930. wrappedNormalsForBabylon = [];
  105931. wrappedUvsForBabylon = [];
  105932. tuplePosNorm = [];
  105933. curPositionInIndices = 0;
  105934. };
  105935. /**
  105936. * Create triangles from polygons by recursion
  105937. * The best to understand how it works is to draw it in the same time you get the recursion.
  105938. * It is important to notice that a triangle is a polygon
  105939. * We get 4 patterns of face defined in OBJ File :
  105940. * facePattern1 = ["1","2","3","4","5","6"]
  105941. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  105942. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  105943. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  105944. * Each pattern is divided by the same method
  105945. * @param face Array[String] The indices of elements
  105946. * @param v Integer The variable to increment
  105947. */
  105948. var getTriangles = function (face, v) {
  105949. //Work for each element of the array
  105950. if (v + 1 < face.length) {
  105951. //Add on the triangle variable the indexes to obtain triangles
  105952. triangles.push(face[0], face[v], face[v + 1]);
  105953. //Incrementation for recursion
  105954. v += 1;
  105955. //Recursion
  105956. getTriangles(face, v);
  105957. }
  105958. //Result obtained after 2 iterations:
  105959. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  105960. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  105961. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  105962. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  105963. };
  105964. /**
  105965. * Create triangles and push the data for each polygon for the pattern 1
  105966. * In this pattern we get vertice positions
  105967. * @param face
  105968. * @param v
  105969. */
  105970. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  105971. //Get the indices of triangles for each polygon
  105972. getTriangles(face, v);
  105973. //For each element in the triangles array.
  105974. //This var could contains 1 to an infinity of triangles
  105975. for (var k = 0; k < triangles.length; k++) {
  105976. // Set position indice
  105977. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  105978. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  105979. positions[indicePositionFromObj], //Get the vectors data
  105980. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  105981. );
  105982. }
  105983. //Reset variable for the next line
  105984. triangles = [];
  105985. };
  105986. /**
  105987. * Create triangles and push the data for each polygon for the pattern 2
  105988. * In this pattern we get vertice positions and uvsu
  105989. * @param face
  105990. * @param v
  105991. */
  105992. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  105993. //Get the indices of triangles for each polygon
  105994. getTriangles(face, v);
  105995. for (var k = 0; k < triangles.length; k++) {
  105996. //triangle[k] = "1/1"
  105997. //Split the data for getting position and uv
  105998. var point = triangles[k].split("/"); // ["1", "1"]
  105999. //Set position indice
  106000. var indicePositionFromObj = parseInt(point[0]) - 1;
  106001. //Set uv indice
  106002. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106003. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  106004. positions[indicePositionFromObj], //Get the values for each element
  106005. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  106006. );
  106007. }
  106008. //Reset variable for the next line
  106009. triangles = [];
  106010. };
  106011. /**
  106012. * Create triangles and push the data for each polygon for the pattern 3
  106013. * In this pattern we get vertice positions, uvs and normals
  106014. * @param face
  106015. * @param v
  106016. */
  106017. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  106018. //Get the indices of triangles for each polygon
  106019. getTriangles(face, v);
  106020. for (var k = 0; k < triangles.length; k++) {
  106021. //triangle[k] = "1/1/1"
  106022. //Split the data for getting position, uv, and normals
  106023. var point = triangles[k].split("/"); // ["1", "1", "1"]
  106024. // Set position indice
  106025. var indicePositionFromObj = parseInt(point[0]) - 1;
  106026. // Set uv indice
  106027. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106028. // Set normal indice
  106029. var indiceNormalFromObj = parseInt(point[2]) - 1;
  106030. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  106031. );
  106032. }
  106033. //Reset variable for the next line
  106034. triangles = [];
  106035. };
  106036. /**
  106037. * Create triangles and push the data for each polygon for the pattern 4
  106038. * In this pattern we get vertice positions and normals
  106039. * @param face
  106040. * @param v
  106041. */
  106042. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  106043. getTriangles(face, v);
  106044. for (var k = 0; k < triangles.length; k++) {
  106045. //triangle[k] = "1//1"
  106046. //Split the data for getting position and normals
  106047. var point = triangles[k].split("//"); // ["1", "1"]
  106048. // We check indices, and normals
  106049. var indicePositionFromObj = parseInt(point[0]) - 1;
  106050. var indiceNormalFromObj = parseInt(point[1]) - 1;
  106051. setData(indicePositionFromObj, 1, //Default value for uv
  106052. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  106053. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  106054. }
  106055. //Reset variable for the next line
  106056. triangles = [];
  106057. };
  106058. var addPreviousObjMesh = function () {
  106059. //Check if it is not the first mesh. Otherwise we don't have data.
  106060. if (meshesFromObj.length > 0) {
  106061. //Get the previous mesh for applying the data about the faces
  106062. //=> in obj file, faces definition append after the name of the mesh
  106063. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  106064. //Set the data into Array for the mesh
  106065. unwrapData();
  106066. // Reverse tab. Otherwise face are displayed in the wrong sens
  106067. indicesForBabylon.reverse();
  106068. //Set the information for the mesh
  106069. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  106070. handledMesh.indices = indicesForBabylon.slice();
  106071. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  106072. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  106073. handledMesh.uvs = unwrappedUVForBabylon.slice();
  106074. //Reset the array for the next mesh
  106075. indicesForBabylon = [];
  106076. unwrappedPositionsForBabylon = [];
  106077. unwrappedNormalsForBabylon = [];
  106078. unwrappedUVForBabylon = [];
  106079. }
  106080. };
  106081. //Main function
  106082. //Split the file into lines
  106083. var lines = data.split('\n');
  106084. //Look at each line
  106085. for (var i = 0; i < lines.length; i++) {
  106086. var line = lines[i].trim();
  106087. var result;
  106088. //Comment or newLine
  106089. if (line.length === 0 || line.charAt(0) === '#') {
  106090. continue;
  106091. //Get information about one position possible for the vertices
  106092. }
  106093. else if ((result = this.vertexPattern.exec(line)) !== null) {
  106094. //Create a Vector3 with the position x, y, z
  106095. //Value of result:
  106096. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106097. //Add the Vector in the list of positions
  106098. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106099. }
  106100. else if ((result = this.normalPattern.exec(line)) !== null) {
  106101. //Create a Vector3 with the normals x, y, z
  106102. //Value of result
  106103. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106104. //Add the Vector in the list of normals
  106105. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106106. }
  106107. else if ((result = this.uvPattern.exec(line)) !== null) {
  106108. //Create a Vector2 with the normals u, v
  106109. //Value of result
  106110. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  106111. //Add the Vector in the list of uvs
  106112. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  106113. //Identify patterns of faces
  106114. //Face could be defined in different type of pattern
  106115. }
  106116. else if ((result = this.facePattern3.exec(line)) !== null) {
  106117. //Value of result:
  106118. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  106119. //Set the data for this face
  106120. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  106121. 1);
  106122. }
  106123. else if ((result = this.facePattern4.exec(line)) !== null) {
  106124. //Value of result:
  106125. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  106126. //Set the data for this face
  106127. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  106128. 1);
  106129. }
  106130. else if ((result = this.facePattern2.exec(line)) !== null) {
  106131. //Value of result:
  106132. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  106133. //Set the data for this face
  106134. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  106135. 1);
  106136. }
  106137. else if ((result = this.facePattern1.exec(line)) !== null) {
  106138. //Value of result
  106139. //["f 1 2 3", "1 2 3"...]
  106140. //Set the data for this face
  106141. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  106142. 1);
  106143. //Define a mesh or an object
  106144. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  106145. }
  106146. else if (this.group.test(line) || this.obj.test(line)) {
  106147. //Create a new mesh corresponding to the name of the group.
  106148. //Definition of the mesh
  106149. var objMesh =
  106150. //Set the name of the current obj mesh
  106151. {
  106152. name: line.substring(2).trim(),
  106153. indices: undefined,
  106154. positions: undefined,
  106155. normals: undefined,
  106156. uvs: undefined,
  106157. materialName: ""
  106158. };
  106159. addPreviousObjMesh();
  106160. //Push the last mesh created with only the name
  106161. meshesFromObj.push(objMesh);
  106162. //Set this variable to indicate that now meshesFromObj has objects defined inside
  106163. hasMeshes = true;
  106164. isFirstMaterial = true;
  106165. increment = 1;
  106166. //Keyword for applying a material
  106167. }
  106168. else if (this.usemtl.test(line)) {
  106169. //Get the name of the material
  106170. materialNameFromObj = line.substring(7).trim();
  106171. //If this new material is in the same mesh
  106172. if (!isFirstMaterial) {
  106173. //Set the data for the previous mesh
  106174. addPreviousObjMesh();
  106175. //Create a new mesh
  106176. var objMesh =
  106177. //Set the name of the current obj mesh
  106178. {
  106179. name: objMeshName + "_mm" + increment.toString(),
  106180. indices: undefined,
  106181. positions: undefined,
  106182. normals: undefined,
  106183. uvs: undefined,
  106184. materialName: materialNameFromObj
  106185. };
  106186. increment++;
  106187. //If meshes are already defined
  106188. meshesFromObj.push(objMesh);
  106189. }
  106190. //Set the material name if the previous line define a mesh
  106191. if (hasMeshes && isFirstMaterial) {
  106192. //Set the material name to the previous mesh (1 material per mesh)
  106193. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  106194. isFirstMaterial = false;
  106195. }
  106196. //Keyword for loading the mtl file
  106197. }
  106198. else if (this.mtllib.test(line)) {
  106199. //Get the name of mtl file
  106200. fileToLoad = line.substring(7).trim();
  106201. //Apply smoothing
  106202. }
  106203. else if (this.smooth.test(line)) {
  106204. // smooth shading => apply smoothing
  106205. //Toda y I don't know it work with babylon and with obj.
  106206. //With the obj file an integer is set
  106207. }
  106208. else {
  106209. //If there is another possibility
  106210. console.log("Unhandled expression at line : " + line);
  106211. }
  106212. }
  106213. //At the end of the file, add the last mesh into the meshesFromObj array
  106214. if (hasMeshes) {
  106215. //Set the data for the last mesh
  106216. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  106217. //Reverse indices for displaying faces in the good sens
  106218. indicesForBabylon.reverse();
  106219. //Get the good array
  106220. unwrapData();
  106221. //Set array
  106222. handledMesh.indices = indicesForBabylon;
  106223. handledMesh.positions = unwrappedPositionsForBabylon;
  106224. handledMesh.normals = unwrappedNormalsForBabylon;
  106225. handledMesh.uvs = unwrappedUVForBabylon;
  106226. }
  106227. //If any o or g keyword found, create a mesj with a random id
  106228. if (!hasMeshes) {
  106229. // reverse tab of indices
  106230. indicesForBabylon.reverse();
  106231. //Get positions normals uvs
  106232. unwrapData();
  106233. //Set data for one mesh
  106234. meshesFromObj.push({
  106235. name: BABYLON.Geometry.RandomId(),
  106236. indices: indicesForBabylon,
  106237. positions: unwrappedPositionsForBabylon,
  106238. normals: unwrappedNormalsForBabylon,
  106239. uvs: unwrappedUVForBabylon,
  106240. materialName: materialNameFromObj
  106241. });
  106242. }
  106243. //Create a BABYLON.Mesh list
  106244. var babylonMeshesArray = []; //The mesh for babylon
  106245. var materialToUse = new Array();
  106246. //Set data for each mesh
  106247. for (var j = 0; j < meshesFromObj.length; j++) {
  106248. //check meshesNames (stlFileLoader)
  106249. if (meshesNames && meshesFromObj[j].name) {
  106250. if (meshesNames instanceof Array) {
  106251. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  106252. continue;
  106253. }
  106254. }
  106255. else {
  106256. if (meshesFromObj[j].name !== meshesNames) {
  106257. continue;
  106258. }
  106259. }
  106260. }
  106261. //Get the current mesh
  106262. //Set the data with VertexBuffer for each mesh
  106263. handledMesh = meshesFromObj[j];
  106264. //Create a BABYLON.Mesh with the name of the obj mesh
  106265. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  106266. //Push the name of the material to an array
  106267. //This is indispensable for the importMesh function
  106268. materialToUse.push(meshesFromObj[j].materialName);
  106269. var vertexData = new BABYLON.VertexData(); //The container for the values
  106270. //Set the data for the babylonMesh
  106271. vertexData.positions = handledMesh.positions;
  106272. vertexData.normals = handledMesh.normals;
  106273. vertexData.uvs = handledMesh.uvs;
  106274. vertexData.indices = handledMesh.indices;
  106275. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  106276. vertexData.applyToMesh(babylonMesh);
  106277. //Push the mesh into an array
  106278. babylonMeshesArray.push(babylonMesh);
  106279. }
  106280. //load the materials
  106281. //Check if we have a file to load
  106282. if (fileToLoad !== "") {
  106283. //Load the file synchronously
  106284. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  106285. //Create materials thanks MTLLoader function
  106286. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  106287. //Look at each material loaded in the mtl file
  106288. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  106289. //Three variables to get all meshes with the same material
  106290. var startIndex = 0;
  106291. var _indices = [];
  106292. var _index;
  106293. //The material from MTL file is used in the meshes loaded
  106294. //Push the indice in an array
  106295. //Check if the material is not used for another mesh
  106296. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  106297. _indices.push(_index);
  106298. startIndex = _index + 1;
  106299. }
  106300. //If the material is not used dispose it
  106301. if (_index == -1 && _indices.length == 0) {
  106302. //If the material is not needed, remove it
  106303. materialsFromMTLFile.materials[n].dispose();
  106304. }
  106305. else {
  106306. for (var o = 0; o < _indices.length; o++) {
  106307. //Apply the material to the BABYLON.Mesh for each mesh with the material
  106308. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  106309. }
  106310. }
  106311. }
  106312. });
  106313. }
  106314. //Return an array with all BABYLON.Mesh
  106315. return babylonMeshesArray;
  106316. };
  106317. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  106318. return OBJFileLoader;
  106319. }());
  106320. BABYLON.OBJFileLoader = OBJFileLoader;
  106321. if (BABYLON.SceneLoader) {
  106322. //Add this loader into the register plugin
  106323. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  106324. }
  106325. })(BABYLON || (BABYLON = {}));
  106326. //# sourceMappingURL=babylon.objFileLoader.js.map
  106327. var BABYLON;
  106328. (function (BABYLON) {
  106329. var GLTFLoaderCoordinateSystemMode;
  106330. (function (GLTFLoaderCoordinateSystemMode) {
  106331. /**
  106332. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  106333. */
  106334. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  106335. /**
  106336. * Sets the useRightHandedSystem flag on the scene.
  106337. */
  106338. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  106339. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  106340. var GLTFLoaderAnimationStartMode;
  106341. (function (GLTFLoaderAnimationStartMode) {
  106342. /**
  106343. * No animation will start.
  106344. */
  106345. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  106346. /**
  106347. * The first animation will start.
  106348. */
  106349. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  106350. /**
  106351. * All animations will start.
  106352. */
  106353. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  106354. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  106355. var GLTFLoaderState;
  106356. (function (GLTFLoaderState) {
  106357. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  106358. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  106359. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  106360. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  106361. var GLTFFileLoader = /** @class */ (function () {
  106362. function GLTFFileLoader() {
  106363. // #region Common options
  106364. /**
  106365. * Raised when the asset has been parsed.
  106366. * The data.json property stores the glTF JSON.
  106367. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  106368. */
  106369. this.onParsedObservable = new BABYLON.Observable();
  106370. // #endregion
  106371. // #region V2 options
  106372. /**
  106373. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  106374. */
  106375. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  106376. /**
  106377. * The animation start mode (NONE, FIRST, ALL).
  106378. */
  106379. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  106380. /**
  106381. * Set to true to compile materials before raising the success callback.
  106382. */
  106383. this.compileMaterials = false;
  106384. /**
  106385. * Set to true to also compile materials with clip planes.
  106386. */
  106387. this.useClipPlane = false;
  106388. /**
  106389. * Set to true to compile shadow generators before raising the success callback.
  106390. */
  106391. this.compileShadowGenerators = false;
  106392. /**
  106393. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  106394. */
  106395. this.onMeshLoadedObservable = new BABYLON.Observable();
  106396. /**
  106397. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  106398. */
  106399. this.onTextureLoadedObservable = new BABYLON.Observable();
  106400. /**
  106401. * Raised when the loader creates a material after parsing the glTF properties of the material.
  106402. */
  106403. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106404. /**
  106405. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  106406. */
  106407. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  106408. /**
  106409. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  106410. * For assets with LODs, raised when all of the LODs are complete.
  106411. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  106412. */
  106413. this.onCompleteObservable = new BABYLON.Observable();
  106414. /**
  106415. * Raised when the loader is disposed.
  106416. */
  106417. this.onDisposeObservable = new BABYLON.Observable();
  106418. /**
  106419. * Raised after a loader extension is created.
  106420. * Set additional options for a loader extension in this event.
  106421. */
  106422. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106423. // #endregion
  106424. this._loader = null;
  106425. this.name = "gltf";
  106426. this.extensions = {
  106427. ".gltf": { isBinary: false },
  106428. ".glb": { isBinary: true }
  106429. };
  106430. }
  106431. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  106432. set: function (callback) {
  106433. if (this._onParsedObserver) {
  106434. this.onParsedObservable.remove(this._onParsedObserver);
  106435. }
  106436. this._onParsedObserver = this.onParsedObservable.add(callback);
  106437. },
  106438. enumerable: true,
  106439. configurable: true
  106440. });
  106441. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  106442. set: function (callback) {
  106443. if (this._onMeshLoadedObserver) {
  106444. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  106445. }
  106446. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  106447. },
  106448. enumerable: true,
  106449. configurable: true
  106450. });
  106451. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  106452. set: function (callback) {
  106453. if (this._onTextureLoadedObserver) {
  106454. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  106455. }
  106456. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  106457. },
  106458. enumerable: true,
  106459. configurable: true
  106460. });
  106461. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  106462. set: function (callback) {
  106463. if (this._onMaterialLoadedObserver) {
  106464. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  106465. }
  106466. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  106467. },
  106468. enumerable: true,
  106469. configurable: true
  106470. });
  106471. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  106472. set: function (callback) {
  106473. if (this._onAnimationGroupLoadedObserver) {
  106474. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  106475. }
  106476. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  106477. },
  106478. enumerable: true,
  106479. configurable: true
  106480. });
  106481. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  106482. set: function (callback) {
  106483. if (this._onCompleteObserver) {
  106484. this.onCompleteObservable.remove(this._onCompleteObserver);
  106485. }
  106486. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  106487. },
  106488. enumerable: true,
  106489. configurable: true
  106490. });
  106491. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  106492. set: function (callback) {
  106493. if (this._onDisposeObserver) {
  106494. this.onDisposeObservable.remove(this._onDisposeObserver);
  106495. }
  106496. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  106497. },
  106498. enumerable: true,
  106499. configurable: true
  106500. });
  106501. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  106502. set: function (callback) {
  106503. if (this._onExtensionLoadedObserver) {
  106504. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  106505. }
  106506. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  106507. },
  106508. enumerable: true,
  106509. configurable: true
  106510. });
  106511. /**
  106512. * Gets a promise that resolves when the asset is completely loaded.
  106513. * @returns A promise that resolves when the asset is completely loaded.
  106514. */
  106515. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  106516. var _this = this;
  106517. return new Promise(function (resolve) {
  106518. _this.onCompleteObservable.add(function () {
  106519. resolve();
  106520. }, undefined, undefined, undefined, true);
  106521. });
  106522. };
  106523. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  106524. /**
  106525. * The loader state or null if not active.
  106526. */
  106527. get: function () {
  106528. return this._loader ? this._loader.state : null;
  106529. },
  106530. enumerable: true,
  106531. configurable: true
  106532. });
  106533. /**
  106534. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  106535. */
  106536. GLTFFileLoader.prototype.dispose = function () {
  106537. if (this._loader) {
  106538. this._loader.dispose();
  106539. this._loader = null;
  106540. }
  106541. this.onMeshLoadedObservable.clear();
  106542. this.onTextureLoadedObservable.clear();
  106543. this.onMaterialLoadedObservable.clear();
  106544. this.onDisposeObservable.notifyObservers(this);
  106545. this.onDisposeObservable.clear();
  106546. };
  106547. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106548. var _this = this;
  106549. return Promise.resolve().then(function () {
  106550. var loaderData = _this._parse(data);
  106551. _this._loader = _this._getLoader(loaderData);
  106552. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  106553. });
  106554. };
  106555. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106556. var _this = this;
  106557. return Promise.resolve().then(function () {
  106558. var loaderData = _this._parse(data);
  106559. _this._loader = _this._getLoader(loaderData);
  106560. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  106561. });
  106562. };
  106563. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  106564. var _this = this;
  106565. return Promise.resolve().then(function () {
  106566. var loaderData = _this._parse(data);
  106567. _this._loader = _this._getLoader(loaderData);
  106568. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  106569. var container = new BABYLON.AssetContainer(scene);
  106570. Array.prototype.push.apply(container.meshes, result.meshes);
  106571. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  106572. Array.prototype.push.apply(container.skeletons, result.skeletons);
  106573. container.removeAllFromScene();
  106574. return container;
  106575. });
  106576. });
  106577. };
  106578. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  106579. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  106580. };
  106581. GLTFFileLoader.prototype.createPlugin = function () {
  106582. return new GLTFFileLoader();
  106583. };
  106584. GLTFFileLoader.prototype._parse = function (data) {
  106585. var parsedData;
  106586. if (data instanceof ArrayBuffer) {
  106587. parsedData = GLTFFileLoader._parseBinary(data);
  106588. }
  106589. else {
  106590. parsedData = {
  106591. json: JSON.parse(data),
  106592. bin: null
  106593. };
  106594. }
  106595. this.onParsedObservable.notifyObservers(parsedData);
  106596. this.onParsedObservable.clear();
  106597. return parsedData;
  106598. };
  106599. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  106600. var _this = this;
  106601. var loaderVersion = { major: 2, minor: 0 };
  106602. var asset = loaderData.json.asset || {};
  106603. var version = GLTFFileLoader._parseVersion(asset.version);
  106604. if (!version) {
  106605. throw new Error("Invalid version: " + asset.version);
  106606. }
  106607. if (asset.minVersion !== undefined) {
  106608. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  106609. if (!minVersion) {
  106610. throw new Error("Invalid minimum version: " + asset.minVersion);
  106611. }
  106612. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  106613. throw new Error("Incompatible minimum version: " + asset.minVersion);
  106614. }
  106615. }
  106616. var createLoaders = {
  106617. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  106618. 2: GLTFFileLoader.CreateGLTFLoaderV2
  106619. };
  106620. var createLoader = createLoaders[version.major];
  106621. if (!createLoader) {
  106622. throw new Error("Unsupported version: " + asset.version);
  106623. }
  106624. var loader = createLoader();
  106625. loader.coordinateSystemMode = this.coordinateSystemMode;
  106626. loader.animationStartMode = this.animationStartMode;
  106627. loader.compileMaterials = this.compileMaterials;
  106628. loader.useClipPlane = this.useClipPlane;
  106629. loader.compileShadowGenerators = this.compileShadowGenerators;
  106630. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  106631. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  106632. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  106633. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  106634. loader.onCompleteObservable.add(function () {
  106635. _this.onMeshLoadedObservable.clear();
  106636. _this.onTextureLoadedObservable.clear();
  106637. _this.onMaterialLoadedObservable.clear();
  106638. _this.onCompleteObservable.notifyObservers(_this);
  106639. _this.onCompleteObservable.clear();
  106640. });
  106641. return loader;
  106642. };
  106643. GLTFFileLoader._parseBinary = function (data) {
  106644. var Binary = {
  106645. Magic: 0x46546C67
  106646. };
  106647. var binaryReader = new BinaryReader(data);
  106648. var magic = binaryReader.readUint32();
  106649. if (magic !== Binary.Magic) {
  106650. throw new Error("Unexpected magic: " + magic);
  106651. }
  106652. var version = binaryReader.readUint32();
  106653. switch (version) {
  106654. case 1: return GLTFFileLoader._parseV1(binaryReader);
  106655. case 2: return GLTFFileLoader._parseV2(binaryReader);
  106656. }
  106657. throw new Error("Unsupported version: " + version);
  106658. };
  106659. GLTFFileLoader._parseV1 = function (binaryReader) {
  106660. var ContentFormat = {
  106661. JSON: 0
  106662. };
  106663. var length = binaryReader.readUint32();
  106664. if (length != binaryReader.getLength()) {
  106665. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106666. }
  106667. var contentLength = binaryReader.readUint32();
  106668. var contentFormat = binaryReader.readUint32();
  106669. var content;
  106670. switch (contentFormat) {
  106671. case ContentFormat.JSON: {
  106672. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  106673. break;
  106674. }
  106675. default: {
  106676. throw new Error("Unexpected content format: " + contentFormat);
  106677. }
  106678. }
  106679. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  106680. var body = binaryReader.readUint8Array(bytesRemaining);
  106681. return {
  106682. json: content,
  106683. bin: body
  106684. };
  106685. };
  106686. GLTFFileLoader._parseV2 = function (binaryReader) {
  106687. var ChunkFormat = {
  106688. JSON: 0x4E4F534A,
  106689. BIN: 0x004E4942
  106690. };
  106691. var length = binaryReader.readUint32();
  106692. if (length !== binaryReader.getLength()) {
  106693. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106694. }
  106695. // JSON chunk
  106696. var chunkLength = binaryReader.readUint32();
  106697. var chunkFormat = binaryReader.readUint32();
  106698. if (chunkFormat !== ChunkFormat.JSON) {
  106699. throw new Error("First chunk format is not JSON");
  106700. }
  106701. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  106702. // Look for BIN chunk
  106703. var bin = null;
  106704. while (binaryReader.getPosition() < binaryReader.getLength()) {
  106705. var chunkLength_1 = binaryReader.readUint32();
  106706. var chunkFormat_1 = binaryReader.readUint32();
  106707. switch (chunkFormat_1) {
  106708. case ChunkFormat.JSON: {
  106709. throw new Error("Unexpected JSON chunk");
  106710. }
  106711. case ChunkFormat.BIN: {
  106712. bin = binaryReader.readUint8Array(chunkLength_1);
  106713. break;
  106714. }
  106715. default: {
  106716. // ignore unrecognized chunkFormat
  106717. binaryReader.skipBytes(chunkLength_1);
  106718. break;
  106719. }
  106720. }
  106721. }
  106722. return {
  106723. json: json,
  106724. bin: bin
  106725. };
  106726. };
  106727. GLTFFileLoader._parseVersion = function (version) {
  106728. if (version === "1.0" || version === "1.0.1") {
  106729. return {
  106730. major: 1,
  106731. minor: 0
  106732. };
  106733. }
  106734. var match = (version + "").match(/^(\d+)\.(\d+)/);
  106735. if (!match) {
  106736. return null;
  106737. }
  106738. return {
  106739. major: parseInt(match[1]),
  106740. minor: parseInt(match[2])
  106741. };
  106742. };
  106743. GLTFFileLoader._compareVersion = function (a, b) {
  106744. if (a.major > b.major)
  106745. return 1;
  106746. if (a.major < b.major)
  106747. return -1;
  106748. if (a.minor > b.minor)
  106749. return 1;
  106750. if (a.minor < b.minor)
  106751. return -1;
  106752. return 0;
  106753. };
  106754. GLTFFileLoader._decodeBufferToText = function (buffer) {
  106755. var result = "";
  106756. var length = buffer.byteLength;
  106757. for (var i = 0; i < length; i++) {
  106758. result += String.fromCharCode(buffer[i]);
  106759. }
  106760. return result;
  106761. };
  106762. // #endregion
  106763. // #region V1 options
  106764. GLTFFileLoader.IncrementalLoading = true;
  106765. GLTFFileLoader.HomogeneousCoordinates = false;
  106766. return GLTFFileLoader;
  106767. }());
  106768. BABYLON.GLTFFileLoader = GLTFFileLoader;
  106769. var BinaryReader = /** @class */ (function () {
  106770. function BinaryReader(arrayBuffer) {
  106771. this._arrayBuffer = arrayBuffer;
  106772. this._dataView = new DataView(arrayBuffer);
  106773. this._byteOffset = 0;
  106774. }
  106775. BinaryReader.prototype.getPosition = function () {
  106776. return this._byteOffset;
  106777. };
  106778. BinaryReader.prototype.getLength = function () {
  106779. return this._arrayBuffer.byteLength;
  106780. };
  106781. BinaryReader.prototype.readUint32 = function () {
  106782. var value = this._dataView.getUint32(this._byteOffset, true);
  106783. this._byteOffset += 4;
  106784. return value;
  106785. };
  106786. BinaryReader.prototype.readUint8Array = function (length) {
  106787. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  106788. this._byteOffset += length;
  106789. return value;
  106790. };
  106791. BinaryReader.prototype.skipBytes = function (length) {
  106792. this._byteOffset += length;
  106793. };
  106794. return BinaryReader;
  106795. }());
  106796. if (BABYLON.SceneLoader) {
  106797. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  106798. }
  106799. })(BABYLON || (BABYLON = {}));
  106800. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  106801. var BABYLON;
  106802. (function (BABYLON) {
  106803. var GLTF1;
  106804. (function (GLTF1) {
  106805. /**
  106806. * Enums
  106807. */
  106808. var EComponentType;
  106809. (function (EComponentType) {
  106810. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  106811. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106812. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  106813. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106814. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  106815. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  106816. var EShaderType;
  106817. (function (EShaderType) {
  106818. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  106819. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  106820. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  106821. var EParameterType;
  106822. (function (EParameterType) {
  106823. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  106824. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106825. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  106826. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106827. EParameterType[EParameterType["INT"] = 5124] = "INT";
  106828. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  106829. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  106830. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  106831. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  106832. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  106833. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  106834. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  106835. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  106836. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  106837. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  106838. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  106839. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  106840. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  106841. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  106842. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  106843. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  106844. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  106845. var ETextureWrapMode;
  106846. (function (ETextureWrapMode) {
  106847. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  106848. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  106849. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  106850. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  106851. var ETextureFilterType;
  106852. (function (ETextureFilterType) {
  106853. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  106854. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  106855. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  106856. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  106857. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  106858. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  106859. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  106860. var ETextureFormat;
  106861. (function (ETextureFormat) {
  106862. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  106863. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  106864. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  106865. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  106866. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  106867. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  106868. var ECullingType;
  106869. (function (ECullingType) {
  106870. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  106871. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  106872. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  106873. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  106874. var EBlendingFunction;
  106875. (function (EBlendingFunction) {
  106876. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  106877. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  106878. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  106879. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  106880. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  106881. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  106882. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  106883. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  106884. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  106885. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  106886. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  106887. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  106888. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  106889. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  106890. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  106891. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  106892. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106893. })(BABYLON || (BABYLON = {}));
  106894. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106895. var BABYLON;
  106896. (function (BABYLON) {
  106897. var GLTF1;
  106898. (function (GLTF1) {
  106899. /**
  106900. * Tokenizer. Used for shaders compatibility
  106901. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  106902. */
  106903. var ETokenType;
  106904. (function (ETokenType) {
  106905. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  106906. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  106907. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  106908. })(ETokenType || (ETokenType = {}));
  106909. var Tokenizer = /** @class */ (function () {
  106910. function Tokenizer(toParse) {
  106911. this._pos = 0;
  106912. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  106913. this._toParse = toParse;
  106914. this._maxPos = toParse.length;
  106915. }
  106916. Tokenizer.prototype.getNextToken = function () {
  106917. if (this.isEnd())
  106918. return ETokenType.END_OF_INPUT;
  106919. this.currentString = this.read();
  106920. this.currentToken = ETokenType.UNKNOWN;
  106921. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  106922. this.currentToken = ETokenType.IDENTIFIER;
  106923. this.currentIdentifier = this.currentString;
  106924. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  106925. this.currentIdentifier += this.currentString;
  106926. this.forward();
  106927. }
  106928. }
  106929. return this.currentToken;
  106930. };
  106931. Tokenizer.prototype.peek = function () {
  106932. return this._toParse[this._pos];
  106933. };
  106934. Tokenizer.prototype.read = function () {
  106935. return this._toParse[this._pos++];
  106936. };
  106937. Tokenizer.prototype.forward = function () {
  106938. this._pos++;
  106939. };
  106940. Tokenizer.prototype.isEnd = function () {
  106941. return this._pos >= this._maxPos;
  106942. };
  106943. return Tokenizer;
  106944. }());
  106945. /**
  106946. * Values
  106947. */
  106948. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  106949. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  106950. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  106951. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  106952. /**
  106953. * Parse
  106954. */
  106955. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  106956. for (var buf in parsedBuffers) {
  106957. var parsedBuffer = parsedBuffers[buf];
  106958. gltfRuntime.buffers[buf] = parsedBuffer;
  106959. gltfRuntime.buffersCount++;
  106960. }
  106961. };
  106962. var parseShaders = function (parsedShaders, gltfRuntime) {
  106963. for (var sha in parsedShaders) {
  106964. var parsedShader = parsedShaders[sha];
  106965. gltfRuntime.shaders[sha] = parsedShader;
  106966. gltfRuntime.shaderscount++;
  106967. }
  106968. };
  106969. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  106970. for (var object in parsedObjects) {
  106971. var parsedObject = parsedObjects[object];
  106972. gltfRuntime[runtimeProperty][object] = parsedObject;
  106973. }
  106974. };
  106975. /**
  106976. * Utils
  106977. */
  106978. var normalizeUVs = function (buffer) {
  106979. if (!buffer) {
  106980. return;
  106981. }
  106982. for (var i = 0; i < buffer.length / 2; i++) {
  106983. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  106984. }
  106985. };
  106986. var getAttribute = function (attributeParameter) {
  106987. if (attributeParameter.semantic === "NORMAL") {
  106988. return "normal";
  106989. }
  106990. else if (attributeParameter.semantic === "POSITION") {
  106991. return "position";
  106992. }
  106993. else if (attributeParameter.semantic === "JOINT") {
  106994. return "matricesIndices";
  106995. }
  106996. else if (attributeParameter.semantic === "WEIGHT") {
  106997. return "matricesWeights";
  106998. }
  106999. else if (attributeParameter.semantic === "COLOR") {
  107000. return "color";
  107001. }
  107002. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  107003. var channel = Number(attributeParameter.semantic.split("_")[1]);
  107004. return "uv" + (channel === 0 ? "" : channel + 1);
  107005. }
  107006. return null;
  107007. };
  107008. /**
  107009. * Loads and creates animations
  107010. */
  107011. var loadAnimations = function (gltfRuntime) {
  107012. for (var anim in gltfRuntime.animations) {
  107013. var animation = gltfRuntime.animations[anim];
  107014. if (!animation.channels || !animation.samplers) {
  107015. continue;
  107016. }
  107017. var lastAnimation = null;
  107018. for (var i = 0; i < animation.channels.length; i++) {
  107019. // Get parameters and load buffers
  107020. var channel = animation.channels[i];
  107021. var sampler = animation.samplers[channel.sampler];
  107022. if (!sampler) {
  107023. continue;
  107024. }
  107025. var inputData = null;
  107026. var outputData = null;
  107027. if (animation.parameters) {
  107028. inputData = animation.parameters[sampler.input];
  107029. outputData = animation.parameters[sampler.output];
  107030. }
  107031. else {
  107032. inputData = sampler.input;
  107033. outputData = sampler.output;
  107034. }
  107035. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  107036. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  107037. var targetID = channel.target.id;
  107038. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  107039. if (targetNode === null) {
  107040. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  107041. }
  107042. if (targetNode === null) {
  107043. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  107044. continue;
  107045. }
  107046. var isBone = targetNode instanceof BABYLON.Bone;
  107047. // Get target path (position, rotation or scaling)
  107048. var targetPath = channel.target.path;
  107049. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  107050. if (targetPathIndex !== -1) {
  107051. targetPath = babylonAnimationPaths[targetPathIndex];
  107052. }
  107053. // Determine animation type
  107054. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  107055. if (!isBone) {
  107056. if (targetPath === "rotationQuaternion") {
  107057. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  107058. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  107059. }
  107060. else {
  107061. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107062. }
  107063. }
  107064. // Create animation and key frames
  107065. var babylonAnimation = null;
  107066. var keys = [];
  107067. var arrayOffset = 0;
  107068. var modifyKey = false;
  107069. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  107070. babylonAnimation = lastAnimation;
  107071. modifyKey = true;
  107072. }
  107073. if (!modifyKey) {
  107074. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107075. }
  107076. // For each frame
  107077. for (var j = 0; j < bufferInput.length; j++) {
  107078. var value = null;
  107079. if (targetPath === "rotationQuaternion") {
  107080. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  107081. arrayOffset += 4;
  107082. }
  107083. else {
  107084. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  107085. arrayOffset += 3;
  107086. }
  107087. if (isBone) {
  107088. var bone = targetNode;
  107089. var translation = BABYLON.Vector3.Zero();
  107090. var rotationQuaternion = new BABYLON.Quaternion();
  107091. var scaling = BABYLON.Vector3.Zero();
  107092. // Warning on decompose
  107093. var mat = bone.getBaseMatrix();
  107094. if (modifyKey && lastAnimation) {
  107095. mat = lastAnimation.getKeys()[j].value;
  107096. }
  107097. mat.decompose(scaling, rotationQuaternion, translation);
  107098. if (targetPath === "position") {
  107099. translation = value;
  107100. }
  107101. else if (targetPath === "rotationQuaternion") {
  107102. rotationQuaternion = value;
  107103. }
  107104. else {
  107105. scaling = value;
  107106. }
  107107. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  107108. }
  107109. if (!modifyKey) {
  107110. keys.push({
  107111. frame: bufferInput[j],
  107112. value: value
  107113. });
  107114. }
  107115. else if (lastAnimation) {
  107116. lastAnimation.getKeys()[j].value = value;
  107117. }
  107118. }
  107119. // Finish
  107120. if (!modifyKey && babylonAnimation) {
  107121. babylonAnimation.setKeys(keys);
  107122. targetNode.animations.push(babylonAnimation);
  107123. }
  107124. lastAnimation = babylonAnimation;
  107125. gltfRuntime.scene.stopAnimation(targetNode);
  107126. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  107127. }
  107128. }
  107129. };
  107130. /**
  107131. * Returns the bones transformation matrix
  107132. */
  107133. var configureBoneTransformation = function (node) {
  107134. var mat = null;
  107135. if (node.translation || node.rotation || node.scale) {
  107136. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  107137. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  107138. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  107139. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  107140. }
  107141. else {
  107142. mat = BABYLON.Matrix.FromArray(node.matrix);
  107143. }
  107144. return mat;
  107145. };
  107146. /**
  107147. * Returns the parent bone
  107148. */
  107149. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  107150. // Try to find
  107151. for (var i = 0; i < newSkeleton.bones.length; i++) {
  107152. if (newSkeleton.bones[i].name === jointName) {
  107153. return newSkeleton.bones[i];
  107154. }
  107155. }
  107156. // Not found, search in gltf nodes
  107157. var nodes = gltfRuntime.nodes;
  107158. for (var nde in nodes) {
  107159. var node = nodes[nde];
  107160. if (!node.jointName) {
  107161. continue;
  107162. }
  107163. var children = node.children;
  107164. for (var i = 0; i < children.length; i++) {
  107165. var child = gltfRuntime.nodes[children[i]];
  107166. if (!child.jointName) {
  107167. continue;
  107168. }
  107169. if (child.jointName === jointName) {
  107170. var mat = configureBoneTransformation(node);
  107171. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  107172. bone.id = nde;
  107173. return bone;
  107174. }
  107175. }
  107176. }
  107177. return null;
  107178. };
  107179. /**
  107180. * Returns the appropriate root node
  107181. */
  107182. var getNodeToRoot = function (nodesToRoot, id) {
  107183. for (var i = 0; i < nodesToRoot.length; i++) {
  107184. var nodeToRoot = nodesToRoot[i];
  107185. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  107186. var child = nodeToRoot.node.children[j];
  107187. if (child === id) {
  107188. return nodeToRoot.bone;
  107189. }
  107190. }
  107191. }
  107192. return null;
  107193. };
  107194. /**
  107195. * Returns the node with the joint name
  107196. */
  107197. var getJointNode = function (gltfRuntime, jointName) {
  107198. var nodes = gltfRuntime.nodes;
  107199. var node = nodes[jointName];
  107200. if (node) {
  107201. return {
  107202. node: node,
  107203. id: jointName
  107204. };
  107205. }
  107206. for (var nde in nodes) {
  107207. node = nodes[nde];
  107208. if (node.jointName === jointName) {
  107209. return {
  107210. node: node,
  107211. id: nde
  107212. };
  107213. }
  107214. }
  107215. return null;
  107216. };
  107217. /**
  107218. * Checks if a nodes is in joints
  107219. */
  107220. var nodeIsInJoints = function (skins, id) {
  107221. for (var i = 0; i < skins.jointNames.length; i++) {
  107222. if (skins.jointNames[i] === id) {
  107223. return true;
  107224. }
  107225. }
  107226. return false;
  107227. };
  107228. /**
  107229. * Fills the nodes to root for bones and builds hierarchy
  107230. */
  107231. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  107232. // Creates nodes for root
  107233. for (var nde in gltfRuntime.nodes) {
  107234. var node = gltfRuntime.nodes[nde];
  107235. var id = nde;
  107236. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  107237. continue;
  107238. }
  107239. // Create node to root bone
  107240. var mat = configureBoneTransformation(node);
  107241. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  107242. bone.id = id;
  107243. nodesToRoot.push({ bone: bone, node: node, id: id });
  107244. }
  107245. // Parenting
  107246. for (var i = 0; i < nodesToRoot.length; i++) {
  107247. var nodeToRoot = nodesToRoot[i];
  107248. var children = nodeToRoot.node.children;
  107249. for (var j = 0; j < children.length; j++) {
  107250. var child = null;
  107251. for (var k = 0; k < nodesToRoot.length; k++) {
  107252. if (nodesToRoot[k].id === children[j]) {
  107253. child = nodesToRoot[k];
  107254. break;
  107255. }
  107256. }
  107257. if (child) {
  107258. child.bone._parent = nodeToRoot.bone;
  107259. nodeToRoot.bone.children.push(child.bone);
  107260. }
  107261. }
  107262. }
  107263. };
  107264. /**
  107265. * Imports a skeleton
  107266. */
  107267. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  107268. if (!newSkeleton) {
  107269. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  107270. }
  107271. if (!skins.babylonSkeleton) {
  107272. return newSkeleton;
  107273. }
  107274. // Find the root bones
  107275. var nodesToRoot = [];
  107276. var nodesToRootToAdd = [];
  107277. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  107278. newSkeleton.bones = [];
  107279. // Joints
  107280. for (var i = 0; i < skins.jointNames.length; i++) {
  107281. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  107282. if (!jointNode) {
  107283. continue;
  107284. }
  107285. var node = jointNode.node;
  107286. if (!node) {
  107287. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  107288. continue;
  107289. }
  107290. var id = jointNode.id;
  107291. // Optimize, if the bone already exists...
  107292. var existingBone = gltfRuntime.scene.getBoneByID(id);
  107293. if (existingBone) {
  107294. newSkeleton.bones.push(existingBone);
  107295. continue;
  107296. }
  107297. // Search for parent bone
  107298. var foundBone = false;
  107299. var parentBone = null;
  107300. for (var j = 0; j < i; j++) {
  107301. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  107302. if (!jointNode_1) {
  107303. continue;
  107304. }
  107305. var joint = jointNode_1.node;
  107306. if (!joint) {
  107307. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  107308. continue;
  107309. }
  107310. var children = joint.children;
  107311. if (!children) {
  107312. continue;
  107313. }
  107314. foundBone = false;
  107315. for (var k = 0; k < children.length; k++) {
  107316. if (children[k] === id) {
  107317. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  107318. foundBone = true;
  107319. break;
  107320. }
  107321. }
  107322. if (foundBone) {
  107323. break;
  107324. }
  107325. }
  107326. // Create bone
  107327. var mat = configureBoneTransformation(node);
  107328. if (!parentBone && nodesToRoot.length > 0) {
  107329. parentBone = getNodeToRoot(nodesToRoot, id);
  107330. if (parentBone) {
  107331. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  107332. nodesToRootToAdd.push(parentBone);
  107333. }
  107334. }
  107335. }
  107336. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  107337. bone.id = id;
  107338. }
  107339. // Polish
  107340. var bones = newSkeleton.bones;
  107341. newSkeleton.bones = [];
  107342. for (var i = 0; i < skins.jointNames.length; i++) {
  107343. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  107344. if (!jointNode) {
  107345. continue;
  107346. }
  107347. for (var j = 0; j < bones.length; j++) {
  107348. if (bones[j].id === jointNode.id) {
  107349. newSkeleton.bones.push(bones[j]);
  107350. break;
  107351. }
  107352. }
  107353. }
  107354. newSkeleton.prepare();
  107355. // Finish
  107356. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  107357. newSkeleton.bones.push(nodesToRootToAdd[i]);
  107358. }
  107359. return newSkeleton;
  107360. };
  107361. /**
  107362. * Imports a mesh and its geometries
  107363. */
  107364. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  107365. if (!newMesh) {
  107366. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107367. newMesh.id = id;
  107368. }
  107369. if (!node.babylonNode) {
  107370. return newMesh;
  107371. }
  107372. var subMaterials = [];
  107373. var vertexData = null;
  107374. var verticesStarts = new Array();
  107375. var verticesCounts = new Array();
  107376. var indexStarts = new Array();
  107377. var indexCounts = new Array();
  107378. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107379. var meshID = meshes[meshIndex];
  107380. var mesh = gltfRuntime.meshes[meshID];
  107381. if (!mesh) {
  107382. continue;
  107383. }
  107384. // Positions, normals and UVs
  107385. for (var i = 0; i < mesh.primitives.length; i++) {
  107386. // Temporary vertex data
  107387. var tempVertexData = new BABYLON.VertexData();
  107388. var primitive = mesh.primitives[i];
  107389. if (primitive.mode !== 4) {
  107390. // continue;
  107391. }
  107392. var attributes = primitive.attributes;
  107393. var accessor = null;
  107394. var buffer = null;
  107395. // Set positions, normal and uvs
  107396. for (var semantic in attributes) {
  107397. // Link accessor and buffer view
  107398. accessor = gltfRuntime.accessors[attributes[semantic]];
  107399. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107400. if (semantic === "NORMAL") {
  107401. tempVertexData.normals = new Float32Array(buffer.length);
  107402. tempVertexData.normals.set(buffer);
  107403. }
  107404. else if (semantic === "POSITION") {
  107405. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  107406. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  107407. for (var j = 0; j < buffer.length; j += 4) {
  107408. tempVertexData.positions[j] = buffer[j];
  107409. tempVertexData.positions[j + 1] = buffer[j + 1];
  107410. tempVertexData.positions[j + 2] = buffer[j + 2];
  107411. }
  107412. }
  107413. else {
  107414. tempVertexData.positions = new Float32Array(buffer.length);
  107415. tempVertexData.positions.set(buffer);
  107416. }
  107417. verticesCounts.push(tempVertexData.positions.length);
  107418. }
  107419. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  107420. var channel = Number(semantic.split("_")[1]);
  107421. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  107422. var uvs = new Float32Array(buffer.length);
  107423. uvs.set(buffer);
  107424. normalizeUVs(uvs);
  107425. tempVertexData.set(uvs, uvKind);
  107426. }
  107427. else if (semantic === "JOINT") {
  107428. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  107429. tempVertexData.matricesIndices.set(buffer);
  107430. }
  107431. else if (semantic === "WEIGHT") {
  107432. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  107433. tempVertexData.matricesWeights.set(buffer);
  107434. }
  107435. else if (semantic === "COLOR") {
  107436. tempVertexData.colors = new Float32Array(buffer.length);
  107437. tempVertexData.colors.set(buffer);
  107438. }
  107439. }
  107440. // Indices
  107441. accessor = gltfRuntime.accessors[primitive.indices];
  107442. if (accessor) {
  107443. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107444. tempVertexData.indices = new Int32Array(buffer.length);
  107445. tempVertexData.indices.set(buffer);
  107446. indexCounts.push(tempVertexData.indices.length);
  107447. }
  107448. else {
  107449. // Set indices on the fly
  107450. var indices = [];
  107451. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  107452. indices.push(j);
  107453. }
  107454. tempVertexData.indices = new Int32Array(indices);
  107455. indexCounts.push(tempVertexData.indices.length);
  107456. }
  107457. if (!vertexData) {
  107458. vertexData = tempVertexData;
  107459. }
  107460. else {
  107461. vertexData.merge(tempVertexData);
  107462. }
  107463. // Sub material
  107464. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  107465. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  107466. // Update vertices start and index start
  107467. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  107468. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  107469. }
  107470. }
  107471. var material;
  107472. if (subMaterials.length > 1) {
  107473. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  107474. material.subMaterials = subMaterials;
  107475. }
  107476. else {
  107477. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  107478. }
  107479. if (subMaterials.length === 1) {
  107480. material = subMaterials[0];
  107481. }
  107482. if (!newMesh.material) {
  107483. newMesh.material = material;
  107484. }
  107485. // Apply geometry
  107486. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  107487. newMesh.computeWorldMatrix(true);
  107488. // Apply submeshes
  107489. newMesh.subMeshes = [];
  107490. var index = 0;
  107491. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107492. var meshID = meshes[meshIndex];
  107493. var mesh = gltfRuntime.meshes[meshID];
  107494. if (!mesh) {
  107495. continue;
  107496. }
  107497. for (var i = 0; i < mesh.primitives.length; i++) {
  107498. if (mesh.primitives[i].mode !== 4) {
  107499. //continue;
  107500. }
  107501. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  107502. index++;
  107503. }
  107504. }
  107505. // Finish
  107506. return newMesh;
  107507. };
  107508. /**
  107509. * Configure node transformation from position, rotation and scaling
  107510. */
  107511. var configureNode = function (newNode, position, rotation, scaling) {
  107512. if (newNode.position) {
  107513. newNode.position = position;
  107514. }
  107515. if (newNode.rotationQuaternion || newNode.rotation) {
  107516. newNode.rotationQuaternion = rotation;
  107517. }
  107518. if (newNode.scaling) {
  107519. newNode.scaling = scaling;
  107520. }
  107521. };
  107522. /**
  107523. * Configures node from transformation matrix
  107524. */
  107525. var configureNodeFromMatrix = function (newNode, node, parent) {
  107526. if (node.matrix) {
  107527. var position = new BABYLON.Vector3(0, 0, 0);
  107528. var rotation = new BABYLON.Quaternion();
  107529. var scaling = new BABYLON.Vector3(0, 0, 0);
  107530. var mat = BABYLON.Matrix.FromArray(node.matrix);
  107531. mat.decompose(scaling, rotation, position);
  107532. configureNode(newNode, position, rotation, scaling);
  107533. }
  107534. else if (node.translation && node.rotation && node.scale) {
  107535. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  107536. }
  107537. newNode.computeWorldMatrix(true);
  107538. };
  107539. /**
  107540. * Imports a node
  107541. */
  107542. var importNode = function (gltfRuntime, node, id, parent) {
  107543. var lastNode = null;
  107544. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  107545. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  107546. return null;
  107547. }
  107548. }
  107549. // Meshes
  107550. if (node.skin) {
  107551. if (node.meshes) {
  107552. var skin = gltfRuntime.skins[node.skin];
  107553. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  107554. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  107555. if (newMesh.skeleton === null) {
  107556. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  107557. if (!skin.babylonSkeleton) {
  107558. skin.babylonSkeleton = newMesh.skeleton;
  107559. }
  107560. }
  107561. lastNode = newMesh;
  107562. }
  107563. }
  107564. else if (node.meshes) {
  107565. /**
  107566. * Improve meshes property
  107567. */
  107568. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  107569. lastNode = newMesh;
  107570. }
  107571. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107572. var light = gltfRuntime.lights[node.light];
  107573. if (light) {
  107574. if (light.type === "ambient") {
  107575. var ambienLight = light[light.type];
  107576. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107577. hemiLight.name = node.name || "";
  107578. if (ambienLight.color) {
  107579. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  107580. }
  107581. lastNode = hemiLight;
  107582. }
  107583. else if (light.type === "directional") {
  107584. var directionalLight = light[light.type];
  107585. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107586. dirLight.name = node.name || "";
  107587. if (directionalLight.color) {
  107588. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  107589. }
  107590. lastNode = dirLight;
  107591. }
  107592. else if (light.type === "point") {
  107593. var pointLight = light[light.type];
  107594. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107595. ptLight.name = node.name || "";
  107596. if (pointLight.color) {
  107597. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  107598. }
  107599. lastNode = ptLight;
  107600. }
  107601. else if (light.type === "spot") {
  107602. var spotLight = light[light.type];
  107603. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  107604. spLight.name = node.name || "";
  107605. if (spotLight.color) {
  107606. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  107607. }
  107608. if (spotLight.fallOfAngle) {
  107609. spLight.angle = spotLight.fallOfAngle;
  107610. }
  107611. if (spotLight.fallOffExponent) {
  107612. spLight.exponent = spotLight.fallOffExponent;
  107613. }
  107614. lastNode = spLight;
  107615. }
  107616. }
  107617. }
  107618. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107619. var camera = gltfRuntime.cameras[node.camera];
  107620. if (camera) {
  107621. if (camera.type === "orthographic") {
  107622. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107623. orthoCamera.name = node.name || "";
  107624. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  107625. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107626. lastNode = orthoCamera;
  107627. }
  107628. else if (camera.type === "perspective") {
  107629. var perspectiveCamera = camera[camera.type];
  107630. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107631. persCamera.name = node.name || "";
  107632. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107633. if (!perspectiveCamera.aspectRatio) {
  107634. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  107635. }
  107636. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  107637. persCamera.maxZ = perspectiveCamera.zfar;
  107638. persCamera.minZ = perspectiveCamera.znear;
  107639. }
  107640. lastNode = persCamera;
  107641. }
  107642. }
  107643. }
  107644. // Empty node
  107645. if (!node.jointName) {
  107646. if (node.babylonNode) {
  107647. return node.babylonNode;
  107648. }
  107649. else if (lastNode === null) {
  107650. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107651. node.babylonNode = dummy;
  107652. lastNode = dummy;
  107653. }
  107654. }
  107655. if (lastNode !== null) {
  107656. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  107657. configureNodeFromMatrix(lastNode, node, parent);
  107658. }
  107659. else {
  107660. var translation = node.translation || [0, 0, 0];
  107661. var rotation = node.rotation || [0, 0, 0, 1];
  107662. var scale = node.scale || [1, 1, 1];
  107663. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  107664. }
  107665. lastNode.updateCache(true);
  107666. node.babylonNode = lastNode;
  107667. }
  107668. return lastNode;
  107669. };
  107670. /**
  107671. * Traverses nodes and creates them
  107672. */
  107673. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  107674. if (meshIncluded === void 0) { meshIncluded = false; }
  107675. var node = gltfRuntime.nodes[id];
  107676. var newNode = null;
  107677. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  107678. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  107679. meshIncluded = true;
  107680. }
  107681. else {
  107682. meshIncluded = false;
  107683. }
  107684. }
  107685. else {
  107686. meshIncluded = true;
  107687. }
  107688. if (!node.jointName && meshIncluded) {
  107689. newNode = importNode(gltfRuntime, node, id, parent);
  107690. if (newNode !== null) {
  107691. newNode.id = id;
  107692. newNode.parent = parent;
  107693. }
  107694. }
  107695. if (node.children) {
  107696. for (var i = 0; i < node.children.length; i++) {
  107697. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  107698. }
  107699. }
  107700. };
  107701. /**
  107702. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  107703. */
  107704. var postLoad = function (gltfRuntime) {
  107705. // Nodes
  107706. var currentScene = gltfRuntime.currentScene;
  107707. if (currentScene) {
  107708. for (var i = 0; i < currentScene.nodes.length; i++) {
  107709. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107710. }
  107711. }
  107712. else {
  107713. for (var thing in gltfRuntime.scenes) {
  107714. currentScene = gltfRuntime.scenes[thing];
  107715. for (var i = 0; i < currentScene.nodes.length; i++) {
  107716. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107717. }
  107718. }
  107719. }
  107720. // Set animations
  107721. loadAnimations(gltfRuntime);
  107722. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  107723. var skeleton = gltfRuntime.scene.skeletons[i];
  107724. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  107725. }
  107726. };
  107727. /**
  107728. * onBind shaderrs callback to set uniforms and matrices
  107729. */
  107730. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  107731. var materialValues = material.values || technique.parameters;
  107732. for (var unif in unTreatedUniforms) {
  107733. var uniform = unTreatedUniforms[unif];
  107734. var type = uniform.type;
  107735. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  107736. if (uniform.semantic && !uniform.source && !uniform.node) {
  107737. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  107738. }
  107739. else if (uniform.semantic && (uniform.source || uniform.node)) {
  107740. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  107741. if (source === null) {
  107742. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  107743. }
  107744. if (source === null) {
  107745. continue;
  107746. }
  107747. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  107748. }
  107749. }
  107750. else {
  107751. var value = materialValues[technique.uniforms[unif]];
  107752. if (!value) {
  107753. continue;
  107754. }
  107755. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107756. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  107757. if (texture === null || texture === undefined) {
  107758. continue;
  107759. }
  107760. shaderMaterial.getEffect().setTexture(unif, texture);
  107761. }
  107762. else {
  107763. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  107764. }
  107765. }
  107766. }
  107767. onSuccess(shaderMaterial);
  107768. };
  107769. /**
  107770. * Prepare uniforms to send the only one time
  107771. * Loads the appropriate textures
  107772. */
  107773. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  107774. var materialValues = material.values || technique.parameters;
  107775. var techniqueUniforms = technique.uniforms;
  107776. /**
  107777. * Prepare values here (not matrices)
  107778. */
  107779. for (var unif in unTreatedUniforms) {
  107780. var uniform = unTreatedUniforms[unif];
  107781. var type = uniform.type;
  107782. var value = materialValues[techniqueUniforms[unif]];
  107783. if (value === undefined) {
  107784. // In case the value is the same for all materials
  107785. value = uniform.value;
  107786. }
  107787. if (!value) {
  107788. continue;
  107789. }
  107790. var onLoadTexture = function (uniformName) {
  107791. return function (texture) {
  107792. if (uniform.value && uniformName) {
  107793. // Static uniform
  107794. shaderMaterial.setTexture(uniformName, texture);
  107795. delete unTreatedUniforms[uniformName];
  107796. }
  107797. };
  107798. };
  107799. // Texture (sampler2D)
  107800. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107801. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  107802. }
  107803. else {
  107804. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  107805. // Static uniform
  107806. delete unTreatedUniforms[unif];
  107807. }
  107808. }
  107809. }
  107810. };
  107811. /**
  107812. * Shader compilation failed
  107813. */
  107814. var onShaderCompileError = function (program, shaderMaterial, onError) {
  107815. return function (effect, error) {
  107816. shaderMaterial.dispose(true);
  107817. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  107818. };
  107819. };
  107820. /**
  107821. * Shader compilation success
  107822. */
  107823. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  107824. return function (_) {
  107825. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  107826. shaderMaterial.onBind = function (mesh) {
  107827. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  107828. };
  107829. };
  107830. };
  107831. /**
  107832. * Returns the appropriate uniform if already handled by babylon
  107833. */
  107834. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  107835. for (var unif in technique.uniforms) {
  107836. var uniform = technique.uniforms[unif];
  107837. var uniformParameter = technique.parameters[uniform];
  107838. if (tokenizer.currentIdentifier === unif) {
  107839. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  107840. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107841. if (transformIndex !== -1) {
  107842. delete unTreatedUniforms[unif];
  107843. return babylonTransforms[transformIndex];
  107844. }
  107845. }
  107846. }
  107847. }
  107848. return tokenizer.currentIdentifier;
  107849. };
  107850. /**
  107851. * All shaders loaded. Create materials one by one
  107852. */
  107853. var importMaterials = function (gltfRuntime) {
  107854. // Create materials
  107855. for (var mat in gltfRuntime.materials) {
  107856. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  107857. }
  107858. };
  107859. /**
  107860. * Implementation of the base glTF spec
  107861. */
  107862. var GLTFLoaderBase = /** @class */ (function () {
  107863. function GLTFLoaderBase() {
  107864. }
  107865. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  107866. var gltfRuntime = {
  107867. extensions: {},
  107868. accessors: {},
  107869. buffers: {},
  107870. bufferViews: {},
  107871. meshes: {},
  107872. lights: {},
  107873. cameras: {},
  107874. nodes: {},
  107875. images: {},
  107876. textures: {},
  107877. shaders: {},
  107878. programs: {},
  107879. samplers: {},
  107880. techniques: {},
  107881. materials: {},
  107882. animations: {},
  107883. skins: {},
  107884. extensionsUsed: [],
  107885. scenes: {},
  107886. buffersCount: 0,
  107887. shaderscount: 0,
  107888. scene: scene,
  107889. rootUrl: rootUrl,
  107890. loadedBufferCount: 0,
  107891. loadedBufferViews: {},
  107892. loadedShaderCount: 0,
  107893. importOnlyMeshes: false,
  107894. dummyNodes: []
  107895. };
  107896. // Parse
  107897. if (parsedData.extensions) {
  107898. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  107899. }
  107900. if (parsedData.extensionsUsed) {
  107901. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  107902. }
  107903. if (parsedData.buffers) {
  107904. parseBuffers(parsedData.buffers, gltfRuntime);
  107905. }
  107906. if (parsedData.bufferViews) {
  107907. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  107908. }
  107909. if (parsedData.accessors) {
  107910. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  107911. }
  107912. if (parsedData.meshes) {
  107913. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  107914. }
  107915. if (parsedData.lights) {
  107916. parseObject(parsedData.lights, "lights", gltfRuntime);
  107917. }
  107918. if (parsedData.cameras) {
  107919. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  107920. }
  107921. if (parsedData.nodes) {
  107922. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  107923. }
  107924. if (parsedData.images) {
  107925. parseObject(parsedData.images, "images", gltfRuntime);
  107926. }
  107927. if (parsedData.textures) {
  107928. parseObject(parsedData.textures, "textures", gltfRuntime);
  107929. }
  107930. if (parsedData.shaders) {
  107931. parseShaders(parsedData.shaders, gltfRuntime);
  107932. }
  107933. if (parsedData.programs) {
  107934. parseObject(parsedData.programs, "programs", gltfRuntime);
  107935. }
  107936. if (parsedData.samplers) {
  107937. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  107938. }
  107939. if (parsedData.techniques) {
  107940. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  107941. }
  107942. if (parsedData.materials) {
  107943. parseObject(parsedData.materials, "materials", gltfRuntime);
  107944. }
  107945. if (parsedData.animations) {
  107946. parseObject(parsedData.animations, "animations", gltfRuntime);
  107947. }
  107948. if (parsedData.skins) {
  107949. parseObject(parsedData.skins, "skins", gltfRuntime);
  107950. }
  107951. if (parsedData.scenes) {
  107952. gltfRuntime.scenes = parsedData.scenes;
  107953. }
  107954. if (parsedData.scene && parsedData.scenes) {
  107955. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  107956. }
  107957. return gltfRuntime;
  107958. };
  107959. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107960. var buffer = gltfRuntime.buffers[id];
  107961. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  107962. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  107963. }
  107964. else {
  107965. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  107966. if (request) {
  107967. onError(request.status + " " + request.statusText);
  107968. }
  107969. });
  107970. }
  107971. };
  107972. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107973. var texture = gltfRuntime.textures[id];
  107974. if (!texture || !texture.source) {
  107975. onError("");
  107976. return;
  107977. }
  107978. if (texture.babylonTexture) {
  107979. onSuccess(null);
  107980. return;
  107981. }
  107982. var source = gltfRuntime.images[texture.source];
  107983. if (BABYLON.Tools.IsBase64(source.uri)) {
  107984. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  107985. }
  107986. else {
  107987. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  107988. if (request) {
  107989. onError(request.status + " " + request.statusText);
  107990. }
  107991. });
  107992. }
  107993. };
  107994. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107995. var texture = gltfRuntime.textures[id];
  107996. if (texture.babylonTexture) {
  107997. onSuccess(texture.babylonTexture);
  107998. return;
  107999. }
  108000. var sampler = gltfRuntime.samplers[texture.sampler];
  108001. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  108002. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  108003. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  108004. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  108005. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108006. var blob = new Blob([buffer]);
  108007. var blobURL = URL.createObjectURL(blob);
  108008. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  108009. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  108010. if (sampler.wrapS !== undefined) {
  108011. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  108012. }
  108013. if (sampler.wrapT !== undefined) {
  108014. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  108015. }
  108016. newTexture.name = id;
  108017. texture.babylonTexture = newTexture;
  108018. onSuccess(newTexture);
  108019. };
  108020. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108021. var shader = gltfRuntime.shaders[id];
  108022. if (BABYLON.Tools.IsBase64(shader.uri)) {
  108023. var shaderString = atob(shader.uri.split(",")[1]);
  108024. onSuccess(shaderString);
  108025. }
  108026. else {
  108027. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  108028. if (request) {
  108029. onError(request.status + " " + request.statusText);
  108030. }
  108031. });
  108032. }
  108033. };
  108034. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108035. var material = gltfRuntime.materials[id];
  108036. if (!material.technique) {
  108037. if (onError) {
  108038. onError("No technique found.");
  108039. }
  108040. return;
  108041. }
  108042. var technique = gltfRuntime.techniques[material.technique];
  108043. if (!technique) {
  108044. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108045. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  108046. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108047. onSuccess(defaultMaterial);
  108048. return;
  108049. }
  108050. var program = gltfRuntime.programs[technique.program];
  108051. var states = technique.states;
  108052. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  108053. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  108054. var newVertexShader = "";
  108055. var newPixelShader = "";
  108056. var vertexTokenizer = new Tokenizer(vertexShader);
  108057. var pixelTokenizer = new Tokenizer(pixelShader);
  108058. var unTreatedUniforms = {};
  108059. var uniforms = [];
  108060. var attributes = [];
  108061. var samplers = [];
  108062. // Fill uniform, sampler2D and attributes
  108063. for (var unif in technique.uniforms) {
  108064. var uniform = technique.uniforms[unif];
  108065. var uniformParameter = technique.parameters[uniform];
  108066. unTreatedUniforms[unif] = uniformParameter;
  108067. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  108068. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  108069. if (transformIndex !== -1) {
  108070. uniforms.push(babylonTransforms[transformIndex]);
  108071. delete unTreatedUniforms[unif];
  108072. }
  108073. else {
  108074. uniforms.push(unif);
  108075. }
  108076. }
  108077. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  108078. samplers.push(unif);
  108079. }
  108080. else {
  108081. uniforms.push(unif);
  108082. }
  108083. }
  108084. for (var attr in technique.attributes) {
  108085. var attribute = technique.attributes[attr];
  108086. var attributeParameter = technique.parameters[attribute];
  108087. if (attributeParameter.semantic) {
  108088. attributes.push(getAttribute(attributeParameter));
  108089. }
  108090. }
  108091. // Configure vertex shader
  108092. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  108093. var tokenType = vertexTokenizer.currentToken;
  108094. if (tokenType !== ETokenType.IDENTIFIER) {
  108095. newVertexShader += vertexTokenizer.currentString;
  108096. continue;
  108097. }
  108098. var foundAttribute = false;
  108099. for (var attr in technique.attributes) {
  108100. var attribute = technique.attributes[attr];
  108101. var attributeParameter = technique.parameters[attribute];
  108102. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  108103. newVertexShader += getAttribute(attributeParameter);
  108104. foundAttribute = true;
  108105. break;
  108106. }
  108107. }
  108108. if (foundAttribute) {
  108109. continue;
  108110. }
  108111. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  108112. }
  108113. // Configure pixel shader
  108114. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  108115. var tokenType = pixelTokenizer.currentToken;
  108116. if (tokenType !== ETokenType.IDENTIFIER) {
  108117. newPixelShader += pixelTokenizer.currentString;
  108118. continue;
  108119. }
  108120. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  108121. }
  108122. // Create shader material
  108123. var shaderPath = {
  108124. vertex: program.vertexShader + id,
  108125. fragment: program.fragmentShader + id
  108126. };
  108127. var options = {
  108128. attributes: attributes,
  108129. uniforms: uniforms,
  108130. samplers: samplers,
  108131. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  108132. };
  108133. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  108134. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  108135. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  108136. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  108137. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  108138. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108139. if (states && states.functions) {
  108140. var functions = states.functions;
  108141. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  108142. shaderMaterial.backFaceCulling = false;
  108143. }
  108144. var blendFunc = functions.blendFuncSeparate;
  108145. if (blendFunc) {
  108146. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108147. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  108148. }
  108149. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108150. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  108151. }
  108152. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108153. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  108154. }
  108155. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108156. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  108157. }
  108158. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108159. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  108160. }
  108161. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108162. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  108163. }
  108164. }
  108165. }
  108166. };
  108167. return GLTFLoaderBase;
  108168. }());
  108169. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  108170. /**
  108171. * glTF V1 Loader
  108172. */
  108173. var GLTFLoader = /** @class */ (function () {
  108174. function GLTFLoader() {
  108175. // #region Stubs for IGLTFLoader interface
  108176. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  108177. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  108178. this.compileMaterials = false;
  108179. this.useClipPlane = false;
  108180. this.compileShadowGenerators = false;
  108181. this.onDisposeObservable = new BABYLON.Observable();
  108182. this.onMeshLoadedObservable = new BABYLON.Observable();
  108183. this.onTextureLoadedObservable = new BABYLON.Observable();
  108184. this.onMaterialLoadedObservable = new BABYLON.Observable();
  108185. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  108186. this.onCompleteObservable = new BABYLON.Observable();
  108187. this.onExtensionLoadedObservable = new BABYLON.Observable();
  108188. this.state = null;
  108189. }
  108190. GLTFLoader.RegisterExtension = function (extension) {
  108191. if (GLTFLoader.Extensions[extension.name]) {
  108192. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  108193. return;
  108194. }
  108195. GLTFLoader.Extensions[extension.name] = extension;
  108196. };
  108197. GLTFLoader.prototype.dispose = function () { };
  108198. // #endregion
  108199. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  108200. var _this = this;
  108201. scene.useRightHandedSystem = true;
  108202. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  108203. gltfRuntime.importOnlyMeshes = true;
  108204. if (meshesNames === "") {
  108205. gltfRuntime.importMeshesNames = [];
  108206. }
  108207. else if (typeof meshesNames === "string") {
  108208. gltfRuntime.importMeshesNames = [meshesNames];
  108209. }
  108210. else if (meshesNames && !(meshesNames instanceof Array)) {
  108211. gltfRuntime.importMeshesNames = [meshesNames];
  108212. }
  108213. else {
  108214. gltfRuntime.importMeshesNames = [];
  108215. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  108216. }
  108217. // Create nodes
  108218. _this._createNodes(gltfRuntime);
  108219. var meshes = new Array();
  108220. var skeletons = new Array();
  108221. // Fill arrays of meshes and skeletons
  108222. for (var nde in gltfRuntime.nodes) {
  108223. var node = gltfRuntime.nodes[nde];
  108224. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  108225. meshes.push(node.babylonNode);
  108226. }
  108227. }
  108228. for (var skl in gltfRuntime.skins) {
  108229. var skin = gltfRuntime.skins[skl];
  108230. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  108231. skeletons.push(skin.babylonSkeleton);
  108232. }
  108233. }
  108234. // Load buffers, shaders, materials, etc.
  108235. _this._loadBuffersAsync(gltfRuntime, function () {
  108236. _this._loadShadersAsync(gltfRuntime, function () {
  108237. importMaterials(gltfRuntime);
  108238. postLoad(gltfRuntime);
  108239. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  108240. onSuccess(meshes, [], skeletons);
  108241. }
  108242. });
  108243. }, onProgress);
  108244. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  108245. onSuccess(meshes, [], skeletons);
  108246. }
  108247. }, onError);
  108248. return true;
  108249. };
  108250. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108251. var _this = this;
  108252. return new Promise(function (resolve, reject) {
  108253. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  108254. resolve({
  108255. meshes: meshes,
  108256. particleSystems: particleSystems,
  108257. skeletons: skeletons
  108258. });
  108259. }, onProgress, function (message) {
  108260. reject(new Error(message));
  108261. });
  108262. });
  108263. };
  108264. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  108265. var _this = this;
  108266. scene.useRightHandedSystem = true;
  108267. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  108268. // Load runtime extensios
  108269. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  108270. // Create nodes
  108271. _this._createNodes(gltfRuntime);
  108272. // Load buffers, shaders, materials, etc.
  108273. _this._loadBuffersAsync(gltfRuntime, function () {
  108274. _this._loadShadersAsync(gltfRuntime, function () {
  108275. importMaterials(gltfRuntime);
  108276. postLoad(gltfRuntime);
  108277. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  108278. onSuccess();
  108279. }
  108280. });
  108281. });
  108282. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  108283. onSuccess();
  108284. }
  108285. }, onError);
  108286. }, onError);
  108287. };
  108288. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108289. var _this = this;
  108290. return new Promise(function (resolve, reject) {
  108291. _this._loadAsync(scene, data, rootUrl, function () {
  108292. resolve();
  108293. }, onProgress, function (message) {
  108294. reject(new Error(message));
  108295. });
  108296. });
  108297. };
  108298. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  108299. var hasShaders = false;
  108300. var processShader = function (sha, shader) {
  108301. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  108302. gltfRuntime.loadedShaderCount++;
  108303. if (shaderString) {
  108304. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  108305. }
  108306. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  108307. onload();
  108308. }
  108309. }, function () {
  108310. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  108311. });
  108312. };
  108313. for (var sha in gltfRuntime.shaders) {
  108314. hasShaders = true;
  108315. var shader = gltfRuntime.shaders[sha];
  108316. if (shader) {
  108317. processShader.bind(this, sha, shader)();
  108318. }
  108319. else {
  108320. BABYLON.Tools.Error("No shader named: " + sha);
  108321. }
  108322. }
  108323. if (!hasShaders) {
  108324. onload();
  108325. }
  108326. };
  108327. ;
  108328. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  108329. var hasBuffers = false;
  108330. var processBuffer = function (buf, buffer) {
  108331. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  108332. gltfRuntime.loadedBufferCount++;
  108333. if (bufferView) {
  108334. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  108335. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  108336. }
  108337. gltfRuntime.loadedBufferViews[buf] = bufferView;
  108338. }
  108339. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  108340. onLoad();
  108341. }
  108342. }, function () {
  108343. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  108344. });
  108345. };
  108346. for (var buf in gltfRuntime.buffers) {
  108347. hasBuffers = true;
  108348. var buffer = gltfRuntime.buffers[buf];
  108349. if (buffer) {
  108350. processBuffer.bind(this, buf, buffer)();
  108351. }
  108352. else {
  108353. BABYLON.Tools.Error("No buffer named: " + buf);
  108354. }
  108355. }
  108356. if (!hasBuffers) {
  108357. onLoad();
  108358. }
  108359. };
  108360. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  108361. var currentScene = gltfRuntime.currentScene;
  108362. if (currentScene) {
  108363. // Only one scene even if multiple scenes are defined
  108364. for (var i = 0; i < currentScene.nodes.length; i++) {
  108365. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108366. }
  108367. }
  108368. else {
  108369. // Load all scenes
  108370. for (var thing in gltfRuntime.scenes) {
  108371. currentScene = gltfRuntime.scenes[thing];
  108372. for (var i = 0; i < currentScene.nodes.length; i++) {
  108373. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108374. }
  108375. }
  108376. }
  108377. };
  108378. GLTFLoader.Extensions = {};
  108379. return GLTFLoader;
  108380. }());
  108381. GLTF1.GLTFLoader = GLTFLoader;
  108382. ;
  108383. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  108384. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108385. })(BABYLON || (BABYLON = {}));
  108386. //# sourceMappingURL=babylon.glTFLoader.js.map
  108387. var BABYLON;
  108388. (function (BABYLON) {
  108389. var GLTF1;
  108390. (function (GLTF1) {
  108391. /**
  108392. * Utils functions for GLTF
  108393. */
  108394. var GLTFUtils = /** @class */ (function () {
  108395. function GLTFUtils() {
  108396. }
  108397. /**
  108398. * Sets the given "parameter" matrix
  108399. * @param scene: the {BABYLON.Scene} object
  108400. * @param source: the source node where to pick the matrix
  108401. * @param parameter: the GLTF technique parameter
  108402. * @param uniformName: the name of the shader's uniform
  108403. * @param shaderMaterial: the shader material
  108404. */
  108405. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  108406. var mat = null;
  108407. if (parameter.semantic === "MODEL") {
  108408. mat = source.getWorldMatrix();
  108409. }
  108410. else if (parameter.semantic === "PROJECTION") {
  108411. mat = scene.getProjectionMatrix();
  108412. }
  108413. else if (parameter.semantic === "VIEW") {
  108414. mat = scene.getViewMatrix();
  108415. }
  108416. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  108417. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  108418. }
  108419. else if (parameter.semantic === "MODELVIEW") {
  108420. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  108421. }
  108422. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  108423. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  108424. }
  108425. else if (parameter.semantic === "MODELINVERSE") {
  108426. mat = source.getWorldMatrix().invert();
  108427. }
  108428. else if (parameter.semantic === "VIEWINVERSE") {
  108429. mat = scene.getViewMatrix().invert();
  108430. }
  108431. else if (parameter.semantic === "PROJECTIONINVERSE") {
  108432. mat = scene.getProjectionMatrix().invert();
  108433. }
  108434. else if (parameter.semantic === "MODELVIEWINVERSE") {
  108435. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  108436. }
  108437. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  108438. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  108439. }
  108440. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  108441. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  108442. }
  108443. else {
  108444. debugger;
  108445. }
  108446. if (mat) {
  108447. switch (parameter.type) {
  108448. case GLTF1.EParameterType.FLOAT_MAT2:
  108449. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  108450. break;
  108451. case GLTF1.EParameterType.FLOAT_MAT3:
  108452. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  108453. break;
  108454. case GLTF1.EParameterType.FLOAT_MAT4:
  108455. shaderMaterial.setMatrix(uniformName, mat);
  108456. break;
  108457. default: break;
  108458. }
  108459. }
  108460. };
  108461. /**
  108462. * Sets the given "parameter" matrix
  108463. * @param shaderMaterial: the shader material
  108464. * @param uniform: the name of the shader's uniform
  108465. * @param value: the value of the uniform
  108466. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  108467. */
  108468. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  108469. switch (type) {
  108470. case GLTF1.EParameterType.FLOAT:
  108471. shaderMaterial.setFloat(uniform, value);
  108472. return true;
  108473. case GLTF1.EParameterType.FLOAT_VEC2:
  108474. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  108475. return true;
  108476. case GLTF1.EParameterType.FLOAT_VEC3:
  108477. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  108478. return true;
  108479. case GLTF1.EParameterType.FLOAT_VEC4:
  108480. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  108481. return true;
  108482. default: return false;
  108483. }
  108484. };
  108485. /**
  108486. * Returns the wrap mode of the texture
  108487. * @param mode: the mode value
  108488. */
  108489. GLTFUtils.GetWrapMode = function (mode) {
  108490. switch (mode) {
  108491. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108492. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108493. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108494. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108495. }
  108496. };
  108497. /**
  108498. * Returns the byte stride giving an accessor
  108499. * @param accessor: the GLTF accessor objet
  108500. */
  108501. GLTFUtils.GetByteStrideFromType = function (accessor) {
  108502. // Needs this function since "byteStride" isn't requiered in glTF format
  108503. var type = accessor.type;
  108504. switch (type) {
  108505. case "VEC2": return 2;
  108506. case "VEC3": return 3;
  108507. case "VEC4": return 4;
  108508. case "MAT2": return 4;
  108509. case "MAT3": return 9;
  108510. case "MAT4": return 16;
  108511. default: return 1;
  108512. }
  108513. };
  108514. /**
  108515. * Returns the texture filter mode giving a mode value
  108516. * @param mode: the filter mode value
  108517. */
  108518. GLTFUtils.GetTextureFilterMode = function (mode) {
  108519. switch (mode) {
  108520. case GLTF1.ETextureFilterType.LINEAR:
  108521. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  108522. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  108523. case GLTF1.ETextureFilterType.NEAREST:
  108524. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  108525. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108526. }
  108527. };
  108528. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  108529. var byteOffset = bufferView.byteOffset + byteOffset;
  108530. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  108531. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  108532. throw new Error("Buffer access is out of range");
  108533. }
  108534. var buffer = loadedBufferView.buffer;
  108535. byteOffset += loadedBufferView.byteOffset;
  108536. switch (componentType) {
  108537. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  108538. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  108539. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  108540. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  108541. default: return new Float32Array(buffer, byteOffset, byteLength);
  108542. }
  108543. };
  108544. /**
  108545. * Returns a buffer from its accessor
  108546. * @param gltfRuntime: the GLTF runtime
  108547. * @param accessor: the GLTF accessor
  108548. */
  108549. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  108550. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  108551. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  108552. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  108553. };
  108554. /**
  108555. * Decodes a buffer view into a string
  108556. * @param view: the buffer view
  108557. */
  108558. GLTFUtils.DecodeBufferToText = function (view) {
  108559. var result = "";
  108560. var length = view.byteLength;
  108561. for (var i = 0; i < length; ++i) {
  108562. result += String.fromCharCode(view[i]);
  108563. }
  108564. return result;
  108565. };
  108566. /**
  108567. * Returns the default material of gltf. Related to
  108568. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  108569. * @param scene: the Babylon.js scene
  108570. */
  108571. GLTFUtils.GetDefaultMaterial = function (scene) {
  108572. if (!GLTFUtils._DefaultMaterial) {
  108573. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  108574. "precision highp float;",
  108575. "",
  108576. "uniform mat4 worldView;",
  108577. "uniform mat4 projection;",
  108578. "",
  108579. "attribute vec3 position;",
  108580. "",
  108581. "void main(void)",
  108582. "{",
  108583. " gl_Position = projection * worldView * vec4(position, 1.0);",
  108584. "}"
  108585. ].join("\n");
  108586. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  108587. "precision highp float;",
  108588. "",
  108589. "uniform vec4 u_emission;",
  108590. "",
  108591. "void main(void)",
  108592. "{",
  108593. " gl_FragColor = u_emission;",
  108594. "}"
  108595. ].join("\n");
  108596. var shaderPath = {
  108597. vertex: "GLTFDefaultMaterial",
  108598. fragment: "GLTFDefaultMaterial"
  108599. };
  108600. var options = {
  108601. attributes: ["position"],
  108602. uniforms: ["worldView", "projection", "u_emission"],
  108603. samplers: new Array(),
  108604. needAlphaBlending: false
  108605. };
  108606. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  108607. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  108608. }
  108609. return GLTFUtils._DefaultMaterial;
  108610. };
  108611. // The GLTF default material
  108612. GLTFUtils._DefaultMaterial = null;
  108613. return GLTFUtils;
  108614. }());
  108615. GLTF1.GLTFUtils = GLTFUtils;
  108616. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108617. })(BABYLON || (BABYLON = {}));
  108618. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  108619. var BABYLON;
  108620. (function (BABYLON) {
  108621. var GLTF1;
  108622. (function (GLTF1) {
  108623. var GLTFLoaderExtension = /** @class */ (function () {
  108624. function GLTFLoaderExtension(name) {
  108625. this._name = name;
  108626. }
  108627. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  108628. get: function () {
  108629. return this._name;
  108630. },
  108631. enumerable: true,
  108632. configurable: true
  108633. });
  108634. /**
  108635. * Defines an override for loading the runtime
  108636. * Return true to stop further extensions from loading the runtime
  108637. */
  108638. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108639. return false;
  108640. };
  108641. /**
  108642. * Defines an onverride for creating gltf runtime
  108643. * Return true to stop further extensions from creating the runtime
  108644. */
  108645. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108646. return false;
  108647. };
  108648. /**
  108649. * Defines an override for loading buffers
  108650. * Return true to stop further extensions from loading this buffer
  108651. */
  108652. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108653. return false;
  108654. };
  108655. /**
  108656. * Defines an override for loading texture buffers
  108657. * Return true to stop further extensions from loading this texture data
  108658. */
  108659. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108660. return false;
  108661. };
  108662. /**
  108663. * Defines an override for creating textures
  108664. * Return true to stop further extensions from loading this texture
  108665. */
  108666. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108667. return false;
  108668. };
  108669. /**
  108670. * Defines an override for loading shader strings
  108671. * Return true to stop further extensions from loading this shader data
  108672. */
  108673. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108674. return false;
  108675. };
  108676. /**
  108677. * Defines an override for loading materials
  108678. * Return true to stop further extensions from loading this material
  108679. */
  108680. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108681. return false;
  108682. };
  108683. // ---------
  108684. // Utilities
  108685. // ---------
  108686. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108687. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108688. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  108689. }, function () {
  108690. setTimeout(function () {
  108691. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108692. });
  108693. });
  108694. };
  108695. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108696. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108697. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  108698. }, function () {
  108699. setTimeout(function () {
  108700. onSuccess();
  108701. });
  108702. });
  108703. };
  108704. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108705. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108706. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108707. }, function () {
  108708. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108709. });
  108710. };
  108711. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  108712. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  108713. };
  108714. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108715. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108716. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108717. }, function () {
  108718. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108719. });
  108720. };
  108721. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108722. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108723. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108724. }, function () {
  108725. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108726. });
  108727. };
  108728. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108729. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108730. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108731. }, function () {
  108732. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108733. });
  108734. };
  108735. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108736. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108737. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108738. }, function () {
  108739. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108740. });
  108741. };
  108742. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  108743. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  108744. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  108745. if (func(loaderExtension)) {
  108746. return;
  108747. }
  108748. }
  108749. defaultFunc();
  108750. };
  108751. return GLTFLoaderExtension;
  108752. }());
  108753. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  108754. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108755. })(BABYLON || (BABYLON = {}));
  108756. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108757. var BABYLON;
  108758. (function (BABYLON) {
  108759. var GLTF1;
  108760. (function (GLTF1) {
  108761. var BinaryExtensionBufferName = "binary_glTF";
  108762. ;
  108763. ;
  108764. var GLTFBinaryExtension = /** @class */ (function (_super) {
  108765. __extends(GLTFBinaryExtension, _super);
  108766. function GLTFBinaryExtension() {
  108767. return _super.call(this, "KHR_binary_glTF") || this;
  108768. }
  108769. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108770. var extensionsUsed = data.json.extensionsUsed;
  108771. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  108772. return false;
  108773. }
  108774. this._bin = data.bin;
  108775. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108776. return true;
  108777. };
  108778. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108779. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  108780. return false;
  108781. }
  108782. if (id !== BinaryExtensionBufferName) {
  108783. return false;
  108784. }
  108785. onSuccess(this._bin);
  108786. return true;
  108787. };
  108788. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108789. var texture = gltfRuntime.textures[id];
  108790. var source = gltfRuntime.images[texture.source];
  108791. if (!source.extensions || !(this.name in source.extensions)) {
  108792. return false;
  108793. }
  108794. var sourceExt = source.extensions[this.name];
  108795. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  108796. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108797. onSuccess(buffer);
  108798. return true;
  108799. };
  108800. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108801. var shader = gltfRuntime.shaders[id];
  108802. if (!shader.extensions || !(this.name in shader.extensions)) {
  108803. return false;
  108804. }
  108805. var binaryExtensionShader = shader.extensions[this.name];
  108806. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  108807. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108808. setTimeout(function () {
  108809. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  108810. onSuccess(shaderString);
  108811. });
  108812. return true;
  108813. };
  108814. return GLTFBinaryExtension;
  108815. }(GLTF1.GLTFLoaderExtension));
  108816. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  108817. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  108818. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108819. })(BABYLON || (BABYLON = {}));
  108820. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  108821. var BABYLON;
  108822. (function (BABYLON) {
  108823. var GLTF1;
  108824. (function (GLTF1) {
  108825. ;
  108826. ;
  108827. ;
  108828. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  108829. __extends(GLTFMaterialsCommonExtension, _super);
  108830. function GLTFMaterialsCommonExtension() {
  108831. return _super.call(this, "KHR_materials_common") || this;
  108832. }
  108833. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108834. if (!gltfRuntime.extensions)
  108835. return false;
  108836. var extension = gltfRuntime.extensions[this.name];
  108837. if (!extension)
  108838. return false;
  108839. // Create lights
  108840. var lights = extension.lights;
  108841. if (lights) {
  108842. for (var thing in lights) {
  108843. var light = lights[thing];
  108844. switch (light.type) {
  108845. case "ambient":
  108846. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  108847. var ambient = light.ambient;
  108848. if (ambient) {
  108849. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  108850. }
  108851. break;
  108852. case "point":
  108853. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  108854. var point = light.point;
  108855. if (point) {
  108856. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  108857. }
  108858. break;
  108859. case "directional":
  108860. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  108861. var directional = light.directional;
  108862. if (directional) {
  108863. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  108864. }
  108865. break;
  108866. case "spot":
  108867. var spot = light.spot;
  108868. if (spot) {
  108869. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  108870. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  108871. }
  108872. break;
  108873. default:
  108874. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  108875. break;
  108876. }
  108877. }
  108878. }
  108879. return false;
  108880. };
  108881. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108882. var material = gltfRuntime.materials[id];
  108883. if (!material || !material.extensions)
  108884. return false;
  108885. var extension = material.extensions[this.name];
  108886. if (!extension)
  108887. return false;
  108888. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108889. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108890. if (extension.technique === "CONSTANT") {
  108891. standardMaterial.disableLighting = true;
  108892. }
  108893. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  108894. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  108895. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  108896. // Ambient
  108897. if (typeof extension.values.ambient === "string") {
  108898. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  108899. }
  108900. else {
  108901. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  108902. }
  108903. // Diffuse
  108904. if (typeof extension.values.diffuse === "string") {
  108905. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  108906. }
  108907. else {
  108908. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  108909. }
  108910. // Emission
  108911. if (typeof extension.values.emission === "string") {
  108912. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  108913. }
  108914. else {
  108915. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  108916. }
  108917. // Specular
  108918. if (typeof extension.values.specular === "string") {
  108919. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  108920. }
  108921. else {
  108922. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  108923. }
  108924. return true;
  108925. };
  108926. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  108927. // Create buffer from texture url
  108928. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108929. // Create texture from buffer
  108930. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  108931. }, onError);
  108932. };
  108933. return GLTFMaterialsCommonExtension;
  108934. }(GLTF1.GLTFLoaderExtension));
  108935. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  108936. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  108937. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108938. })(BABYLON || (BABYLON = {}));
  108939. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  108940. var BABYLON;
  108941. (function (BABYLON) {
  108942. var GLTF2;
  108943. (function (GLTF2) {
  108944. var ArrayItem = /** @class */ (function () {
  108945. function ArrayItem() {
  108946. }
  108947. ArrayItem.Assign = function (values) {
  108948. if (values) {
  108949. for (var index = 0; index < values.length; index++) {
  108950. values[index]._index = index;
  108951. }
  108952. }
  108953. };
  108954. return ArrayItem;
  108955. }());
  108956. GLTF2.ArrayItem = ArrayItem;
  108957. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108958. })(BABYLON || (BABYLON = {}));
  108959. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  108960. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  108961. var BABYLON;
  108962. (function (BABYLON) {
  108963. var GLTF2;
  108964. (function (GLTF2) {
  108965. var GLTFLoader = /** @class */ (function () {
  108966. function GLTFLoader() {
  108967. this._completePromises = new Array();
  108968. this._disposed = false;
  108969. this._state = null;
  108970. this._extensions = {};
  108971. this._defaultSampler = {};
  108972. this._requests = new Array();
  108973. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  108974. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  108975. this.compileMaterials = false;
  108976. this.useClipPlane = false;
  108977. this.compileShadowGenerators = false;
  108978. this.onDisposeObservable = new BABYLON.Observable();
  108979. this.onMeshLoadedObservable = new BABYLON.Observable();
  108980. this.onTextureLoadedObservable = new BABYLON.Observable();
  108981. this.onMaterialLoadedObservable = new BABYLON.Observable();
  108982. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  108983. this.onExtensionLoadedObservable = new BABYLON.Observable();
  108984. this.onCompleteObservable = new BABYLON.Observable();
  108985. }
  108986. GLTFLoader._Register = function (name, factory) {
  108987. if (GLTFLoader._Factories[name]) {
  108988. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  108989. return;
  108990. }
  108991. GLTFLoader._Factories[name] = factory;
  108992. // Keep the order of registration so that extensions registered first are called first.
  108993. GLTFLoader._Names.push(name);
  108994. };
  108995. Object.defineProperty(GLTFLoader.prototype, "state", {
  108996. get: function () {
  108997. return this._state;
  108998. },
  108999. enumerable: true,
  109000. configurable: true
  109001. });
  109002. GLTFLoader.prototype.dispose = function () {
  109003. if (this._disposed) {
  109004. return;
  109005. }
  109006. this._disposed = true;
  109007. this.onDisposeObservable.notifyObservers(this);
  109008. this.onDisposeObservable.clear();
  109009. this._clear();
  109010. };
  109011. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  109012. var _this = this;
  109013. return Promise.resolve().then(function () {
  109014. var nodes = null;
  109015. if (meshesNames) {
  109016. var nodeMap_1 = {};
  109017. if (_this._gltf.nodes) {
  109018. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  109019. var node = _a[_i];
  109020. if (node.name) {
  109021. nodeMap_1[node.name] = node;
  109022. }
  109023. }
  109024. }
  109025. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  109026. nodes = names.map(function (name) {
  109027. var node = nodeMap_1[name];
  109028. if (!node) {
  109029. throw new Error("Failed to find node '" + name + "'");
  109030. }
  109031. return node;
  109032. });
  109033. }
  109034. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  109035. return {
  109036. meshes: _this._getMeshes(),
  109037. particleSystems: [],
  109038. skeletons: _this._getSkeletons(),
  109039. };
  109040. });
  109041. });
  109042. };
  109043. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  109044. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  109045. };
  109046. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  109047. var _this = this;
  109048. return Promise.resolve().then(function () {
  109049. _this._loadExtensions();
  109050. _this._babylonScene = scene;
  109051. _this._rootUrl = rootUrl;
  109052. _this._progressCallback = onProgress;
  109053. _this._state = BABYLON.GLTFLoaderState.Loading;
  109054. _this._loadData(data);
  109055. _this._checkExtensions();
  109056. var promises = new Array();
  109057. if (nodes) {
  109058. promises.push(_this._loadNodesAsync(nodes));
  109059. }
  109060. else {
  109061. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  109062. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  109063. }
  109064. if (_this.compileMaterials) {
  109065. promises.push(_this._compileMaterialsAsync());
  109066. }
  109067. if (_this.compileShadowGenerators) {
  109068. promises.push(_this._compileShadowGeneratorsAsync());
  109069. }
  109070. var resultPromise = Promise.all(promises).then(function () {
  109071. _this._state = BABYLON.GLTFLoaderState.Ready;
  109072. _this._startAnimations();
  109073. });
  109074. resultPromise.then(function () {
  109075. _this._rootBabylonMesh.setEnabled(true);
  109076. BABYLON.Tools.SetImmediate(function () {
  109077. if (!_this._disposed) {
  109078. Promise.all(_this._completePromises).then(function () {
  109079. _this._state = BABYLON.GLTFLoaderState.Complete;
  109080. _this.onCompleteObservable.notifyObservers(_this);
  109081. _this.onCompleteObservable.clear();
  109082. _this._clear();
  109083. }).catch(function (error) {
  109084. BABYLON.Tools.Error("glTF Loader: " + error.message);
  109085. _this._clear();
  109086. });
  109087. }
  109088. });
  109089. });
  109090. return resultPromise;
  109091. }).catch(function (error) {
  109092. BABYLON.Tools.Error("glTF Loader: " + error.message);
  109093. _this._clear();
  109094. throw error;
  109095. });
  109096. };
  109097. GLTFLoader.prototype._loadExtensions = function () {
  109098. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  109099. var name_1 = _a[_i];
  109100. var extension = GLTFLoader._Factories[name_1](this);
  109101. this._extensions[name_1] = extension;
  109102. this.onExtensionLoadedObservable.notifyObservers(extension);
  109103. }
  109104. this.onExtensionLoadedObservable.clear();
  109105. };
  109106. GLTFLoader.prototype._loadData = function (data) {
  109107. this._gltf = data.json;
  109108. this._setupData();
  109109. if (data.bin) {
  109110. var buffers = this._gltf.buffers;
  109111. if (buffers && buffers[0] && !buffers[0].uri) {
  109112. var binaryBuffer = buffers[0];
  109113. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  109114. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  109115. }
  109116. binaryBuffer._data = Promise.resolve(data.bin);
  109117. }
  109118. else {
  109119. BABYLON.Tools.Warn("Unexpected BIN chunk");
  109120. }
  109121. }
  109122. };
  109123. GLTFLoader.prototype._setupData = function () {
  109124. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  109125. GLTF2.ArrayItem.Assign(this._gltf.animations);
  109126. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  109127. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  109128. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  109129. GLTF2.ArrayItem.Assign(this._gltf.images);
  109130. GLTF2.ArrayItem.Assign(this._gltf.materials);
  109131. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  109132. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  109133. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  109134. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  109135. GLTF2.ArrayItem.Assign(this._gltf.skins);
  109136. GLTF2.ArrayItem.Assign(this._gltf.textures);
  109137. if (this._gltf.nodes) {
  109138. var nodeParents = {};
  109139. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  109140. var node = _a[_i];
  109141. if (node.children) {
  109142. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  109143. var index = _c[_b];
  109144. nodeParents[index] = node._index;
  109145. }
  109146. }
  109147. }
  109148. var rootNode = this._createRootNode();
  109149. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  109150. var node = _e[_d];
  109151. var parentIndex = nodeParents[node._index];
  109152. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  109153. }
  109154. }
  109155. };
  109156. GLTFLoader.prototype._checkExtensions = function () {
  109157. if (this._gltf.extensionsRequired) {
  109158. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  109159. var name_2 = _a[_i];
  109160. var extension = this._extensions[name_2];
  109161. if (!extension || !extension.enabled) {
  109162. throw new Error("Require extension " + name_2 + " is not available");
  109163. }
  109164. }
  109165. }
  109166. };
  109167. GLTFLoader.prototype._createRootNode = function () {
  109168. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  109169. this._rootBabylonMesh.setEnabled(false);
  109170. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  109171. switch (this.coordinateSystemMode) {
  109172. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  109173. if (!this._babylonScene.useRightHandedSystem) {
  109174. rootNode.rotation = [0, 1, 0, 0];
  109175. rootNode.scale = [1, 1, -1];
  109176. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  109177. }
  109178. break;
  109179. }
  109180. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  109181. this._babylonScene.useRightHandedSystem = true;
  109182. break;
  109183. }
  109184. default: {
  109185. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  109186. }
  109187. }
  109188. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  109189. return rootNode;
  109190. };
  109191. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  109192. var promises = new Array();
  109193. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  109194. var node = nodes_1[_i];
  109195. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  109196. }
  109197. promises.push(this._loadAnimationsAsync());
  109198. return Promise.all(promises).then(function () { });
  109199. };
  109200. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  109201. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  109202. if (promise) {
  109203. return promise;
  109204. }
  109205. var promises = new Array();
  109206. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  109207. var index = _a[_i];
  109208. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  109209. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  109210. }
  109211. promises.push(this._loadAnimationsAsync());
  109212. return Promise.all(promises).then(function () { });
  109213. };
  109214. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  109215. if (node._primitiveBabylonMeshes) {
  109216. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  109217. var babylonMesh = _a[_i];
  109218. callback(babylonMesh);
  109219. }
  109220. }
  109221. else {
  109222. callback(node._babylonMesh);
  109223. }
  109224. };
  109225. GLTFLoader.prototype._getMeshes = function () {
  109226. var meshes = new Array();
  109227. // Root mesh is always first.
  109228. meshes.push(this._rootBabylonMesh);
  109229. var nodes = this._gltf.nodes;
  109230. if (nodes) {
  109231. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  109232. var node = nodes_2[_i];
  109233. if (node._babylonMesh) {
  109234. meshes.push(node._babylonMesh);
  109235. }
  109236. if (node._primitiveBabylonMeshes) {
  109237. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  109238. var babylonMesh = _b[_a];
  109239. meshes.push(babylonMesh);
  109240. }
  109241. }
  109242. }
  109243. }
  109244. return meshes;
  109245. };
  109246. GLTFLoader.prototype._getSkeletons = function () {
  109247. var skeletons = new Array();
  109248. var skins = this._gltf.skins;
  109249. if (skins) {
  109250. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  109251. var skin = skins_1[_i];
  109252. if (skin._babylonSkeleton) {
  109253. skeletons.push(skin._babylonSkeleton);
  109254. }
  109255. }
  109256. }
  109257. return skeletons;
  109258. };
  109259. GLTFLoader.prototype._startAnimations = function () {
  109260. var animations = this._gltf.animations;
  109261. if (!animations) {
  109262. return;
  109263. }
  109264. switch (this.animationStartMode) {
  109265. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  109266. // do nothing
  109267. break;
  109268. }
  109269. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  109270. var animation = animations[0];
  109271. animation._babylonAnimationGroup.start(true);
  109272. break;
  109273. }
  109274. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  109275. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  109276. var animation = animations_1[_i];
  109277. animation._babylonAnimationGroup.start(true);
  109278. }
  109279. break;
  109280. }
  109281. default: {
  109282. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  109283. return;
  109284. }
  109285. }
  109286. };
  109287. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  109288. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  109289. if (promise) {
  109290. return promise;
  109291. }
  109292. if (node._babylonMesh) {
  109293. throw new Error(context + ": Invalid recursive node hierarchy");
  109294. }
  109295. var promises = new Array();
  109296. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  109297. node._babylonMesh = babylonMesh;
  109298. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  109299. node._babylonAnimationTargets.push(babylonMesh);
  109300. GLTFLoader._LoadTransform(node, babylonMesh);
  109301. if (node.mesh != undefined) {
  109302. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  109303. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  109304. }
  109305. if (node.children) {
  109306. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  109307. var index = _a[_i];
  109308. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  109309. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  109310. }
  109311. }
  109312. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  109313. return Promise.all(promises).then(function () { });
  109314. };
  109315. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  109316. // TODO: instancing
  109317. var _this = this;
  109318. var promises = new Array();
  109319. var primitives = mesh.primitives;
  109320. if (!primitives || primitives.length === 0) {
  109321. throw new Error(context + ": Primitives are missing");
  109322. }
  109323. GLTF2.ArrayItem.Assign(primitives);
  109324. if (primitives.length === 1) {
  109325. var primitive = primitives[0];
  109326. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  109327. }
  109328. else {
  109329. node._primitiveBabylonMeshes = [];
  109330. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  109331. var primitive = primitives_1[_i];
  109332. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  109333. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  109334. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  109335. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  109336. }
  109337. }
  109338. if (node.skin != undefined) {
  109339. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  109340. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  109341. }
  109342. return Promise.all(promises).then(function () {
  109343. _this._forEachPrimitive(node, function (babylonMesh) {
  109344. babylonMesh._refreshBoundingInfo(true);
  109345. });
  109346. });
  109347. };
  109348. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  109349. var _this = this;
  109350. var promises = new Array();
  109351. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  109352. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  109353. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  109354. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  109355. }));
  109356. if (primitive.material == undefined) {
  109357. babylonMesh.material = this._getDefaultMaterial();
  109358. }
  109359. else {
  109360. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  109361. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  109362. babylonMesh.material = babylonMaterial;
  109363. }));
  109364. }
  109365. return Promise.all(promises).then(function () { });
  109366. };
  109367. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109368. var _this = this;
  109369. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  109370. if (promise) {
  109371. return promise;
  109372. }
  109373. var attributes = primitive.attributes;
  109374. if (!attributes) {
  109375. throw new Error(context + ": Attributes are missing");
  109376. }
  109377. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  109378. // TODO: handle other primitive modes
  109379. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  109380. }
  109381. var promises = new Array();
  109382. var babylonVertexData = new BABYLON.VertexData();
  109383. if (primitive.indices == undefined) {
  109384. var positionAccessorIndex = attributes["POSITION"];
  109385. if (positionAccessorIndex != undefined) {
  109386. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  109387. babylonVertexData.indices = new Uint32Array(accessor.count);
  109388. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  109389. babylonVertexData.indices[i] = i;
  109390. }
  109391. }
  109392. }
  109393. else {
  109394. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  109395. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  109396. babylonVertexData.indices = data;
  109397. }));
  109398. }
  109399. var loadAttribute = function (attribute, kind) {
  109400. if (attributes[attribute] == undefined) {
  109401. return;
  109402. }
  109403. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109404. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109405. babylonMesh._delayInfo.push(kind);
  109406. }
  109407. if (attribute === "COLOR_0") {
  109408. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  109409. babylonMesh.hasVertexAlpha = true;
  109410. }
  109411. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109412. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109413. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  109414. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  109415. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  109416. }
  109417. babylonVertexData.set(attributeData, kind);
  109418. }));
  109419. };
  109420. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109421. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109422. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109423. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109424. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109425. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109426. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109427. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  109428. return Promise.all(promises).then(function () {
  109429. return babylonVertexData;
  109430. });
  109431. };
  109432. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  109433. if (!primitive.targets) {
  109434. return;
  109435. }
  109436. if (node._numMorphTargets == undefined) {
  109437. node._numMorphTargets = primitive.targets.length;
  109438. }
  109439. else if (primitive.targets.length !== node._numMorphTargets) {
  109440. throw new Error(context + ": Primitives do not have the same number of targets");
  109441. }
  109442. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  109443. for (var index = 0; index < primitive.targets.length; index++) {
  109444. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  109445. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  109446. // TODO: tell the target whether it has positions, normals, tangents
  109447. }
  109448. };
  109449. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  109450. if (!primitive.targets) {
  109451. return Promise.resolve();
  109452. }
  109453. var promises = new Array();
  109454. var morphTargetManager = babylonMesh.morphTargetManager;
  109455. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  109456. var babylonMorphTarget = morphTargetManager.getTarget(index);
  109457. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  109458. }
  109459. return Promise.all(promises).then(function () { });
  109460. };
  109461. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  109462. var _this = this;
  109463. var promises = new Array();
  109464. var loadAttribute = function (attribute, setData) {
  109465. if (attributes[attribute] == undefined) {
  109466. return;
  109467. }
  109468. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109469. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109470. setData(data);
  109471. }));
  109472. };
  109473. loadAttribute("POSITION", function (data) {
  109474. if (babylonVertexData.positions) {
  109475. for (var i = 0; i < data.length; i++) {
  109476. data[i] += babylonVertexData.positions[i];
  109477. }
  109478. babylonMorphTarget.setPositions(data);
  109479. }
  109480. });
  109481. loadAttribute("NORMAL", function (data) {
  109482. if (babylonVertexData.normals) {
  109483. for (var i = 0; i < data.length; i++) {
  109484. data[i] += babylonVertexData.normals[i];
  109485. }
  109486. babylonMorphTarget.setNormals(data);
  109487. }
  109488. });
  109489. loadAttribute("TANGENT", function (data) {
  109490. if (babylonVertexData.tangents) {
  109491. // Tangent data for morph targets is stored as xyz delta.
  109492. // The vertexData.tangent is stored as xyzw.
  109493. // So we need to skip every fourth vertexData.tangent.
  109494. for (var i = 0, j = 0; i < data.length; i++) {
  109495. data[i] += babylonVertexData.tangents[j++];
  109496. if ((i + 1) % 3 == 0) {
  109497. j++;
  109498. }
  109499. }
  109500. babylonMorphTarget.setTangents(data);
  109501. }
  109502. });
  109503. return Promise.all(promises).then(function () { });
  109504. };
  109505. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  109506. if (accessor.componentType == 5126 /* FLOAT */) {
  109507. return data;
  109508. }
  109509. var factor = 1;
  109510. if (accessor.normalized) {
  109511. switch (accessor.componentType) {
  109512. case 5121 /* UNSIGNED_BYTE */: {
  109513. factor = 1 / 255;
  109514. break;
  109515. }
  109516. case 5123 /* UNSIGNED_SHORT */: {
  109517. factor = 1 / 65535;
  109518. break;
  109519. }
  109520. default: {
  109521. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  109522. }
  109523. }
  109524. }
  109525. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  109526. for (var i = 0; i < result.length; i++) {
  109527. result[i] = data[i] * factor;
  109528. }
  109529. return result;
  109530. };
  109531. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  109532. var result = new Float32Array(data.length / 3 * 4);
  109533. var offset = 0;
  109534. for (var i = 0; i < result.length; i++) {
  109535. if ((i + 1) % 4 === 0) {
  109536. result[i] = 1;
  109537. }
  109538. else {
  109539. result[i] = data[offset++];
  109540. }
  109541. }
  109542. return result;
  109543. };
  109544. GLTFLoader._LoadTransform = function (node, babylonNode) {
  109545. var position = BABYLON.Vector3.Zero();
  109546. var rotation = BABYLON.Quaternion.Identity();
  109547. var scaling = BABYLON.Vector3.One();
  109548. if (node.matrix) {
  109549. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  109550. matrix.decompose(scaling, rotation, position);
  109551. }
  109552. else {
  109553. if (node.translation)
  109554. position = BABYLON.Vector3.FromArray(node.translation);
  109555. if (node.rotation)
  109556. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  109557. if (node.scale)
  109558. scaling = BABYLON.Vector3.FromArray(node.scale);
  109559. }
  109560. babylonNode.position = position;
  109561. babylonNode.rotationQuaternion = rotation;
  109562. babylonNode.scaling = scaling;
  109563. };
  109564. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  109565. var _this = this;
  109566. var assignSkeleton = function () {
  109567. _this._forEachPrimitive(node, function (babylonMesh) {
  109568. babylonMesh.skeleton = skin._babylonSkeleton;
  109569. });
  109570. node._babylonMesh.parent = _this._rootBabylonMesh;
  109571. node._babylonMesh.position = BABYLON.Vector3.Zero();
  109572. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  109573. node._babylonMesh.scaling = BABYLON.Vector3.One();
  109574. };
  109575. if (skin._loaded) {
  109576. return skin._loaded.then(function () {
  109577. assignSkeleton();
  109578. });
  109579. }
  109580. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  109581. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  109582. var skeletonId = "skeleton" + skin._index;
  109583. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  109584. skin._babylonSkeleton = babylonSkeleton;
  109585. _this._loadBones(context, skin, inverseBindMatricesData);
  109586. assignSkeleton();
  109587. }));
  109588. };
  109589. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  109590. if (skin.inverseBindMatrices == undefined) {
  109591. return Promise.resolve(null);
  109592. }
  109593. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  109594. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109595. return data;
  109596. });
  109597. };
  109598. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  109599. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  109600. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  109601. node._babylonAnimationTargets.push(babylonBone);
  109602. return babylonBone;
  109603. };
  109604. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  109605. var babylonBones = {};
  109606. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  109607. var index = _a[_i];
  109608. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  109609. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  109610. }
  109611. };
  109612. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  109613. var babylonBone = babylonBones[node._index];
  109614. if (babylonBone) {
  109615. return babylonBone;
  109616. }
  109617. var boneIndex = skin.joints.indexOf(node._index);
  109618. var baseMatrix = BABYLON.Matrix.Identity();
  109619. if (inverseBindMatricesData && boneIndex !== -1) {
  109620. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  109621. baseMatrix.invertToRef(baseMatrix);
  109622. }
  109623. var babylonParentBone = null;
  109624. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  109625. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  109626. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  109627. }
  109628. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  109629. babylonBones[node._index] = babylonBone;
  109630. return babylonBone;
  109631. };
  109632. GLTFLoader.prototype._getNodeMatrix = function (node) {
  109633. return node.matrix ?
  109634. BABYLON.Matrix.FromArray(node.matrix) :
  109635. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  109636. };
  109637. GLTFLoader.prototype._loadAnimationsAsync = function () {
  109638. var animations = this._gltf.animations;
  109639. if (!animations) {
  109640. return Promise.resolve();
  109641. }
  109642. var promises = new Array();
  109643. for (var index = 0; index < animations.length; index++) {
  109644. var animation = animations[index];
  109645. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  109646. }
  109647. return Promise.all(promises).then(function () { });
  109648. };
  109649. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  109650. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  109651. animation._babylonAnimationGroup = babylonAnimationGroup;
  109652. var promises = new Array();
  109653. GLTF2.ArrayItem.Assign(animation.channels);
  109654. GLTF2.ArrayItem.Assign(animation.samplers);
  109655. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  109656. var channel = _a[_i];
  109657. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  109658. }
  109659. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  109660. return Promise.all(promises).then(function () {
  109661. babylonAnimationGroup.normalize();
  109662. });
  109663. };
  109664. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  109665. var _this = this;
  109666. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  109667. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  109668. return Promise.resolve();
  109669. }
  109670. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  109671. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  109672. var targetPath;
  109673. var animationType;
  109674. switch (channel.target.path) {
  109675. case "translation" /* TRANSLATION */: {
  109676. targetPath = "position";
  109677. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109678. break;
  109679. }
  109680. case "rotation" /* ROTATION */: {
  109681. targetPath = "rotationQuaternion";
  109682. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  109683. break;
  109684. }
  109685. case "scale" /* SCALE */: {
  109686. targetPath = "scaling";
  109687. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109688. break;
  109689. }
  109690. case "weights" /* WEIGHTS */: {
  109691. targetPath = "influence";
  109692. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  109693. break;
  109694. }
  109695. default: {
  109696. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  109697. }
  109698. }
  109699. var outputBufferOffset = 0;
  109700. var getNextOutputValue;
  109701. switch (targetPath) {
  109702. case "position": {
  109703. getNextOutputValue = function () {
  109704. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109705. outputBufferOffset += 3;
  109706. return value;
  109707. };
  109708. break;
  109709. }
  109710. case "rotationQuaternion": {
  109711. getNextOutputValue = function () {
  109712. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  109713. outputBufferOffset += 4;
  109714. return value;
  109715. };
  109716. break;
  109717. }
  109718. case "scaling": {
  109719. getNextOutputValue = function () {
  109720. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109721. outputBufferOffset += 3;
  109722. return value;
  109723. };
  109724. break;
  109725. }
  109726. case "influence": {
  109727. getNextOutputValue = function () {
  109728. var value = new Array(targetNode._numMorphTargets);
  109729. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  109730. value[i] = data.output[outputBufferOffset++];
  109731. }
  109732. return value;
  109733. };
  109734. break;
  109735. }
  109736. }
  109737. var getNextKey;
  109738. switch (data.interpolation) {
  109739. case "STEP" /* STEP */: {
  109740. getNextKey = function (frameIndex) { return ({
  109741. frame: data.input[frameIndex],
  109742. value: getNextOutputValue(),
  109743. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  109744. }); };
  109745. break;
  109746. }
  109747. case "LINEAR" /* LINEAR */: {
  109748. getNextKey = function (frameIndex) { return ({
  109749. frame: data.input[frameIndex],
  109750. value: getNextOutputValue()
  109751. }); };
  109752. break;
  109753. }
  109754. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109755. getNextKey = function (frameIndex) { return ({
  109756. frame: data.input[frameIndex],
  109757. inTangent: getNextOutputValue(),
  109758. value: getNextOutputValue(),
  109759. outTangent: getNextOutputValue()
  109760. }); };
  109761. break;
  109762. }
  109763. }
  109764. var keys;
  109765. if (data.input.length === 1) {
  109766. var key = getNextKey(0);
  109767. keys = [
  109768. { frame: key.frame, value: key.value },
  109769. { frame: key.frame + 1, value: key.value }
  109770. ];
  109771. }
  109772. else {
  109773. keys = new Array(data.input.length);
  109774. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  109775. keys[frameIndex] = getNextKey(frameIndex);
  109776. }
  109777. }
  109778. if (targetPath === "influence") {
  109779. var _loop_1 = function (targetIndex) {
  109780. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109781. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109782. babylonAnimation.setKeys(keys.map(function (key) { return ({
  109783. frame: key.frame,
  109784. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  109785. value: key.value[targetIndex],
  109786. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  109787. }); }));
  109788. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  109789. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  109790. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  109791. });
  109792. };
  109793. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  109794. _loop_1(targetIndex);
  109795. }
  109796. }
  109797. else {
  109798. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109799. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109800. babylonAnimation.setKeys(keys);
  109801. if (targetNode._babylonAnimationTargets) {
  109802. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  109803. var target = _a[_i];
  109804. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  109805. }
  109806. }
  109807. }
  109808. });
  109809. };
  109810. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  109811. if (sampler._data) {
  109812. return sampler._data;
  109813. }
  109814. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  109815. switch (interpolation) {
  109816. case "STEP" /* STEP */:
  109817. case "LINEAR" /* LINEAR */:
  109818. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109819. break;
  109820. }
  109821. default: {
  109822. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  109823. }
  109824. }
  109825. var inputData;
  109826. var outputData;
  109827. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  109828. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  109829. sampler._data = Promise.all([
  109830. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  109831. inputData = data;
  109832. }),
  109833. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  109834. outputData = data;
  109835. })
  109836. ]).then(function () {
  109837. return {
  109838. input: inputData,
  109839. interpolation: interpolation,
  109840. output: outputData,
  109841. };
  109842. });
  109843. return sampler._data;
  109844. };
  109845. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  109846. if (buffer._data) {
  109847. return buffer._data;
  109848. }
  109849. if (!buffer.uri) {
  109850. throw new Error(context + ": Uri is missing");
  109851. }
  109852. buffer._data = this._loadUriAsync(context, buffer.uri);
  109853. return buffer._data;
  109854. };
  109855. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  109856. if (bufferView._data) {
  109857. return bufferView._data;
  109858. }
  109859. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  109860. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  109861. try {
  109862. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  109863. }
  109864. catch (e) {
  109865. throw new Error(context + ": " + e.message);
  109866. }
  109867. });
  109868. return bufferView._data;
  109869. };
  109870. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  109871. var _this = this;
  109872. if (accessor.sparse) {
  109873. throw new Error(context + ": Sparse accessors are not currently supported");
  109874. }
  109875. if (accessor._data) {
  109876. return accessor._data;
  109877. }
  109878. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109879. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  109880. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  109881. var byteOffset = accessor.byteOffset || 0;
  109882. var byteStride = bufferView.byteStride;
  109883. if (byteStride === 0) {
  109884. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  109885. }
  109886. try {
  109887. switch (accessor.componentType) {
  109888. case 5120 /* BYTE */: {
  109889. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109890. }
  109891. case 5121 /* UNSIGNED_BYTE */: {
  109892. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109893. }
  109894. case 5122 /* SHORT */: {
  109895. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109896. }
  109897. case 5123 /* UNSIGNED_SHORT */: {
  109898. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109899. }
  109900. case 5125 /* UNSIGNED_INT */: {
  109901. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109902. }
  109903. case 5126 /* FLOAT */: {
  109904. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109905. }
  109906. default: {
  109907. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  109908. }
  109909. }
  109910. }
  109911. catch (e) {
  109912. throw new Error(context + ": " + e.messsage);
  109913. }
  109914. });
  109915. return accessor._data;
  109916. };
  109917. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  109918. byteOffset += data.byteOffset;
  109919. var targetLength = count * numComponents;
  109920. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  109921. return new typedArray(data.buffer, byteOffset, targetLength);
  109922. }
  109923. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  109924. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  109925. var targetBuffer = new typedArray(targetLength);
  109926. var sourceIndex = 0;
  109927. var targetIndex = 0;
  109928. while (targetIndex < targetLength) {
  109929. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  109930. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  109931. targetIndex++;
  109932. }
  109933. sourceIndex += elementStride;
  109934. }
  109935. return targetBuffer;
  109936. };
  109937. GLTFLoader.prototype._getDefaultMaterial = function () {
  109938. var id = "__gltf_default";
  109939. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  109940. if (!babylonMaterial) {
  109941. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  109942. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109943. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109944. babylonMaterial.metallic = 1;
  109945. babylonMaterial.roughness = 1;
  109946. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109947. }
  109948. return babylonMaterial;
  109949. };
  109950. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  109951. var promises = new Array();
  109952. var babylonMaterial = material._babylonMaterial;
  109953. // Ensure metallic workflow
  109954. babylonMaterial.metallic = 1;
  109955. babylonMaterial.roughness = 1;
  109956. var properties = material.pbrMetallicRoughness;
  109957. if (properties) {
  109958. if (properties.baseColorFactor) {
  109959. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109960. babylonMaterial.alpha = properties.baseColorFactor[3];
  109961. }
  109962. else {
  109963. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109964. }
  109965. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  109966. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  109967. if (properties.baseColorTexture) {
  109968. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109969. babylonMaterial.albedoTexture = texture;
  109970. }));
  109971. }
  109972. if (properties.metallicRoughnessTexture) {
  109973. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  109974. babylonMaterial.metallicTexture = texture;
  109975. }));
  109976. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  109977. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  109978. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  109979. }
  109980. }
  109981. this._loadMaterialAlphaProperties(context, material);
  109982. return Promise.all(promises).then(function () { });
  109983. };
  109984. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109985. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  109986. if (promise) {
  109987. return promise;
  109988. }
  109989. material._babylonMeshes = material._babylonMeshes || [];
  109990. material._babylonMeshes.push(babylonMesh);
  109991. if (!material._loaded) {
  109992. var promises = new Array();
  109993. var babylonMaterial = this._createMaterial(material);
  109994. material._babylonMaterial = babylonMaterial;
  109995. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  109996. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  109997. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109998. material._loaded = Promise.all(promises).then(function () { });
  109999. }
  110000. assign(material._babylonMaterial);
  110001. return material._loaded;
  110002. };
  110003. GLTFLoader.prototype._createMaterial = function (material) {
  110004. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  110005. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  110006. return babylonMaterial;
  110007. };
  110008. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  110009. var promises = new Array();
  110010. var babylonMaterial = material._babylonMaterial;
  110011. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  110012. if (material.doubleSided) {
  110013. babylonMaterial.backFaceCulling = false;
  110014. babylonMaterial.twoSidedLighting = true;
  110015. }
  110016. if (material.normalTexture) {
  110017. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  110018. babylonMaterial.bumpTexture = texture;
  110019. }));
  110020. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  110021. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  110022. if (material.normalTexture.scale != undefined) {
  110023. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  110024. }
  110025. }
  110026. if (material.occlusionTexture) {
  110027. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  110028. babylonMaterial.ambientTexture = texture;
  110029. }));
  110030. babylonMaterial.useAmbientInGrayScale = true;
  110031. if (material.occlusionTexture.strength != undefined) {
  110032. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  110033. }
  110034. }
  110035. if (material.emissiveTexture) {
  110036. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  110037. babylonMaterial.emissiveTexture = texture;
  110038. }));
  110039. }
  110040. return Promise.all(promises).then(function () { });
  110041. };
  110042. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  110043. var babylonMaterial = material._babylonMaterial;
  110044. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  110045. switch (alphaMode) {
  110046. case "OPAQUE" /* OPAQUE */: {
  110047. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  110048. break;
  110049. }
  110050. case "MASK" /* MASK */: {
  110051. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  110052. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  110053. if (babylonMaterial.alpha) {
  110054. if (babylonMaterial.alpha === 0) {
  110055. babylonMaterial.alphaCutOff = 1;
  110056. }
  110057. else {
  110058. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  110059. }
  110060. babylonMaterial.alpha = 1;
  110061. }
  110062. if (babylonMaterial.albedoTexture) {
  110063. babylonMaterial.albedoTexture.hasAlpha = true;
  110064. }
  110065. break;
  110066. }
  110067. case "BLEND" /* BLEND */: {
  110068. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  110069. if (babylonMaterial.albedoTexture) {
  110070. babylonMaterial.albedoTexture.hasAlpha = true;
  110071. babylonMaterial.useAlphaFromAlbedoTexture = true;
  110072. }
  110073. break;
  110074. }
  110075. default: {
  110076. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  110077. }
  110078. }
  110079. };
  110080. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  110081. var _this = this;
  110082. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  110083. context = "#/textures/" + textureInfo.index;
  110084. var promises = new Array();
  110085. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  110086. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  110087. var deferred = new BABYLON.Deferred();
  110088. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  110089. if (!_this._disposed) {
  110090. deferred.resolve();
  110091. }
  110092. }, function (message, exception) {
  110093. if (!_this._disposed) {
  110094. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  110095. }
  110096. });
  110097. promises.push(deferred.promise);
  110098. babylonTexture.name = texture.name || "texture" + texture._index;
  110099. babylonTexture.wrapU = samplerData.wrapU;
  110100. babylonTexture.wrapV = samplerData.wrapV;
  110101. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  110102. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  110103. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  110104. babylonTexture.updateURL(objectURL);
  110105. }));
  110106. assign(babylonTexture);
  110107. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  110108. return Promise.all(promises).then(function () { });
  110109. };
  110110. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  110111. if (!sampler._data) {
  110112. sampler._data = {
  110113. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  110114. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  110115. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  110116. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  110117. };
  110118. }
  110119. ;
  110120. return sampler._data;
  110121. };
  110122. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  110123. if (image._objectURL) {
  110124. return image._objectURL;
  110125. }
  110126. var promise;
  110127. if (image.uri) {
  110128. promise = this._loadUriAsync(context, image.uri);
  110129. }
  110130. else {
  110131. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  110132. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  110133. }
  110134. image._objectURL = promise.then(function (data) {
  110135. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  110136. });
  110137. return image._objectURL;
  110138. };
  110139. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  110140. var _this = this;
  110141. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  110142. if (promise) {
  110143. return promise;
  110144. }
  110145. if (!GLTFLoader._ValidateUri(uri)) {
  110146. throw new Error(context + ": Uri '" + uri + "' is invalid");
  110147. }
  110148. if (BABYLON.Tools.IsBase64(uri)) {
  110149. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  110150. }
  110151. return new Promise(function (resolve, reject) {
  110152. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  110153. if (!_this._disposed) {
  110154. resolve(new Uint8Array(data));
  110155. }
  110156. }, function (event) {
  110157. if (!_this._disposed) {
  110158. try {
  110159. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  110160. request._lengthComputable = event.lengthComputable;
  110161. request._loaded = event.loaded;
  110162. request._total = event.total;
  110163. _this._onProgress();
  110164. }
  110165. }
  110166. catch (e) {
  110167. reject(e);
  110168. }
  110169. }
  110170. }, _this._babylonScene.database, true, function (request, exception) {
  110171. if (!_this._disposed) {
  110172. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  110173. }
  110174. });
  110175. _this._requests.push(request);
  110176. });
  110177. };
  110178. GLTFLoader.prototype._onProgress = function () {
  110179. if (!this._progressCallback) {
  110180. return;
  110181. }
  110182. var lengthComputable = true;
  110183. var loaded = 0;
  110184. var total = 0;
  110185. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  110186. var request = _a[_i];
  110187. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  110188. return;
  110189. }
  110190. lengthComputable = lengthComputable && request._lengthComputable;
  110191. loaded += request._loaded;
  110192. total += request._total;
  110193. }
  110194. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  110195. };
  110196. GLTFLoader._GetProperty = function (context, array, index) {
  110197. if (!array || index == undefined || !array[index]) {
  110198. throw new Error(context + ": Failed to find index (" + index + ")");
  110199. }
  110200. return array[index];
  110201. };
  110202. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  110203. // Set defaults if undefined
  110204. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  110205. switch (mode) {
  110206. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  110207. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  110208. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  110209. default:
  110210. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  110211. return BABYLON.Texture.WRAP_ADDRESSMODE;
  110212. }
  110213. };
  110214. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  110215. // Set defaults if undefined
  110216. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  110217. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  110218. if (magFilter === 9729 /* LINEAR */) {
  110219. switch (minFilter) {
  110220. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  110221. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  110222. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  110223. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  110224. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  110225. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  110226. default:
  110227. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  110228. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  110229. }
  110230. }
  110231. else {
  110232. if (magFilter !== 9728 /* NEAREST */) {
  110233. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  110234. }
  110235. switch (minFilter) {
  110236. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  110237. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  110238. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  110239. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  110240. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  110241. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  110242. default:
  110243. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  110244. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  110245. }
  110246. }
  110247. };
  110248. GLTFLoader._GetNumComponents = function (context, type) {
  110249. switch (type) {
  110250. case "SCALAR": return 1;
  110251. case "VEC2": return 2;
  110252. case "VEC3": return 3;
  110253. case "VEC4": return 4;
  110254. case "MAT2": return 4;
  110255. case "MAT3": return 9;
  110256. case "MAT4": return 16;
  110257. }
  110258. throw new Error(context + ": Invalid type (" + type + ")");
  110259. };
  110260. GLTFLoader._ValidateUri = function (uri) {
  110261. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  110262. };
  110263. GLTFLoader.prototype._compileMaterialsAsync = function () {
  110264. var promises = new Array();
  110265. if (this._gltf.materials) {
  110266. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  110267. var material = _a[_i];
  110268. var babylonMaterial = material._babylonMaterial;
  110269. var babylonMeshes = material._babylonMeshes;
  110270. if (babylonMaterial && babylonMeshes) {
  110271. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  110272. var babylonMesh = babylonMeshes_1[_b];
  110273. // Ensure nonUniformScaling is set if necessary.
  110274. babylonMesh.computeWorldMatrix(true);
  110275. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  110276. if (this.useClipPlane) {
  110277. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  110278. }
  110279. }
  110280. }
  110281. }
  110282. }
  110283. return Promise.all(promises).then(function () { });
  110284. };
  110285. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  110286. var promises = new Array();
  110287. var lights = this._babylonScene.lights;
  110288. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  110289. var light = lights_1[_i];
  110290. var generator = light.getShadowGenerator();
  110291. if (generator) {
  110292. promises.push(generator.forceCompilationAsync());
  110293. }
  110294. }
  110295. return Promise.all(promises).then(function () { });
  110296. };
  110297. GLTFLoader.prototype._clear = function () {
  110298. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  110299. var request = _a[_i];
  110300. request.abort();
  110301. }
  110302. this._requests.length = 0;
  110303. if (this._gltf && this._gltf.images) {
  110304. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  110305. var image = _c[_b];
  110306. if (image._objectURL) {
  110307. image._objectURL.then(function (value) {
  110308. URL.revokeObjectURL(value);
  110309. });
  110310. image._objectURL = undefined;
  110311. }
  110312. }
  110313. }
  110314. delete this._gltf;
  110315. delete this._babylonScene;
  110316. this._completePromises.length = 0;
  110317. for (var name_3 in this._extensions) {
  110318. this._extensions[name_3].dispose();
  110319. }
  110320. this._extensions = {};
  110321. delete this._rootBabylonMesh;
  110322. delete this._progressCallback;
  110323. this.onMeshLoadedObservable.clear();
  110324. this.onTextureLoadedObservable.clear();
  110325. this.onMaterialLoadedObservable.clear();
  110326. };
  110327. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  110328. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  110329. var name_4 = _a[_i];
  110330. var extension = this._extensions[name_4];
  110331. if (extension.enabled) {
  110332. var promise = actionAsync(extension);
  110333. if (promise) {
  110334. return promise;
  110335. }
  110336. }
  110337. }
  110338. return null;
  110339. };
  110340. GLTFLoader._Names = new Array();
  110341. GLTFLoader._Factories = {};
  110342. return GLTFLoader;
  110343. }());
  110344. GLTF2.GLTFLoader = GLTFLoader;
  110345. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  110346. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110347. })(BABYLON || (BABYLON = {}));
  110348. //# sourceMappingURL=babylon.glTFLoader.js.map
  110349. var BABYLON;
  110350. (function (BABYLON) {
  110351. var GLTF2;
  110352. (function (GLTF2) {
  110353. var GLTFLoaderExtension = /** @class */ (function () {
  110354. function GLTFLoaderExtension(loader) {
  110355. this.enabled = true;
  110356. this._loader = loader;
  110357. }
  110358. GLTFLoaderExtension.prototype.dispose = function () {
  110359. delete this._loader;
  110360. };
  110361. // #region Overridable Methods
  110362. /** Override this method to modify the default behavior for loading scenes. */
  110363. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  110364. /** Override this method to modify the default behavior for loading nodes. */
  110365. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  110366. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  110367. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  110368. /** Override this method to modify the default behavior for loading materials. */
  110369. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  110370. /** Override this method to modify the default behavior for loading uris. */
  110371. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  110372. // #endregion
  110373. /** Helper method called by a loader extension to load an glTF extension. */
  110374. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  110375. if (!property.extensions) {
  110376. return null;
  110377. }
  110378. var extensions = property.extensions;
  110379. var extension = extensions[this.name];
  110380. if (!extension) {
  110381. return null;
  110382. }
  110383. // Clear out the extension before executing the action to avoid recursing into the same property.
  110384. delete extensions[this.name];
  110385. try {
  110386. return actionAsync(context + "/extensions/" + this.name, extension);
  110387. }
  110388. finally {
  110389. // Restore the extension after executing the action.
  110390. extensions[this.name] = extension;
  110391. }
  110392. };
  110393. /** Helper method called by the loader to allow extensions to override loading scenes. */
  110394. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  110395. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  110396. };
  110397. /** Helper method called by the loader to allow extensions to override loading nodes. */
  110398. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  110399. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  110400. };
  110401. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  110402. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  110403. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  110404. };
  110405. /** Helper method called by the loader to allow extensions to override loading materials. */
  110406. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  110407. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  110408. };
  110409. /** Helper method called by the loader to allow extensions to override loading uris. */
  110410. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  110411. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  110412. };
  110413. return GLTFLoaderExtension;
  110414. }());
  110415. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  110416. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110417. })(BABYLON || (BABYLON = {}));
  110418. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  110419. var BABYLON;
  110420. (function (BABYLON) {
  110421. var GLTF2;
  110422. (function (GLTF2) {
  110423. var Extensions;
  110424. (function (Extensions) {
  110425. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  110426. var NAME = "MSFT_lod";
  110427. var MSFT_lod = /** @class */ (function (_super) {
  110428. __extends(MSFT_lod, _super);
  110429. function MSFT_lod() {
  110430. var _this = _super !== null && _super.apply(this, arguments) || this;
  110431. _this.name = NAME;
  110432. /**
  110433. * Maximum number of LODs to load, starting from the lowest LOD.
  110434. */
  110435. _this.maxLODsToLoad = Number.MAX_VALUE;
  110436. _this._loadingNodeLOD = null;
  110437. _this._loadNodeSignals = {};
  110438. _this._loadingMaterialLOD = null;
  110439. _this._loadMaterialSignals = {};
  110440. return _this;
  110441. }
  110442. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  110443. var _this = this;
  110444. return this._loadExtensionAsync(context, node, function (context, extension) {
  110445. var firstPromise;
  110446. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  110447. var _loop_1 = function (indexLOD) {
  110448. var nodeLOD = nodeLODs[indexLOD];
  110449. if (indexLOD !== 0) {
  110450. _this._loadingNodeLOD = nodeLOD;
  110451. if (!_this._loadNodeSignals[nodeLOD._index]) {
  110452. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  110453. }
  110454. }
  110455. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  110456. if (indexLOD !== 0) {
  110457. var previousNodeLOD = nodeLODs[indexLOD - 1];
  110458. if (previousNodeLOD._babylonMesh) {
  110459. previousNodeLOD._babylonMesh.dispose();
  110460. delete previousNodeLOD._babylonMesh;
  110461. }
  110462. }
  110463. if (indexLOD !== nodeLODs.length - 1) {
  110464. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  110465. if (_this._loadNodeSignals[nodeIndex]) {
  110466. _this._loadNodeSignals[nodeIndex].resolve();
  110467. delete _this._loadNodeSignals[nodeIndex];
  110468. }
  110469. }
  110470. });
  110471. if (indexLOD === 0) {
  110472. firstPromise = promise;
  110473. }
  110474. else {
  110475. _this._loader._completePromises.push(promise);
  110476. _this._loadingNodeLOD = null;
  110477. }
  110478. };
  110479. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  110480. _loop_1(indexLOD);
  110481. }
  110482. return firstPromise;
  110483. });
  110484. };
  110485. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  110486. var _this = this;
  110487. // Don't load material LODs if already loading a node LOD.
  110488. if (this._loadingNodeLOD) {
  110489. return null;
  110490. }
  110491. return this._loadExtensionAsync(context, material, function (context, extension) {
  110492. var firstPromise;
  110493. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  110494. var _loop_2 = function (indexLOD) {
  110495. var materialLOD = materialLODs[indexLOD];
  110496. if (indexLOD !== 0) {
  110497. _this._loadingMaterialLOD = materialLOD;
  110498. if (!_this._loadMaterialSignals[materialLOD._index]) {
  110499. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  110500. }
  110501. }
  110502. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  110503. if (indexLOD !== 0) {
  110504. assign(materialLOD._babylonMaterial);
  110505. var previousMaterialLOD = materialLODs[indexLOD - 1];
  110506. if (previousMaterialLOD._babylonMaterial) {
  110507. previousMaterialLOD._babylonMaterial.dispose();
  110508. delete previousMaterialLOD._babylonMaterial;
  110509. }
  110510. }
  110511. if (indexLOD !== materialLODs.length - 1) {
  110512. var materialIndex = materialLODs[indexLOD + 1]._index;
  110513. if (_this._loadMaterialSignals[materialIndex]) {
  110514. _this._loadMaterialSignals[materialIndex].resolve();
  110515. delete _this._loadMaterialSignals[materialIndex];
  110516. }
  110517. }
  110518. });
  110519. if (indexLOD === 0) {
  110520. firstPromise = promise;
  110521. }
  110522. else {
  110523. _this._loader._completePromises.push(promise);
  110524. _this._loadingMaterialLOD = null;
  110525. }
  110526. };
  110527. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  110528. _loop_2(indexLOD);
  110529. }
  110530. return firstPromise;
  110531. });
  110532. };
  110533. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  110534. var _this = this;
  110535. // Defer the loading of uris if loading a material or node LOD.
  110536. if (this._loadingMaterialLOD) {
  110537. var index = this._loadingMaterialLOD._index;
  110538. return this._loadMaterialSignals[index].promise.then(function () {
  110539. return _this._loader._loadUriAsync(context, uri);
  110540. });
  110541. }
  110542. else if (this._loadingNodeLOD) {
  110543. var index = this._loadingNodeLOD._index;
  110544. return this._loadNodeSignals[index].promise.then(function () {
  110545. return _this._loader._loadUriAsync(context, uri);
  110546. });
  110547. }
  110548. return null;
  110549. };
  110550. /**
  110551. * Gets an array of LOD properties from lowest to highest.
  110552. */
  110553. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  110554. if (this.maxLODsToLoad <= 0) {
  110555. throw new Error("maxLODsToLoad must be greater than zero");
  110556. }
  110557. var properties = new Array();
  110558. for (var i = ids.length - 1; i >= 0; i--) {
  110559. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  110560. if (properties.length === this.maxLODsToLoad) {
  110561. return properties;
  110562. }
  110563. }
  110564. properties.push(property);
  110565. return properties;
  110566. };
  110567. return MSFT_lod;
  110568. }(GLTF2.GLTFLoaderExtension));
  110569. Extensions.MSFT_lod = MSFT_lod;
  110570. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  110571. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110572. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110573. })(BABYLON || (BABYLON = {}));
  110574. //# sourceMappingURL=MSFT_lod.js.map
  110575. var BABYLON;
  110576. (function (BABYLON) {
  110577. var GLTF2;
  110578. (function (GLTF2) {
  110579. var Extensions;
  110580. (function (Extensions) {
  110581. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  110582. var NAME = "KHR_draco_mesh_compression";
  110583. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  110584. __extends(KHR_draco_mesh_compression, _super);
  110585. function KHR_draco_mesh_compression(loader) {
  110586. var _this = _super.call(this, loader) || this;
  110587. _this.name = NAME;
  110588. _this._dracoCompression = null;
  110589. // Disable extension if decoder is not available.
  110590. if (!BABYLON.DracoCompression.DecoderUrl) {
  110591. _this.enabled = false;
  110592. }
  110593. return _this;
  110594. }
  110595. KHR_draco_mesh_compression.prototype.dispose = function () {
  110596. if (this._dracoCompression) {
  110597. this._dracoCompression.dispose();
  110598. }
  110599. _super.prototype.dispose.call(this);
  110600. };
  110601. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  110602. var _this = this;
  110603. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  110604. if (primitive.mode != undefined) {
  110605. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  110606. primitive.mode !== 4 /* TRIANGLES */) {
  110607. throw new Error(context + ": Unsupported mode " + primitive.mode);
  110608. }
  110609. // TODO: handle triangle strips
  110610. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  110611. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  110612. }
  110613. }
  110614. var attributes = {};
  110615. var loadAttribute = function (name, kind) {
  110616. var uniqueId = extension.attributes[name];
  110617. if (uniqueId == undefined) {
  110618. return;
  110619. }
  110620. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  110621. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  110622. babylonMesh._delayInfo.push(kind);
  110623. }
  110624. attributes[kind] = uniqueId;
  110625. };
  110626. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  110627. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  110628. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  110629. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  110630. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  110631. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  110632. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  110633. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  110634. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  110635. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110636. try {
  110637. if (!_this._dracoCompression) {
  110638. _this._dracoCompression = new BABYLON.DracoCompression();
  110639. }
  110640. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  110641. }
  110642. catch (e) {
  110643. throw new Error(context + ": " + e.message);
  110644. }
  110645. });
  110646. });
  110647. };
  110648. return KHR_draco_mesh_compression;
  110649. }(GLTF2.GLTFLoaderExtension));
  110650. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  110651. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  110652. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110653. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110654. })(BABYLON || (BABYLON = {}));
  110655. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  110656. var BABYLON;
  110657. (function (BABYLON) {
  110658. var GLTF2;
  110659. (function (GLTF2) {
  110660. var Extensions;
  110661. (function (Extensions) {
  110662. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  110663. var NAME = "KHR_materials_pbrSpecularGlossiness";
  110664. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  110665. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  110666. function KHR_materials_pbrSpecularGlossiness() {
  110667. var _this = _super !== null && _super.apply(this, arguments) || this;
  110668. _this.name = NAME;
  110669. return _this;
  110670. }
  110671. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  110672. var _this = this;
  110673. return this._loadExtensionAsync(context, material, function (context, extension) {
  110674. material._babylonMeshes = material._babylonMeshes || [];
  110675. material._babylonMeshes.push(babylonMesh);
  110676. if (!material._loaded) {
  110677. var promises = new Array();
  110678. var babylonMaterial = _this._loader._createMaterial(material);
  110679. material._babylonMaterial = babylonMaterial;
  110680. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  110681. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  110682. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110683. material._loaded = Promise.all(promises).then(function () { });
  110684. }
  110685. assign(material._babylonMaterial);
  110686. return material._loaded;
  110687. });
  110688. };
  110689. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  110690. var promises = new Array();
  110691. var babylonMaterial = material._babylonMaterial;
  110692. if (properties.diffuseFactor) {
  110693. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  110694. babylonMaterial.alpha = properties.diffuseFactor[3];
  110695. }
  110696. else {
  110697. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110698. }
  110699. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  110700. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  110701. if (properties.diffuseTexture) {
  110702. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  110703. babylonMaterial.albedoTexture = texture;
  110704. }));
  110705. }
  110706. if (properties.specularGlossinessTexture) {
  110707. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  110708. babylonMaterial.reflectivityTexture = texture;
  110709. }));
  110710. babylonMaterial.reflectivityTexture.hasAlpha = true;
  110711. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  110712. }
  110713. this._loader._loadMaterialAlphaProperties(context, material);
  110714. return Promise.all(promises).then(function () { });
  110715. };
  110716. return KHR_materials_pbrSpecularGlossiness;
  110717. }(GLTF2.GLTFLoaderExtension));
  110718. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  110719. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  110720. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110721. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110722. })(BABYLON || (BABYLON = {}));
  110723. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  110724. var BABYLON;
  110725. (function (BABYLON) {
  110726. var GLTF2;
  110727. (function (GLTF2) {
  110728. var Extensions;
  110729. (function (Extensions) {
  110730. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  110731. var NAME = "KHR_lights";
  110732. var LightType;
  110733. (function (LightType) {
  110734. LightType["AMBIENT"] = "ambient";
  110735. LightType["DIRECTIONAL"] = "directional";
  110736. LightType["POINT"] = "point";
  110737. LightType["SPOT"] = "spot";
  110738. })(LightType || (LightType = {}));
  110739. var KHR_lights = /** @class */ (function (_super) {
  110740. __extends(KHR_lights, _super);
  110741. function KHR_lights() {
  110742. var _this = _super !== null && _super.apply(this, arguments) || this;
  110743. _this.name = NAME;
  110744. return _this;
  110745. }
  110746. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  110747. var _this = this;
  110748. return this._loadExtensionAsync(context, scene, function (context, extension) {
  110749. var promise = _this._loader._loadSceneAsync(context, scene);
  110750. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  110751. if (light.type !== LightType.AMBIENT) {
  110752. throw new Error(context + ": Only ambient lights are allowed on a scene");
  110753. }
  110754. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  110755. return promise;
  110756. });
  110757. };
  110758. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  110759. var _this = this;
  110760. return this._loadExtensionAsync(context, node, function (context, extension) {
  110761. var promise = _this._loader._loadNodeAsync(context, node);
  110762. var babylonLight;
  110763. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  110764. var name = node._babylonMesh.name;
  110765. switch (light.type) {
  110766. case LightType.AMBIENT: {
  110767. throw new Error(context + ": Ambient lights are not allowed on a node");
  110768. }
  110769. case LightType.DIRECTIONAL: {
  110770. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  110771. break;
  110772. }
  110773. case LightType.POINT: {
  110774. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  110775. break;
  110776. }
  110777. case LightType.SPOT: {
  110778. var spotLight = light;
  110779. // TODO: support inner and outer cone angles
  110780. //const innerConeAngle = spotLight.innerConeAngle || 0;
  110781. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  110782. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  110783. break;
  110784. }
  110785. default: {
  110786. throw new Error(context + ": Invalid light type (" + light.type + ")");
  110787. }
  110788. }
  110789. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  110790. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  110791. babylonLight.parent = node._babylonMesh;
  110792. return promise;
  110793. });
  110794. };
  110795. Object.defineProperty(KHR_lights.prototype, "_lights", {
  110796. get: function () {
  110797. var extensions = this._loader._gltf.extensions;
  110798. if (!extensions || !extensions[this.name]) {
  110799. throw new Error("#/extensions: '" + this.name + "' not found");
  110800. }
  110801. var extension = extensions[this.name];
  110802. return extension.lights;
  110803. },
  110804. enumerable: true,
  110805. configurable: true
  110806. });
  110807. return KHR_lights;
  110808. }(GLTF2.GLTFLoaderExtension));
  110809. Extensions.KHR_lights = KHR_lights;
  110810. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  110811. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110812. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110813. })(BABYLON || (BABYLON = {}));
  110814. //# sourceMappingURL=KHR_lights.js.map
  110815. return BABYLON;
  110816. });
  110817. /***/ }),
  110818. /* 33 */
  110819. /***/ (function(module, exports, __webpack_require__) {
  110820. /*!
  110821. * PEP v0.4.3 | https://github.com/jquery/PEP
  110822. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  110823. */
  110824. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define(b):a.PointerEventsPolyfill=b()}(this,function(){"use strict";function a(a,b){b=b||Object.create(null);var c=document.createEvent("Event");c.initEvent(a,b.bubbles||!1,b.cancelable||!1);
  110825. // define inherited MouseEvent properties
  110826. // skip bubbles and cancelable since they're set above in initEvent()
  110827. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  110828. // Spec requires that pointers without pressure specified use 0.5 for down
  110829. // state and 0 for up state.
  110830. var f=0;
  110831. // add x/y properties aliased to clientX/Y
  110832. // define the properties of the PointerEvent interface
  110833. return f=b.pressure&&c.buttons?b.pressure:c.buttons?.5:0,c.x=c.clientX,c.y=c.clientY,c.pointerId=b.pointerId||0,c.width=b.width||0,c.height=b.height||0,c.pressure=f,c.tiltX=b.tiltX||0,c.tiltY=b.tiltY||0,c.twist=b.twist||0,c.tangentialPressure=b.tangentialPressure||0,c.pointerType=b.pointerType||"",c.hwTimestamp=b.hwTimestamp||0,c.isPrimary=b.isPrimary||!1,c}function b(){this.array=[],this.size=0}function c(a,b,c,d){this.addCallback=a.bind(d),this.removeCallback=b.bind(d),this.changedCallback=c.bind(d),A&&(this.observer=new A(this.mutationWatcher.bind(this)))}function d(a){return"body /shadow-deep/ "+e(a)}function e(a){return'[touch-action="'+a+'"]'}function f(a){return"{ -ms-touch-action: "+a+"; touch-action: "+a+"; }"}function g(){if(F){D.forEach(function(a){String(a)===a?(E+=e(a)+f(a)+"\n",G&&(E+=d(a)+f(a)+"\n")):(E+=a.selectors.map(e)+f(a.rule)+"\n",G&&(E+=a.selectors.map(d)+f(a.rule)+"\n"))});var a=document.createElement("style");a.textContent=E,document.head.appendChild(a)}}function h(){
  110834. // only activate if this platform does not have pointer events
  110835. if(!window.PointerEvent){if(window.PointerEvent=a,window.navigator.msPointerEnabled){var b=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:b,enumerable:!0}),u.registerSource("ms",_)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),u.registerSource("mouse",N),void 0!==window.ontouchstart&&u.registerSource("touch",V);u.register(document)}}function i(a){if(!u.pointermap.has(a)){var b=new Error("InvalidPointerId");throw b.name="InvalidPointerId",b}}function j(a){for(var b=a.parentNode;b&&b!==a.ownerDocument;)b=b.parentNode;if(!b){var c=new Error("InvalidStateError");throw c.name="InvalidStateError",c}}function k(a){var b=u.pointermap.get(a);return 0!==b.buttons}function l(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:W},releasePointerCapture:{value:X},hasPointerCapture:{value:Y}})}/**
  110836. * This is the constructor for new PointerEvents.
  110837. *
  110838. * New Pointer Events must be given a type, and an optional dictionary of
  110839. * initialization properties.
  110840. *
  110841. * Due to certain platform requirements, events returned from the constructor
  110842. * identify as MouseEvents.
  110843. *
  110844. * @constructor
  110845. * @param {String} inType The type of the event to create.
  110846. * @param {Object} [inDict] An optional dictionary of initial event properties.
  110847. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  110848. */
  110849. var m=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],n=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],o=window.Map&&window.Map.prototype.forEach,p=o?Map:b;b.prototype={set:function(a,b){return void 0===b?this["delete"](a):(this.has(a)||this.size++,void(this.array[a]=b))},has:function(a){return void 0!==this.array[a]},"delete":function(a){this.has(a)&&(delete this.array[a],this.size--)},get:function(a){return this.array[a]},clear:function(){this.array.length=0,this.size=0},
  110850. // return value, key, map
  110851. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  110852. // MouseEvent
  110853. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  110854. // DOM Level 3
  110855. "buttons",
  110856. // PointerEvent
  110857. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  110858. // event instance
  110859. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  110860. // MouseEvent
  110861. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  110862. // DOM Level 3
  110863. 0,
  110864. // PointerEvent
  110865. 0,0,0,0,0,0,"",0,!1,
  110866. // event instance
  110867. "",null,null,0,0,0,0],s={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},t="undefined"!=typeof SVGElementInstance,u={pointermap:new p,eventMap:Object.create(null),captureInfo:Object.create(null),
  110868. // Scope objects for native events.
  110869. // This exists for ease of testing.
  110870. eventSources:Object.create(null),eventSourceList:[],/**
  110871. * Add a new event source that will generate pointer events.
  110872. *
  110873. * `inSource` must contain an array of event names named `events`, and
  110874. * functions with the names specified in the `events` array.
  110875. * @param {string} name A name for the event source
  110876. * @param {Object} source A new source of platform events.
  110877. */
  110878. registerSource:function(a,b){var c=b,d=c.events;d&&(d.forEach(function(a){c[a]&&(this.eventMap[a]=c[a].bind(c))},this),this.eventSources[a]=c,this.eventSourceList.push(c))},register:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110879. // call eventsource register
  110880. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110881. // call eventsource register
  110882. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  110883. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  110884. return!1}},
  110885. // EVENTS
  110886. down:function(a){a.bubbles=!0,this.fireEvent("pointerdown",a)},move:function(a){a.bubbles=!0,this.fireEvent("pointermove",a)},up:function(a){a.bubbles=!0,this.fireEvent("pointerup",a)},enter:function(a){a.bubbles=!1,this.fireEvent("pointerenter",a)},leave:function(a){a.bubbles=!1,this.fireEvent("pointerleave",a)},over:function(a){a.bubbles=!0,this.fireEvent("pointerover",a)},out:function(a){a.bubbles=!0,this.fireEvent("pointerout",a)},cancel:function(a){a.bubbles=!0,this.fireEvent("pointercancel",a)},leaveOut:function(a){this.out(a),this.propagate(a,this.leave,!1)},enterOver:function(a){this.over(a),this.propagate(a,this.enter,!0)},
  110887. // LISTENER LOGIC
  110888. eventHandler:function(a){
  110889. // This is used to prevent multiple dispatch of pointerevents from
  110890. // platform events. This can happen when two elements in different scopes
  110891. // are set up to create pointer events, which is relevant to Shadow DOM.
  110892. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  110893. // set up event listeners
  110894. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  110895. // remove event listeners
  110896. unlisten:function(a,b){b.forEach(function(b){this.removeEvent(a,b)},this)},addEvent:/*scope.external.addEvent || */function(a,b){a.addEventListener(b,this.boundHandler)},removeEvent:/*scope.external.removeEvent || */function(a,b){a.removeEventListener(b,this.boundHandler)},
  110897. // EVENT CREATION AND TRACKING
  110898. /**
  110899. * Creates a new Event of type `inType`, based on the information in
  110900. * `inEvent`.
  110901. *
  110902. * @param {string} inType A string representing the type of event to create
  110903. * @param {Event} inEvent A platform event with a target
  110904. * @return {Event} A PointerEvent of type `inType`
  110905. */
  110906. makeEvent:function(b,c){
  110907. // relatedTarget must be null if pointer is captured
  110908. this.captureInfo[c.pointerId]&&(c.relatedTarget=null);var d=new a(b,c);return c.preventDefault&&(d.preventDefault=c.preventDefault),d._target=d._target||c.target,d},
  110909. // make and dispatch an event in one call
  110910. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  110911. * Returns a snapshot of inEvent, with writable properties.
  110912. *
  110913. * @param {Event} inEvent An event that contains properties to copy.
  110914. * @return {Object} An object containing shallow copies of `inEvent`'s
  110915. * properties.
  110916. */
  110917. cloneEvent:function(a){for(var b,c=Object.create(null),d=0;d<q.length;d++)b=q[d],c[b]=a[b]||r[d],
  110918. // Work around SVGInstanceElement shadow tree
  110919. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  110920. // This is the behavior implemented by Firefox.
  110921. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  110922. // keep the semantics of preventDefault
  110923. return a.preventDefault&&(c.preventDefault=function(){a.preventDefault()}),c},getTarget:function(a){var b=this.captureInfo[a.pointerId];return b?a._target!==b&&a.type in s?void 0:b:a._target},propagate:function(a,b,c){
  110924. // Order of conditions due to document.contains() missing in IE.
  110925. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  110926. // Touch: Do not propagate if node is detached.
  110927. if(e.push(d),d=d.parentNode,!d)return;c&&e.reverse(),e.forEach(function(c){a.target=c,b.call(this,a)},this)},setCapture:function(b,c,d){this.captureInfo[b]&&this.releaseCapture(b,d),this.captureInfo[b]=c,this.implicitRelease=this.releaseCapture.bind(this,b,d),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease);var e=new a("gotpointercapture");e.pointerId=b,e._target=c,d||this.asyncDispatchEvent(e)},releaseCapture:function(b,c){var d=this.captureInfo[b];if(d){this.captureInfo[b]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease);var e=new a("lostpointercapture");e.pointerId=b,e._target=d,c||this.asyncDispatchEvent(e)}},/**
  110928. * Dispatches the event to its target.
  110929. *
  110930. * @param {Event} inEvent The event to be dispatched.
  110931. * @return {Boolean} True if an event handler returns true, false otherwise.
  110932. */
  110933. dispatchEvent:/*scope.external.dispatchEvent || */function(a){var b=this.getTarget(a);if(b)return b.dispatchEvent(a)},asyncDispatchEvent:function(a){requestAnimationFrame(this.dispatchEvent.bind(this,a))}};u.boundHandler=u.eventHandler.bind(u);var v={shadow:function(a){if(a)return a.shadowRoot||a.webkitShadowRoot},canTarget:function(a){return a&&Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);if(this.canTarget(b))return b},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c&&(b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){if(a){var d,e,f=a.elementFromPoint(b,c);for(
  110934. // is element a shadow host?
  110935. e=this.targetingShadow(f);e;){if(
  110936. // find the the element inside the shadow root
  110937. d=e.elementFromPoint(b,c)){
  110938. // shadowed element may contain a shadow root
  110939. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  110940. // check for older shadows
  110941. e=this.olderShadow(e)}
  110942. // light dom element is the target
  110943. return f}},owner:function(a){
  110944. // walk up until you hit the shadow root or document
  110945. for(var b=a;b.parentNode;)b=b.parentNode;
  110946. // the owner element is expected to be a Document or ShadowRoot
  110947. return b.nodeType!==Node.DOCUMENT_NODE&&b.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(b=document),b},findTarget:function(a){var b=a.clientX,c=a.clientY,d=this.owner(a.target);
  110948. // if x, y is not in this root, fall back to document search
  110949. return d.elementFromPoint(b,c)||(d=document),this.searchRoot(d,b,c)}},w=Array.prototype.forEach.call.bind(Array.prototype.forEach),x=Array.prototype.map.call.bind(Array.prototype.map),y=Array.prototype.slice.call.bind(Array.prototype.slice),z=Array.prototype.filter.call.bind(Array.prototype.filter),A=window.MutationObserver||window.WebKitMutationObserver,B="[touch-action]",C={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};c.prototype={watchSubtree:function(a){
  110950. // Only watch scopes that can target find, as these are top-level.
  110951. // Otherwise we can see duplicate additions and removals that add noise.
  110952. //
  110953. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  110954. // a removal without an insertion when a node is redistributed among
  110955. // shadows. Since it all ends up correct in the document, watching only
  110956. // the document will yield the correct mutations to watch.
  110957. this.observer&&v.canTarget(a)&&this.observer.observe(a,C)},enableOnSubtree:function(a){this.watchSubtree(a),a===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(a)},installNewSubtree:function(a){w(this.findElements(a),this.addElement,this)},findElements:function(a){return a.querySelectorAll?a.querySelectorAll(B):[]},removeElement:function(a){this.removeCallback(a)},addElement:function(a){this.addCallback(a)},elementChanged:function(a,b){this.changedCallback(a,b)},concatLists:function(a,b){return a.concat(y(b))},
  110958. // register all touch-action = none nodes on document load
  110959. installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(a){return a.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(a){
  110960. // find children with touch-action
  110961. var b=x(a,this.findElements,this);
  110962. // flatten the list
  110963. // make sure the added nodes are accounted for
  110964. return b.push(z(a,this.isElement)),b.reduce(this.concatLists,[])},mutationWatcher:function(a){a.forEach(this.mutationHandler,this)},mutationHandler:function(a){if("childList"===a.type){var b=this.flattenMutationTree(a.addedNodes);b.forEach(this.addElement,this);var c=this.flattenMutationTree(a.removedNodes);c.forEach(this.removeElement,this)}else"attributes"===a.type&&this.elementChanged(a.target,a.oldValue)}};var D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],E="",F=window.PointerEvent||window.MSPointerEvent,G=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,H=u.pointermap,I=25,J=[1,4,2,8,16],K=!1;try{K=1===new MouseEvent("test",{buttons:1}).buttons}catch(L){}
  110965. // handler block for native mouse events
  110966. var M,N={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},lastTouches:[],
  110967. // collide with the global mouse listener
  110968. isEventSimulatedFromTouch:function(a){for(var b,c=this.lastTouches,d=a.clientX,e=a.clientY,f=0,g=c.length;f<g&&(b=c[f]);f++){
  110969. // simulated mouse events will be swallowed near a primary touchend
  110970. var h=Math.abs(d-b.x),i=Math.abs(e-b.y);if(h<=I&&i<=I)return!0}},prepareEvent:function(a){var b=u.cloneEvent(a),c=b.preventDefault;return b.preventDefault=function(){a.preventDefault(),c()},b.pointerId=this.POINTER_ID,b.isPrimary=!0,b.pointerType=this.POINTER_TYPE,b},prepareButtonsForMove:function(a,b){var c=H.get(this.POINTER_ID);
  110971. // Update buttons state after possible out-of-document mouseup.
  110972. 0!==b.which&&c?a.buttons=c.buttons:a.buttons=0,b.buttons=a.buttons},mousedown:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);K||(c.buttons=J[c.button],b&&(c.buttons|=b.buttons),a.buttons=c.buttons),H.set(this.POINTER_ID,a),b&&0!==b.buttons?u.move(c):u.down(c)}},mousemove:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.move(b)}},mouseup:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);if(!K){var d=J[c.button];
  110973. // Produces wrong state of buttons in Browsers without `buttons` support
  110974. // when a mouse button that was pressed outside the document is released
  110975. // inside and other buttons are still pressed down.
  110976. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  110977. // Support: Firefox <=44 only
  110978. // FF Ubuntu includes the lifted button in the `buttons` property on
  110979. // mouseup.
  110980. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  110981. c.buttons&=~J[c.button],0===c.buttons?u.up(c):u.move(c)}},mouseover:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.enterOver(b)}},mouseout:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,u.leaveOut(b)}},cancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.deactivateMouse()},deactivateMouse:function(){H["delete"](this.POINTER_ID)}},O=u.captureInfo,P=v.findTarget.bind(v),Q=v.allShadows.bind(v),R=u.pointermap,S=2500,T=200,U="touch-action",V={events:["touchstart","touchmove","touchend","touchcancel"],register:function(a){M.enableOnSubtree(a)},unregister:function(){},elementAdded:function(a){var b=a.getAttribute(U),c=this.touchActionToScrollType(b);c&&(a._scrollType=c,u.listen(a,this.events),
  110982. // set touch-action on shadows as well
  110983. Q(a).forEach(function(a){a._scrollType=c,u.listen(a,this.events)},this))},elementRemoved:function(a){a._scrollType=void 0,u.unlisten(a,this.events),
  110984. // remove touch-action from shadow
  110985. Q(a).forEach(function(a){a._scrollType=void 0,u.unlisten(a,this.events)},this)},elementChanged:function(a,b){var c=a.getAttribute(U),d=this.touchActionToScrollType(c),e=this.touchActionToScrollType(b);
  110986. // simply update scrollType if listeners are already established
  110987. d&&e?(a._scrollType=d,Q(a).forEach(function(a){a._scrollType=d},this)):e?this.elementRemoved(a):d&&this.elementAdded(a)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(a){var b=a,c=this.scrollTypes;return"none"===b?"none":b===c.XSCROLLER?"X":b===c.YSCROLLER?"Y":c.SCROLLER.exec(b)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(a){return this.firstTouch===a.identifier},setPrimaryTouch:function(a){
  110988. // set primary touch if there no pointers, or the only pointer is the mouse
  110989. (0===R.size||1===R.size&&R.has(1))&&(this.firstTouch=a.identifier,this.firstXY={X:a.clientX,Y:a.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(a){a.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var a=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(a,T)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(a){var b=0;return"touchstart"!==a&&"touchmove"!==a||(b=1),b},touchToPointer:function(a){var b=this.currentTouchEvent,c=u.cloneEvent(a),d=c.pointerId=a.identifier+2;c.target=O[d]||P(c),c.bubbles=!0,c.cancelable=!0,c.detail=this.clickCount,c.button=0,c.buttons=this.typeToButtons(b.type),c.width=2*(a.radiusX||a.webkitRadiusX||0),c.height=2*(a.radiusY||a.webkitRadiusY||0),c.pressure=a.force||a.webkitForce||.5,c.isPrimary=this.isPrimaryTouch(a),c.pointerType=this.POINTER_TYPE,
  110990. // forward modifier keys
  110991. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  110992. // forward touch preventDefaults
  110993. var e=this;return c.preventDefault=function(){e.scrolling=!1,e.firstXY=null,b.preventDefault()},c},processTouches:function(a,b){var c=a.changedTouches;this.currentTouchEvent=a;for(var d,e=0;e<c.length;e++)d=c[e],b.call(this,this.touchToPointer(d))},
  110994. // For single axis scrollers, determines whether the element should emit
  110995. // pointer events or behave as a scroller
  110996. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  110997. // this element is a touch-action: none, should never scroll
  110998. b=!1;else if("XY"===c)
  110999. // this element should always scroll
  111000. b=!0;else{var d=a.changedTouches[0],e=c,f="Y"===c?"X":"Y",g=Math.abs(d["client"+e]-this.firstXY[e]),h=Math.abs(d["client"+f]-this.firstXY[f]);
  111001. // if delta in the scroll axis > delta other axis, scroll instead of
  111002. // making events
  111003. b=g>=h}return this.firstXY=null,b}},findTouch:function(a,b){for(var c,d=0,e=a.length;d<e&&(c=a[d]);d++)if(c.identifier===b)return!0},
  111004. // In some instances, a touchstart can happen without a touchend. This
  111005. // leaves the pointermap in a broken state.
  111006. // Therefore, on every touchstart, we remove the touches that did not fire a
  111007. // touchend event.
  111008. // To keep state globally consistent, we fire a
  111009. // pointercancel for this "abandoned" touch
  111010. vacuumTouches:function(a){var b=a.touches;
  111011. // pointermap.size should be < tl.length here, as the touchstart has not
  111012. // been processed yet.
  111013. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  111014. // Never remove pointerId == 1, which is mouse.
  111015. // Touch identifiers are 2 smaller than their pointerId, which is the
  111016. // index in pointermap.
  111017. if(1!==d&&!this.findTouch(b,d-2)){var e=a.out;c.push(e)}},this),c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a),this.setPrimaryTouch(a.changedTouches[0]),this.dedupSynthMouse(a),this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){R.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}),u.enterOver(a),u.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=a,c=R.get(b.pointerId);
  111018. // a finger drifted off the screen, ignore it
  111019. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  111020. // recover from retargeting by shadow
  111021. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  111022. // clean up case when finger leaves the screen
  111023. b.target=e,b.relatedTarget=null,this.cancelOut(b))),c.out=b,c.outTarget=b.target}},touchend:function(a){this.dedupSynthMouse(a),this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(u.up(a),u.leaveOut(a)),this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){u.cancel(a),u.leaveOut(a),this.cleanUpPointer(a)},cleanUpPointer:function(a){R["delete"](a.pointerId),this.removePrimaryPointer(a)},
  111024. // prevent synth mouse events from creating pointer events
  111025. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  111026. // only the primary finger will synth mouse events
  111027. if(this.isPrimaryTouch(c)){
  111028. // remember x/y of last touch
  111029. var d={x:c.clientX,y:c.clientY};b.push(d);var e=function(a,b){var c=a.indexOf(b);c>-1&&a.splice(c,1)}.bind(null,b,d);setTimeout(e,S)}}};M=new c(V.elementAdded,V.elementRemoved,V.elementChanged,V);var W,X,Y,Z=u.pointermap,$=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,_={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(a){var b=a;return $&&(b=u.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);var b=this.prepareEvent(a);u.down(b)},MSPointerMove:function(a){var b=this.prepareEvent(a);u.move(b)},MSPointerUp:function(a){var b=this.prepareEvent(a);u.up(b),this.cleanup(a.pointerId)},MSPointerOut:function(a){var b=this.prepareEvent(a);u.leaveOut(b)},MSPointerOver:function(a){var b=this.prepareEvent(a);u.enterOver(b)},MSPointerCancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){var b=u.makeEvent("lostpointercapture",a);u.dispatchEvent(b)},MSGotPointerCapture:function(a){var b=u.makeEvent("gotpointercapture",a);u.dispatchEvent(b)}},aa=window.navigator;aa.msPointerEnabled?(W=function(a){i(a),j(this),k(a)&&(u.setCapture(a,this,!0),this.msSetPointerCapture(a))},X=function(a){i(a),u.releaseCapture(a,!0),this.msReleasePointerCapture(a)}):(W=function(a){i(a),j(this),k(a)&&u.setCapture(a,this)},X=function(a){i(a),u.releaseCapture(a)}),Y=function(a){return!!u.captureInfo[a]},g(),h(),l();var ba={dispatcher:u,Installer:c,PointerEvent:a,PointerMap:p,targetFinding:v};return ba});
  111030. /***/ }),
  111031. /* 34 */
  111032. /***/ (function(module, exports, __webpack_require__) {
  111033. "use strict";
  111034. Object.defineProperty(exports, "__esModule", { value: true });
  111035. var defaultViewer_1 = __webpack_require__(4);
  111036. var mappers_1 = __webpack_require__(1);
  111037. function InitTags(selector) {
  111038. if (selector === void 0) { selector = 'babylon'; }
  111039. var elements = document.querySelectorAll(selector);
  111040. for (var i = 0; i < elements.length; ++i) {
  111041. var element = elements.item(i);
  111042. var configMapper = mappers_1.mapperManager.getMapper('dom');
  111043. var config = configMapper.map(element);
  111044. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  111045. }
  111046. }
  111047. exports.InitTags = InitTags;
  111048. /***/ })
  111049. /******/ ]);
  111050. return BabylonViewer;
  111051. });